/
main.go
354 lines (316 loc) · 7.77 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package main
import (
"bytes"
"flag"
"fmt"
"hash/crc32"
"io/ioutil"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
var (
flagdebug = flag.Bool("d", true, "show debug output")
flagdir = flag.String("dir", "cwd", "directory to scan. default is current working directory (cwd)")
flagtarget = flag.String("tar", "cwd", "directory to extract to. default is current working directory (cwd)")
flagefr = flag.String("rem", "", "extra files to remove (i.e. *.nfo, *.sfv), default does not remove extras")
flagminsize = flag.Int64("min", 200000000, "minimum file size to include in scan. default is 200MB") // 3MB
flagtest = flag.Bool("test", false, "tests process, doesn't delete files.")
rf rcdFlags
extractext = []string{".rar", ".zip", ".7z"}
whitelist = []string{
".mkv", ".mp4", ".avi",
".bup", ".ifo", ".vob",
}
)
func main() {
flag.Parse()
// Print the logo :P
printLogo()
rf.Min = flagInt(flagminsize)
// Root folder to scan
fpSAbs, _ := filepath.Abs(flagString(flagdir))
rf.Dir = fpSAbs
if flagString(flagdir) == "cwd" {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
rf.Dir = dir
}
// Root folder to extract to
fpTAbs, _ := filepath.Abs(flagString(flagtarget))
rf.Target = fpTAbs
if flagString(flagtarget) == "cwd" {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
rf.Target = dir
}
if flagBool(flagtest) {
fmt.Println("**Test mode enabled!")
}
fmt.Printf("Scanning directory: %s\n", rf.Dir)
fmt.Println("_____________________")
ok := test7zip()
if !ok {
fmt.Println("7zip has not been found, verify 7-Zip is installed and in the PATH env variable.")
return
}
fmt.Println("_____________________")
i := folderWalk(rf.Dir)
if i < 1 {
fmt.Println("No archives found.")
}
}
func flagString(fs *string) string {
return fmt.Sprint(*fs)
}
func flagInt(fi *int64) int64 {
return int64(*fi)
}
func flagBool(fb *bool) bool {
return bool(*fb)
}
func folderWalk(path string) (i int64) {
i = 0
var err = filepath.Walk(path, func(path string, _ os.FileInfo, _ error) error {
for _, x := range extractext {
if filepath.Ext(path) == x && !rarPartXX(path) {
var ok bool
ok = testcrc32(path)
if ok == false {
fmt.Println("Test Failed - skipping archive")
fmt.Println("_________")
continue
}
ok = testarchive(path)
if ok == false {
fmt.Println("Test Failed - skipping archive")
fmt.Println("_________")
continue
}
ok = extract(path, rf.Target)
if ok == false {
printDebug("Extract failed %s\n", "")
} else {
i = i + 1
cleanPath(path)
}
fmt.Println("_________")
}
}
return nil
})
if err != nil {
printDebug("er: %+v\n", err)
}
return
}
func test7zip() (ok bool) {
ok = true
printDebug("Testing: 7-Zip%s\n", "")
out, err := exec.Command("7z").Output()
if err != nil {
log.Fatal(err)
}
if !bytes.Contains(out, []byte("7-Zip")) {
fmt.Println("7-Zip not found.")
ok = false
}
if ok {
fmt.Println("7-Zip found")
}
return
}
func testarchive(path string) (ok bool) {
ok = true
printDebug("Testing: %s\n", path)
out, err := exec.Command("7z", "t", path).Output()
if err != nil {
if strings.Contains(err.Error(), "CRC") {
fmt.Println("err: ", err)
ok = false
}
}
fmt.Println(string(out))
if bytes.Contains(out, []byte("CRC")) && !bytes.Contains(out, []byte("Everything is Ok")) {
fmt.Println("ERROR: CRC Failed")
fmt.Println(path)
ok = false
}
if ok {
fmt.Println("Archive Test PASSED")
}
return
}
func testcrc32(path string) (ok bool) {
ok = true
d := filepath.Dir(path)
var err = filepath.Walk(d, func(fpath string, f os.FileInfo, _ error) error {
if filepath.Ext(fpath) == ".sfv" {
printDebug("Found sfv\n%s\n", fpath)
dat, err := ioutil.ReadFile(fpath)
if err != nil {
return err
}
temp := strings.Split(string(dat), "\n")
for i, x := range temp {
if math.Remainder(float64(i), 25) == 0 {
fmt.Println("")
}
if len(x) < 1 {
continue
}
if string(x[0]) == ";" {
continue
}
result := strings.Fields(x)
if len(result) > 0 {
rcrc32 := result[len(result)-1]
h, err := getHash(d + "\\" + result[0])
if err != nil {
//fmt.Println(err)
}
s := strconv.FormatInt(int64(h), 16)
s = strings.TrimLeft(s, "0")
rcrc32 = strings.TrimLeft(rcrc32, "0")
s = strings.ToUpper(s)
rcrc32 = strings.ToUpper(rcrc32)
if s != rcrc32 {
ok = false
printDebug("CRC does not match:\n%s\n%s - %s\n", result[0], rcrc32, s)
} else {
printDebug("%s", ".")
}
}
}
printDebug("%s\n", "")
}
return nil
})
if err != nil {
ok = false
fmt.Println(err)
}
return
}
func getHash(filename string) (uint32, error) {
bs, err := ioutil.ReadFile(filename)
if err != nil {
return 0, err
}
h := crc32.NewIEEE()
h.Write(bs)
bs = nil
return h.Sum32(), nil
}
func extract(path, destpath string) (ok bool) {
ok = true
d := filepath.Dir(destpath)
printDebug("Extracting: %s\nDestination: %s\n", path, d)
cmd := exec.Command("7z", "x", path, "-o"+d, "-y")
if err := cmd.Run(); err != nil {
// error code 2 means Fatal Error from 7zip executable
// possible cause could be a missing file in a multipart archive
if err.Error() == "exit status 2" {
printDebug("Extration error: %+v\n", err)
ok = false
}
}
if !ok {
printDebug("Extraction failed %s\n", "")
} else {
printDebug("Extraction complete %s\n", "")
}
return
}
func cleanPath(path string) {
wd := filepath.Dir(path)
printDebug("Cleaning: %s\n", wd)
var err = filepath.Walk(wd, func(fpath string, f os.FileInfo, _ error) error {
keepfile := false
for _, x := range whitelist {
// Check if file extension is in the keeper list
if filepath.Ext(fpath) == x {
keepfile = true
}
// Check if file size > min, prevent accidental deletion of wanted files
if f.Size() > rf.Min {
keepfile = true
}
}
// Don't delete root folder
if fpath == wd {
keepfile = true
}
// Test mode to prevent file deletion
if flagBool(flagtest) {
keepfile = true
printDebug("Testing - %s\n", "deletion skipped")
}
// Delete file if it doesnt match any of the keeper rules
if keepfile == false {
printDebug("Deleting: %s\n", fpath)
err := os.Remove(fpath)
if err != nil {
printDebug("File deletion error: %+v\n", err)
}
}
return nil
})
if err != nil {
printDebug("Clean err: %+v\n", err)
}
}
func rarPartXX(path string) bool {
if !strings.HasSuffix(path, ".rar") {
return false
}
if strings.HasSuffix(path, ".part01.rar") || strings.HasSuffix(path, ".part1.rar") {
return false
}
if strings.HasSuffix(path, ".rar") && !strings.Contains(path, ".part") {
return false
}
return true
}
// Check err
func check(e error) {
if e != nil {
panic(e)
}
}
// Only print debug output if the debug flag is true
func printDebug(format string, vars ...interface{}) {
if *flagdebug {
if vars[0] == nil {
fmt.Println(format)
return
}
fmt.Printf(format, vars...)
}
}
// Hold flag data
type rcdFlags struct {
Dir string
Target string
Debug bool
ExtraFilesToRemove string
Min int64
}
// Print the logo, obviously
func printLogo() {
fmt.Println("██████╗ ██████╗██████╗")
fmt.Println("██╔══██╗██╔════╝██╔══██╗")
fmt.Println("██████╔╝██║ ██║ ██║")
fmt.Println("██╔══██╗██║ ██║ ██║")
fmt.Println("██║ ██║╚██████╗██████╔╝")
fmt.Println("╚═╝ ╚═╝ ╚═════╝╚═════╝ rarcursed")
fmt.Println("")
}