-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathutils.go
251 lines (212 loc) · 7.2 KB
/
utils.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
package main
import (
"fmt"
"log/slog"
"math/rand"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/k0kubun/go-ansi"
"github.com/schollz/progressbar/v3"
)
var allFileURLs []string
func downloadFiles(outputDir, filePath string, fileNames, allowExtensions []string, downloadNoExt bool, numThreads int, randomize bool) {
filenameWithExt := filepath.Base(filePath)
dirName := strings.TrimSuffix(filenameWithExt, filepath.Ext(filenameWithExt))
outPath := filepath.Join(outputDir, "inis", dirName)
// Ensure the output directory exists for inis
if err := os.MkdirAll(outPath, os.ModePerm); err != nil {
slog.Error(fmt.Sprintf("Error creating base output directory: %v\n", err))
return
}
outPathFilesBase := filepath.Join(outputDir, "files")
// Ensure the output directory exists for files
if err := os.MkdirAll(outPathFilesBase, os.ModePerm); err != nil {
slog.Error(fmt.Sprintf("Error creating base output directory: %v\n", err))
return
}
// Create a wait group to wait for all goroutines to finish
var wg sync.WaitGroup
wg.Add(len(fileNames))
// Create a channel to limit the number of concurrent downloads
semaphore := make(chan struct{}, numThreads)
if randomize {
randomizeStrings(fileNames)
}
// Iterate over the filenames and download the files
for _, filename := range fileNames {
filename = strings.ReplaceAll(filename, "\\", "/")
if strings.Contains(filename, "/") {
dir := filepath.Dir(filename)
if err := os.MkdirAll(filepath.Join(outPath, dir), os.ModePerm); err != nil {
slog.Error(fmt.Sprintf("Error creating base output directory: %v\n", err))
return
}
}
wanted, outPathFiles := fileWanted(allowExtensions, downloadNoExt, filename, outputDir)
if !wanted {
wg.Done()
continue
}
// Add an empty struct to the semaphore channel to "take up" one slot/thread
semaphore <- struct{}{}
go downloadINIAndFile(outPath, outPathFiles, filename, dirName, &wg, semaphore)
}
wg.Wait()
}
// Helper function to check if two slices of bytes are equal
func bytesEqual(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func extractFileName(href string) string {
// Split the URL by '/'
parts := strings.Split(href, "/")
// Get the last part of the URL
lastPart := parts[len(parts)-1]
// Remove any leading or trailing spaces
trimmedPart := strings.TrimSpace(lastPart)
return trimmedPart
}
func randomizeStrings(strings []string) {
// Create a new source for random numbers
source := rand.NewSource(time.Now().UnixNano())
random := rand.New(source)
// Randomize the order of the slice using sort.Slice
sort.Slice(strings, func(i, j int) bool {
return random.Intn(2) == 0
})
}
func extractURLs(fileDirectoryURL string) ([]string, []string) {
html, err := getURL(fileDirectoryURL)
if err != nil {
return nil, nil
}
var fileURLs []string
var dirURLs []string
// Regular expression pattern to match URLs
urlPattern := `\d+ <a href="(http://[^"]+)">`
// Regular expression pattern to match directory URLs
dirPattern := `<dir> <a href="(http://[^"]+)">`
// Find all URLs
urls := regexp.MustCompile(urlPattern).FindAllStringSubmatch(html, -1)
for _, url := range urls {
fileURLs = append(fileURLs, url[1])
}
// Find all directory URLs
doubleDirURLs := regexp.MustCompile(dirPattern).FindAllStringSubmatch(html, -1)
for _, url := range doubleDirURLs {
dirURLs = append(dirURLs, url[1])
}
return fileURLs, dirURLs
}
func getAllFileURLsFromDirNames(dataLibFiles []string, numThreads int, randomize bool) []string {
bar := progressbar.NewOptions(-1,
progressbar.OptionSetWriter(ansi.NewAnsiStdout()),
progressbar.OptionEnableColorCodes(true),
progressbar.OptionShowBytes(false),
progressbar.OptionShowCount(),
progressbar.OptionShowElapsedTimeOnFinish(),
progressbar.OptionSetWidth(30),
progressbar.OptionSetDescription("[cyan][1/2][reset] Getting file URLs"),
progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]=[reset]",
SaucerHead: "[green]>[reset]",
SaucerPadding: " ",
BarStart: "[",
BarEnd: "]",
}))
// Create a wait group to wait for all goroutines to finish
var wg sync.WaitGroup
wg.Add(len(dataLibFiles))
// Create a mutex for file appending
mu := &sync.Mutex{}
// Create a channel to limit the number of concurrent downloads
semaphore := make(chan struct{}, numThreads)
if randomize {
randomizeStrings(dataLibFiles)
}
for _, dataLibFile := range dataLibFiles {
// Skip INI files
if strings.HasSuffix(dataLibFile, ".INI") {
wg.Done()
continue
}
var fileDirectoryURL string
if !strings.Contains(dataLibFile, "http") {
fileDirectoryURL = fmt.Sprintf("%s/SMS_DP_SMSPKG$/%s", urlBase, dataLibFile)
} else {
fileDirectoryURL = dataLibFile
}
// Add an empty struct to the semaphore channel to "take up" one slot/thread
semaphore <- struct{}{}
go getFilesFromDirNames(fileDirectoryURL, bar, &wg, semaphore, mu)
}
wg.Wait()
bar.Finish()
return allFileURLs
}
func getFilesFromDirNames(fileDirectoryURL string, bar *progressbar.ProgressBar, wg *sync.WaitGroup, semaphore chan struct{}, mu *sync.Mutex) {
fileURLs, dirURLs := extractURLs(fileDirectoryURL)
bar.Add(len(fileURLs))
mu.Lock()
allFileURLs = append(allFileURLs, fileURLs...)
mu.Unlock()
// Read one struct from the semaphore channel to "let go" of one slot/thread
<-semaphore
if len(dirURLs) > 0 {
slog.Debug(fmt.Sprintf("Found %d directories in %s", len(dirURLs), fileDirectoryURL))
for _, dirURL := range dirURLs {
wg.Add(1)
// Add an empty struct to the semaphore channel to "take up" one slot/thread
semaphore <- struct{}{}
getFilesFromDirNames(dirURL, bar, wg, semaphore, mu)
}
}
// If we "Done()" before the Add it the wg could hit zero and then an Add could run and panic the Wait()
wg.Done()
}
func fileWanted(allowExtensions []string, downloadNoExt bool, filename string, outputDir string) (bool, string) {
var outPathFiles string
fileSuffix := filepath.Ext(filename)
// Remove the leading dot (.) from the file suffix
if len(fileSuffix) > 1 {
fileSuffix = fileSuffix[1:]
if allowExtensions != nil && !slices.Contains(allowExtensions, "all") && !slices.Contains(allowExtensions, fileSuffix) {
slog.Debug(fmt.Sprintf("Skipping %s: %s not wanted", filename, fileSuffix))
return false, ""
}
outPathFiles = filepath.Join(outputDir, "files", fileSuffix)
// Ensure the output directory exists for files
if err := os.MkdirAll(outPathFiles, os.ModePerm); err != nil {
slog.Error(fmt.Sprintf("Error creating file type output directory: %v\n", err))
return false, ""
}
} else {
if downloadNoExt {
slog.Debug(fmt.Sprintf("File %s has no file extension, downloading it!", filename))
outPathFiles = filepath.Join(outputDir, "files", "UKN")
// Ensure the output directory exists for files
if err := os.MkdirAll(outPathFiles, os.ModePerm); err != nil {
slog.Error(fmt.Sprintf("Error creating file type output directory: %v\n", err))
return false, ""
}
} else {
slog.Debug(fmt.Sprintf("File %s has no file extension, and files without extensions are not being kept, skipping", filename))
return false, ""
}
}
return true, outPathFiles
}