-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathFunctions.swift
1959 lines (1854 loc) · 68.9 KB
/
Functions.swift
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import SafariServices
private let logger = USLogger(#fileID)
// helpers
func getRequireLocation() -> URL {
// simple helper in case required code save directory needs to change
return getDocumentsDirectory().appendingPathComponent("require")
}
func dateToMilliseconds(_ date: Date) -> Int {
let since1970 = date.timeIntervalSince1970
return Int(since1970 * 1000)
}
func sanitize(_ str: String) -> String {
// removes invalid filename characters from strings
var sanitized = str
if sanitized.first == "." {
sanitized = "%2" + str.dropFirst()
}
sanitized = sanitized.replacingOccurrences(of: "/", with: "%2F")
sanitized = sanitized.replacingOccurrences(of: ":", with: "%3A")
sanitized = sanitized.replacingOccurrences(of: "\\", with: "%5C")
return sanitized
}
func unsanitize(_ str: String) -> String {
var s = str
if s.hasPrefix("%2") && !s.hasPrefix("%2F") {
s = "." + s.dropFirst(2)
}
if s.removingPercentEncoding != s {
s = s.removingPercentEncoding ?? s
}
return s
}
func normalizeWeight(_ weight: String) -> String {
if let w = Int(weight) {
if w > 999 {
return "999"
} else if w < 1 {
return "1"
} else {
return weight
}
} else {
return "1"
}
}
func getSaveLocation() -> URL? {
#if os(iOS)
if isCurrentDefaultScriptsDirectory() {
logger?.info("\(#function, privacy: .public) - Uninitialized save location")
return nil
}
#endif
let url = Preferences.scriptsDirectoryUrl
logger?.debug("\(#function, privacy: .public) - \(url, privacy: .public)")
return url
}
func openSaveLocation() -> Bool {
#if os(macOS)
guard let saveLocation = getSaveLocation() else {
return false
}
let didStartAccessing = saveLocation.startAccessingSecurityScopedResource()
defer {
if didStartAccessing {saveLocation.stopAccessingSecurityScopedResource()}
}
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: saveLocation.path)
#endif
return true
}
func validateUrl(_ urlString: String) -> Bool {
guard
let parts = jsLikeURL(urlString),
let ptcl = parts["protocol"],
let path = parts["pathname"]
else {
logger?.error("\(#function, privacy: .public) - Invalid URL: \(urlString, privacy: .public)")
return false
}
if
(ptcl != "https:" && ptcl != "http:")
|| (!path.hasSuffix(".css") && !path.hasSuffix(".js"))
{
return false
}
return true
}
func isVersionNewer(_ oldVersion: String, _ newVersion: String) -> Bool {
let oldVersions = oldVersion.components(separatedBy: ".")
let newVersions = newVersion.components(separatedBy: ".")
for (index, version) in newVersions.enumerated() {
let a = Int(version) ?? 0
let oldVersionValue = oldVersions.indices.contains(index) ? oldVersions[index] : "0"
let b = Int(oldVersionValue) ?? 0
if a > b {
return true
}
if a < b {
return false
}
}
return false
}
func isEncoded(_ str: String) -> Bool {
if let decoded = str.removingPercentEncoding {
return decoded != str
}
return false
}
// parser
func parse(_ content: String) -> [String: Any]? {
// returns structured data from content of file
// will fail to parse if metablock or required @name key missing
let pattern = #"(?:(\/\/ ==UserScript==[ \t]*?\r?\n([\S\s]*?)\r?\n\/\/ ==\/UserScript==)([\S\s]*)|(\/\* ==UserStyle==[ \t]*?\r?\n([\S\s]*?)\r?\n==\/UserStyle== \*\/)([\S\s]*))"#
// force try b/c pattern is known to be valid regex
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: content.utf16.count)
// return nil/fail if metablock missing
guard let match = regex.firstMatch(in: content, options: [], range: range) else {
return nil
}
// at this point the text content has passed initial validation, it contains valid metadata
// the metadata can be in userscript or userstyle format, need to check for this and adjust group numbers
// rather than being too strict, text content can precede the opening userscript tag, however it will be ignored
// adjust start index of file content while assigning group numbers to account for any text content preceding opening tag
let contentStartIndex = content.index(content.startIndex, offsetBy: match.range.lowerBound)
var g1, g2, g3:Int
if (content[contentStartIndex..<content.endIndex].starts(with: "//")) {
g1 = 1; g2 = 2; g3 = 3
} else {
g1 = 4; g2 = 5; g3 = 6
}
// can force unwrap metablock since nil check was done above
let metablock = content[Range(match.range(at: g1), in: content)!]
// create var to store separated metadata keys/values
var metadata = [:] as [String: [String]]
// iterate through the possible metadata keys in file
if let metas = Range(match.range(at: g2), in: content) {
// split metadatas by new line
let metaArray = content[metas].split(whereSeparator: \.isNewline)
// loop through metadata lines and populate metadata dictionary
for meta in metaArray {
let p = #"^(?:[ \t]*(?:\/\/)?[ \t]*@)([\w-]+)[ \t]+([^\s]+[^\r\n\t\v\f]*)"#
// this pattern checks for specific keys that won't have values
let p2 = #"^(?:[ \t]*(?:\/\/)?[ \t]*@)(noframes)[ \t]*$"#
// the individual meta string, ie. // @name File Name
let metaString = String(meta).trimmingCharacters(in: .whitespaces)
// force try b/c pattern is known to be valid regex
let re = try! NSRegularExpression(pattern: p, options: [])
let re2 = try! NSRegularExpression(pattern: p2, options: [])
let range = NSRange(location: 0, length: metaString.utf16.count)
// key lines not properly prefixed & without values will be skipped
if let m = re.firstMatch(in: metaString, options: [], range: range) {
// force unwrap key & value since matches regex above
let key = metaString[Range(m.range(at: 1), in: metaString)!]
let value = metaString[Range(m.range(at: 2), in: metaString)!]
if metadata[String(key)] == nil {
// if key does not exist in metadata dict, add it
metadata[String(key)] = []
}
metadata[String(key)]?.append(String(value))
} else if let m2 = re2.firstMatch(in: metaString, options: [], range: range) {
// force unwrap key since matches regex above
let key = metaString[Range(m2.range(at: 1), in: metaString)!]
metadata[String(key)] = []
}
}
}
// return nil/fail if @name key is missing or @name has no value
if metadata["name"] == nil {
return nil
}
// get the code
let code = content[Range(match.range(at: g3), in: content)!]
let trimmedCode = code.trimmingCharacters(in: .whitespacesAndNewlines)
return [
"code": trimmedCode,
"content": content,
"metablock": String(metablock),
"metadata": metadata
]
}
// manifest
struct Manifest: Codable {
var blacklist:[String]
var declarativeNetRequest: [String]
var disabled:[String]
var exclude: [String: [String]]
var excludeMatch: [String: [String]]
var include: [String: [String]]
var match: [String: [String]]
var require: [String: [String]]
var settings: [String: String]
private enum CodingKeys : String, CodingKey {
case blacklist, declarativeNetRequest, disabled, exclude, excludeMatch = "exclude-match", include, match, require, settings
}
}
let defaultSettings = [
"active": "true",
"autoCloseBrackets": "true",
"autoHint": "true",
"descriptions": "true",
"languageCode": Locale.current.languageCode ?? "en",
"lint": "false",
"log": "false",
"sortOrder": "lastModifiedDesc",
"showCount": "true",
"showInvisibles": "true",
"tabSize": "4"
]
func updateManifest(with data: Manifest) -> Bool {
let content = data
let url = getDocumentsDirectory().appendingPathComponent("manifest.json")
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let encoded = try encoder.encode(content)
let fileContent = String(decoding: encoded, as: UTF8.self)
try fileContent.write(to: url, atomically: false, encoding: .utf8)
return true
} catch {
logger?.error("\(#function, privacy: .public) - failed to update manifest: \(error.localizedDescription, privacy: .public)")
return false
}
}
func getManifest() -> Manifest {
let url = getDocumentsDirectory().appendingPathComponent("manifest.json")
if
let content = try? String(contentsOf: url, encoding: .utf8),
let data = content.data(using: .utf8),
let decoded = try? JSONDecoder().decode(Manifest.self, from: Data(data))
{
return decoded
} else {
// manifest missing, improperly formatted or missing key
// create new manifest with default key/vals
let manifest = Manifest(
blacklist: [],
declarativeNetRequest: [],
disabled: [],
exclude: [:],
excludeMatch: [:],
include: [:],
match: [:],
require: [:],
settings: defaultSettings
)
_ = updateManifest(with: manifest)
return manifest
}
}
func updateManifestMatches(_ optionalFilesArray: [[String: Any]] = []) -> Bool {
logger?.info("\(#function, privacy: .public) - started")
// only get all files if files were not provided
var files = [[String: Any]]()
if optionalFilesArray.isEmpty {
guard let getFiles = getAllFiles() else {return false}
files = getFiles
} else {
files = optionalFilesArray
}
var manifest = getManifest()
for file in files {
// can be force unwrapped because getAllFiles didn't return nil
let metadata = file["metadata"] as! [String: [String]]
let filename = file["filename"] as! String
// skip request type userscripts
let runAt = metadata["run-at"]?[0] ?? "document-end"
if runAt == "request" {
continue
}
// populate excludes & matches
var excludeMatched = [String]()
var matched = [String]()
var excluded = [String]()
var included = [String]()
if metadata["exclude-match"] != nil {
excludeMatched.append(contentsOf: metadata["exclude-match"]!)
}
if metadata["match"] != nil {
matched.append(contentsOf: metadata["match"]!)
}
if metadata["include"] != nil {
included.append(contentsOf: metadata["include"]!)
}
if metadata["exclude"] != nil {
excluded.append(contentsOf: metadata["exclude"]!)
}
// if in declarativeNetRequest array, remove it
if manifest.declarativeNetRequest.contains(filename) {
if let index = manifest.declarativeNetRequest.firstIndex(of: filename) {
manifest.declarativeNetRequest.remove(at: index)
} else {
logger?.error("\(#function, privacy: .public) - failed to remove \(filename, privacy: .public) from dNR array")
}
}
// update manifest values
manifest.excludeMatch = updatePatternDict(filename, excludeMatched, manifest.excludeMatch)
manifest.match = updatePatternDict(filename, matched, manifest.match)
manifest.exclude = updatePatternDict(filename, excluded, manifest.exclude)
manifest.include = updatePatternDict(filename, included, manifest.include)
if !updateManifest(with: manifest) {
logger?.error("\(#function, privacy: .public) - failed to update manifest matches")
return false
}
}
logger?.info("\(#function, privacy: .public) - completed")
return true
}
func updatePatternDict(_ filename: String, _ filePatterns: [String], _ manifestKeys: [String: [String]]) -> [String: [String]] {
// will hold the exclude/match patterns in manifest that have file name as value
var patternsInManifestForFile = [String]()
// new var from func argument, so it can be manipulated
var returnDictionary = manifestKeys
// patterns from manifest
let keys = returnDictionary.keys
// determine what patterns already have this filename as a value
for key in keys {
// key is an array of filenames
guard let filenames = returnDictionary[key] else {
logger?.error("\(#function, privacy: .public) - failed to get values for manifest key, \(key, privacy: .public)")
continue
}
for name in filenames {
// name is a single filename
// if name is same as filename, file already added for this pattern
// add it to patternsInManifestForFile for later comparison
if name == filename {
patternsInManifestForFile.append(key)
}
}
}
// patterns in file metadata and patterns in manifest that have filename as a value
// filename already present in manifest for these patterns, do nothing with these
// let common = filePatterns.filter{patternsInManifestForFile.contains($0)}
// patterns in file metadata, but don't have the filename as a value within the manifest
// these are the manifest patterns that the filename needs to be added to
let addFilenameTo = filePatterns.filter{!patternsInManifestForFile.contains($0)}
// the patterns that have the filename as a value, but not present in file metadata
// ie. these are the manifest patterns we need to remove the filename from
let removeFilenameFrom = patternsInManifestForFile.filter{!filePatterns.contains($0)}
// check if filename needs to be added or new key/val needs to be created
for pattern in addFilenameTo {
if returnDictionary[pattern] != nil {
returnDictionary[pattern]?.append(filename)
} else {
returnDictionary[pattern] = [filename]
}
}
for pattern in removeFilenameFrom {
// get the index of the filename within the array
let ind = returnDictionary[pattern]?.firstIndex(of: filename)
// remove filename from array by index
returnDictionary[pattern]?.remove(at: ind!)
// if filename was the last item in array, remove the url pattern from dictionary
if returnDictionary[pattern]!.isEmpty {
returnDictionary.removeValue(forKey: pattern)
}
}
return returnDictionary
}
func updateManifestRequired(_ optionalFilesArray: [[String: Any]] = []) -> Bool {
logger?.info("\(#function, privacy: .public) - started")
// only get all files if files were not provided
var files = [[String: Any]]()
if optionalFilesArray.isEmpty {
guard let getFiles = getAllFiles() else {
logger?.info("\(#function, privacy: .public) - count not get files")
return false
}
files = getFiles
} else {
files = optionalFilesArray
}
logger?.info("\(#function, privacy: .public) - will loop through \(files.count, privacy: .public)")
var manifest = getManifest()
for file in files {
// can be force unwrapped because getAllFiles didn't return nil
let filename = file["filename"] as! String
let metadata = file["metadata"] as! [String: [String]]
let type = file["type"] as! String
let required = metadata["require"] ?? []
logger?.info("\(#function, privacy: .public) - begin \(filename, privacy: .public)")
// get required resources for file, if fail, skip updating manifest
if !getRequiredCode(filename, required, type) {
logger?.error("\(#function, privacy: .public) - couldn't fetch remote content for \(filename, privacy: .public)")
continue
}
// create filenames from sanitized resource urls
// getRequiredCode does the same thing when saving to disk
// populate array with entries for manifest
var r = [String]()
for resource in required {
let sanitizedResourceName = sanitize(resource)
r.append(sanitizedResourceName)
}
// if there are values, write them to manifest
// if failed to write to manifest, continue to next file & log error
if !r.isEmpty && r != manifest.require[filename] {
manifest.require[filename] = r
if !updateManifest(with: manifest) {
logger?.error("\(#function, privacy: .public) - couldn't update manifest when getting required resources")
}
}
logger?.info("\(#function, privacy: .public) - end \(filename, privacy: .public)")
}
logger?.info("\(#function, privacy: .public) - completed")
return true
}
func updateManifestDeclarativeNetRequests(_ optionalFilesArray: [[String: Any]] = []) -> Bool {
logger?.info("\(#function, privacy: .public) - started")
var files = [[String: Any]]()
if optionalFilesArray.isEmpty {
guard let getFiles = getAllFiles() else {
logger?.error("\(#function, privacy: .public) - failed at (1)")
return false
}
files = getFiles
} else {
files = optionalFilesArray
}
var manifest = getManifest()
for file in files {
// can be force unwrapped because getAllFiles didn't return nil
// and getAllFiles always returns the following
let metadata = file["metadata"] as! [String: [String]]
let filename = file["filename"] as! String
let runAt = metadata["run-at"]?[0] ?? "document-end"
// if not a request type, ignore
if runAt != "request" {
continue
}
var update = false
// if filename already in manifest
if !manifest.declarativeNetRequest.contains(filename) {
manifest.declarativeNetRequest.append(filename)
update = true
}
// if filename in another array remove it
for (pattern, filenames) in manifest.match {
for fn in filenames {
if fn == filename, let index = manifest.match[pattern]?.firstIndex(of: filename) {
manifest.match[pattern]?.remove(at: index)
update = true
}
}
}
for (pattern, filenames) in manifest.excludeMatch {
for fn in filenames {
if fn == filename, let index = manifest.excludeMatch[pattern]?.firstIndex(of: filename) {
manifest.excludeMatch[pattern]?.remove(at: index)
update = true
}
}
}
for (pattern, filenames) in manifest.include {
for fn in filenames {
if fn == filename, let index = manifest.include[pattern]?.firstIndex(of: filename) {
manifest.include[pattern]?.remove(at: index)
update = true
}
}
}
for (pattern, filenames) in manifest.exclude {
for fn in filenames {
if fn == filename, let index = manifest.exclude[pattern]?.firstIndex(of: filename) {
manifest.exclude[pattern]?.remove(at: index)
update = true
}
}
}
if update, !updateManifest(with: manifest) {
logger?.error("\(#function, privacy: .public) - failed at (2)")
return false
}
}
logger?.info("\(#function, privacy: .public) - completed")
return true
}
func purgeManifest(_ optionalFilesArray: [[String: Any]] = []) -> Bool {
logger?.info("\(#function, privacy: .public) - started")
// purge all manifest keys of any stale entries
var update = false, manifest = getManifest(), allSaveLocationFilenames = [String]()
// only get all files if files were not provided
var allFiles = [[String: Any]]()
if optionalFilesArray.isEmpty {
// if getAllFiles fails to return, ignore and pass an empty array
let getFiles = getAllFiles() ?? []
allFiles = getFiles
} else {
allFiles = optionalFilesArray
}
// populate array with filenames
for file in allFiles {
if let filename = file["filename"] as? String {
allSaveLocationFilenames.append(filename)
}
}
// loop through manifest keys, if no file exists for value, remove value from manifest
// if there are no more filenames in pattern, remove pattern from manifest
for (pattern, filenames) in manifest.match {
for filename in filenames {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.match[pattern]?.firstIndex(of: filename) {
manifest.match[pattern]?.remove(at: index)
update = true
logger?.info("\(#function, privacy: .public) - Could not find \(filename, privacy: .public) in save location, removed from match pattern - \(pattern, privacy: .public)")
}
}
}
if let length = manifest.match[pattern]?.count {
if length < 1, let ind = manifest.match.index(forKey: pattern) {
manifest.match.remove(at: ind)
logger?.info("\(#function, privacy: .public) - No more files for \(pattern, privacy: .public) match pattern, removed from manifest")
}
}
}
for (pattern, filenames) in manifest.excludeMatch {
for filename in filenames {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.excludeMatch[pattern]?.firstIndex(of: filename) {
manifest.excludeMatch[pattern]?.remove(at: index)
update = true
logger?.info("\(#function, privacy: .public) - Could not find \(filename, privacy: .public) in save location, removed from exclude-match pattern - \(pattern, privacy: .public)")
}
}
}
if let length = manifest.excludeMatch[pattern]?.count {
if length < 1, let ind = manifest.excludeMatch.index(forKey: pattern) {
manifest.excludeMatch.remove(at: ind)
logger?.info("\(#function, privacy: .public) - No more files for \(pattern, privacy: .public) exclude-match pattern, removed from manifest")
}
}
}
for (pattern, filenames) in manifest.exclude {
for filename in filenames {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.exclude[pattern]?.firstIndex(of: filename) {
manifest.exclude[pattern]?.remove(at: index)
update = true
logger?.info("\(#function, privacy: .public) - Could not find \(filename, privacy: .public) in save location, removed from exclude pattern - \(pattern, privacy: .public)")
}
}
}
if let length = manifest.exclude[pattern]?.count {
if length < 1, let ind = manifest.exclude.index(forKey: pattern) {
manifest.exclude.remove(at: ind)
logger?.info("\(#function, privacy: .public) - No more files for \(pattern, privacy: .public) exclude pattern, removed from manifest")
}
}
}
for (pattern, filenames) in manifest.include {
for filename in filenames {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.include[pattern]?.firstIndex(of: filename) {
manifest.include[pattern]?.remove(at: index)
update = true
logger?.info("\(#function, privacy: .public) - Could not find \(filename, privacy: .public) in save location, removed from exclude pattern - \(pattern, privacy: .public)")
}
}
}
if let length = manifest.include[pattern]?.count {
if length < 1, let ind = manifest.include.index(forKey: pattern) {
manifest.include.remove(at: ind)
logger?.info("\(#function, privacy: .public) - No more files for \(pattern, privacy: .public) exclude pattern, removed from manifest")
}
}
}
// loop through manifest required
for (filename, _) in manifest.require {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.require.index(forKey: filename) {
manifest.require.remove(at: index)
// remove associated resources
if !getRequiredCode(filename, [], (filename as NSString).pathExtension) {
logger?.error("\(#function, privacy: .public) - failed to remove required resources when purging \(filename, privacy: .public) from manifest required records")
}
update = true
logger?.info("\(#function, privacy: .public) - No more required resources for \(filename, privacy: .public), removed from manifest along with resource folder")
}
}
}
// loop through manifest disabled
for filename in manifest.disabled {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.disabled.firstIndex(of: filename) {
manifest.disabled.remove(at: index)
update = true
logger?.info("\(#function, privacy: .public) - Could not find \(filename, privacy: .public) in save location, removed from disabled")
}
}
}
// loop through manifest declarativeNetRequest
for filename in manifest.declarativeNetRequest {
if !allSaveLocationFilenames.contains(filename) {
if let index = manifest.declarativeNetRequest.firstIndex(of: filename) {
manifest.declarativeNetRequest.remove(at: index)
update = true
logger?.info("\(#function, privacy: .public) - Could not find \(filename, privacy: .public) in save location, removed from dNR")
}
}
}
// remove obsolete settings
for setting in manifest.settings {
if !defaultSettings.keys.contains(setting.key) {
manifest.settings.removeValue(forKey: setting.key)
update = true
logger?.info("\(#function, privacy: .public) - Removed obsolete setting - \(setting.key, privacy: .public)")
}
}
if update, !updateManifest(with: manifest) {
logger?.error("\(#function, privacy: .public) - failed to purge manifest")
return false
}
logger?.info("\(#function, privacy: .public) - completed")
return true
}
// settings
func checkSettings() -> Bool {
// iterate over default settings and individually check if each present
// if missing add setting to manifest about to be returned
// missing keys will occur when new settings introduced
var manifest = getManifest()
var update = false
for (key, value) in defaultSettings {
if manifest.settings[key] == nil {
manifest.settings[key] = value
update = true
}
}
if update, !updateManifest(with: manifest) {
logger?.error("\(#function, privacy: .public) - failed to update manifest settings")
return false
}
return true
}
func updateSettings(_ settings: [String: String]) -> Bool {
var manifest = getManifest()
manifest.settings = settings
if updateManifest(with: manifest) != true {
logger?.error("\(#function, privacy: .public) - failed to update settings")
return false
}
return true
}
// files
func getAllFiles(includeCode: Bool = false) -> [[String: Any]]? {
logger?.info("\(#function, privacy: .public) - started")
// returns all files of proper type with filenames, metadata & more
var files = [[String: Any]]()
let fm = FileManager.default
let manifest = getManifest()
guard let saveLocation = getSaveLocation() else {
logger?.error("\(#function, privacy: .public) - failed at (1)")
return nil
}
// security scope
let didStartAccessing = saveLocation.startAccessingSecurityScopedResource()
defer {
if didStartAccessing {saveLocation.stopAccessingSecurityScopedResource()}
}
// get all file urls within save location
guard let urls = try? fm.contentsOfDirectory(at: saveLocation, includingPropertiesForKeys: []) else {
logger?.error("\(#function, privacy: .public) - failed at (2)")
return nil
}
for url in urls {
var fileData = [String: Any]()
// only read contents for css & js files
let filename = url.lastPathComponent
if (!filename.hasSuffix(".css") && !filename.hasSuffix(".js")) {
continue
}
// file will be skipped if metablock is missing
guard
let content = try? String(contentsOf: url, encoding: .utf8),
let dateMod = try? fm.attributesOfItem(atPath: url.path)[.modificationDate] as? Date,
let parsed = parse(content),
let metadata = parsed["metadata"] as? [String: [String]],
let type = filename.split(separator: ".").last
else {
logger?.info("\(#function, privacy: .public) - ignoring \(filename, privacy: .public), file missing or metadata missing from file contents")
continue
}
fileData["canUpdate"] = false
fileData["content"] = content
fileData["disabled"] = manifest.disabled.contains(filename)
fileData["filename"] = filename
fileData["lastModified"] = dateToMilliseconds(dateMod)
fileData["metadata"] = metadata
// force unwrap name since parser ensure it exists
fileData["name"] = metadata["name"]![0]
fileData["type"] = "\(type)"
// add extra data if a request userscript
let runAt = metadata["run-at"]?[0] ?? "document-end"
if runAt == "request" {
fileData["request"] = true
}
if metadata["description"] != nil {
fileData["description"] = metadata["description"]![0]
}
if metadata["version"] != nil && metadata["updateURL"] != nil {
fileData["canUpdate"] = true
}
fileData["noframes"] = metadata["noframes"] != nil ? true : false
// if asked, also return the code string
if (includeCode) {
// can force unwrap because always returned from parser
fileData["code"] = parsed["code"] as! String
}
files.append(fileData)
}
logger?.info("\(#function, privacy: .public) - completed")
return files
}
func getRequiredCode(_ filename: String, _ resources: [String], _ fileType: String) -> Bool {
let directory = getRequireLocation().appendingPathComponent(filename)
// if file requires no resource but directory exists, remove it
// this resource is not user-generated and can be downloaded again, so just remove it instead of moves to the trash
// also in ios, the volume “Data” has no trash and item can only be removed directly
if resources.isEmpty {
if FileManager.default.fileExists(atPath: directory.path) {
do {
try FileManager.default.removeItem(at: directory)
} catch {
logger?.error("\(#function, privacy: .public) - failed to remove directory: \(error.localizedDescription, privacy: .public)")
}
}
return true
}
// record URLs for subsequent processing
var resourceUrls = Set<URL>()
// loop through resource urls and attempt to fetch it
for resourceUrlString in resources {
// get the path of the url string
guard let resourceUrlPath = URLComponents(string: resourceUrlString)?.path else {
// if path can not be obtained, skip and log
logger?.info("\(#function, privacy: .public) - failed to get path on \(filename, privacy: .public) for \(resourceUrlString, privacy: .public)")
continue
}
// skip urls pointing to files of different types
if resourceUrlPath.hasSuffix(fileType) {
let resourceFilename = sanitize(resourceUrlString)
let fileURL = directory.appendingPathComponent(resourceFilename)
// insert url to resolve symlink into set
resourceUrls.insert(fileURL.standardizedFileURL)
// only attempt to get resource if it does not yet exist
if FileManager.default.fileExists(atPath: fileURL.path) {continue}
// get the remote file contents
guard let contents = getRemoteFileContents(resourceUrlString) else {continue}
// check if file specific folder exists at requires directory
if !FileManager.default.fileExists(atPath: directory.path) {
guard ((try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)) != nil) else {
logger?.info("\(#function, privacy: .public) - failed to create required code directory for \(filename, privacy: .public)")
return false
}
}
// finally write file to directory
guard ((try? contents.write(to: fileURL, atomically: false, encoding: .utf8)) != nil) else {
logger?.info("\(#function, privacy: .public) - failed to write content to file for \(filename, privacy: .public) from \(resourceUrlString, privacy: .public)")
return false
}
}
}
// cleanup downloaded files that are no longer required
do {
var downloadedUrls = Set<URL>()
// get all downloaded resources url
let fileUrls = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [])
// insert url to resolve symlink into set
for url in fileUrls { downloadedUrls.insert(url.standardizedFileURL) }
// exclude currently required resources
let abandonedUrls = downloadedUrls.subtracting(resourceUrls)
// loop through abandoned urls and attempt to remove it
for abandonFileUrl in abandonedUrls {
do {
try FileManager.default.removeItem(at: abandonFileUrl)
logger?.info("\(#function, privacy: .public) - cleanup abandoned resource: \(unsanitize(abandonFileUrl.lastPathComponent), privacy: .public)")
} catch {
logger?.error("\(#function, privacy: .public) - failed to remove abandoned resource: \(error.localizedDescription, privacy: .public)")
}
}
} catch {
logger?.error("\(#function, privacy: .public) - failed to cleanup resources: \(error.localizedDescription, privacy: .public)")
}
return true
}
func checkForRemoteUpdates(_ optionalFilesArray: [[String: Any]] = []) -> [[String: String]]? {
// only get all files if files were not provided
var files = [[String: Any]]()
if optionalFilesArray.isEmpty {
guard let getFiles = getAllFiles() else {
logger?.error("\(#function, privacy: .public) - failed at (1)")
return nil
}
files = getFiles
} else {
files = optionalFilesArray
}
var hasUpdates = [[String: String]]()
for file in files {
// can be force unwrapped because getAllFiles didn't return nil
let filename = file["filename"] as! String
let canUpdate = file["canUpdate"] as! Bool
let metadata = file["metadata"] as! [String: [String]]
let type = file["type"] as! String
let name = metadata["name"]![0]
logger?.info("\(#function, privacy: .public) - Checking for remote updates for \(filename, privacy: .public)")
if canUpdate {
let currentVersion = metadata["version"]![0]
let updateUrl = metadata["updateURL"]![0]
// before fetching remote contents, ensure it points to a file of the same type
if !updateUrl.hasSuffix(type) {continue}
guard
let remoteFileContents = getRemoteFileContents(updateUrl),
let remoteFileContentsParsed = parse(remoteFileContents),
let remoteMetadata = remoteFileContentsParsed["metadata"] as? [String: [String]],
let remoteVersion = remoteMetadata["version"]?[0]
else {
logger?.error("\(#function, privacy: .public) - failed to parse remote file contents")
return nil
}
let remoteVersionNewer = isVersionNewer(currentVersion, remoteVersion)
if remoteVersionNewer {
hasUpdates.append(["name": name, "filename": filename, "type": type, "url": updateUrl])
}
}
}
logger?.info("\(#function, privacy: .public) - Finished checking for remote updates for \(files.count, privacy: .public) files")
return hasUpdates
}
func getRemoteFileContents(_ url: String) -> String? {
logger?.info("\(#function, privacy: .public) - started for \(url, privacy: .public)")
// if url is http change to https
var urlChecked = url
if urlChecked.hasPrefix("http:") {
urlChecked = urlChecked.replacingOccurrences(of: "http:", with: "https:")
logger?.info("\(#function, privacy: .public) - \(url, privacy: .public) is using insecure http, attempt to fetch remote content with https")
}
// convert url string to url
guard let solidURL = fixedURL(string: urlChecked) else {
logger?.error("\(#function, privacy: .public) - failed at (1), invalid URL: \(url, privacy: .public)")
return nil
}
var contents = ""
// get remote file contents, synchronously
let semaphore = DispatchSemaphore(value: 0)
var task: URLSessionDataTask?
task = URLSession.shared.dataTask(with: solidURL) { data, response, error in
if let r = response as? HTTPURLResponse, data != nil, error == nil {
if r.statusCode == 200 {
contents = String(data: data!, encoding: .utf8) ?? ""
} else {
logger?.error("\(#function, privacy: .public) - http statusCode (\(r.statusCode, privacy: .public)): \(url, privacy: .public)")
}
}
if let error = error {
logger?.error("\(#function, privacy: .public) - task error: \(error.localizedDescription, privacy: .public) (\(url, privacy: .public))")
}
semaphore.signal()
}
task?.resume()
// wait 30 seconds before timing out
if semaphore.wait(timeout: .now() + 30) == .timedOut {
task?.cancel()
logger?.error("\(#function, privacy: .public) - 30 seconds timeout: \(url, privacy: .public)")
}
// if made it to this point and contents still an empty string, something went wrong with the request
if contents.isEmpty {
logger?.error("\(#function, privacy: .public) - failed at (2), contents empty: \(url, privacy: .public)")
return nil
}
logger?.info("\(#function, privacy: .public) - completed for \(url, privacy: .public)")
return contents
}
func updateAllFiles(_ optionalFilesArray: [[String: Any]] = []) -> Bool {
// get names of all files with updates available
guard
let filesWithUpdates = checkForRemoteUpdates(optionalFilesArray),
let saveLocation = getSaveLocation()
else {
logger?.error("\(#function, privacy: .public) - failed to update files (1)")
return false
}
// security scope
let didStartAccessing = saveLocation.startAccessingSecurityScopedResource()
defer {
if didStartAccessing {saveLocation.stopAccessingSecurityScopedResource()}
}
for file in filesWithUpdates {
// can be force unwrapped because checkForRemoteUpdates didn't return nil
let filename = file["filename"]!
let fileUrl = saveLocation.appendingPathComponent(filename)
guard
let content = try? String(contentsOf: fileUrl, encoding: .utf8),
let parsed = parse(content),
let metadata = parsed["metadata"] as? [String: [String]],
let updateUrl = metadata["updateURL"]?[0]
else {
logger?.error("\(#function, privacy: .public) - failed to update files (2)")
continue
}
let downloadUrl = metadata["downloadURL"] != nil ? metadata["downloadURL"]![0] : updateUrl
guard
let remoteFileContents = getRemoteFileContents(downloadUrl),
((try? remoteFileContents.write(to: fileUrl, atomically: false, encoding: .utf8)) != nil)
else {
logger?.error("\(#function, privacy: .public) - failed to update files (3)")
continue
}
logger?.info("\(#function, privacy: .public) - updated \(filename, privacy: .public) with contents fetched from \(downloadUrl, privacy: .public)")
}
return true
}
func toggleFile(_ filename: String,_ action: String) -> Bool {
// if file doesn't exist return false
guard let saveLocation = getSaveLocation() else {
logger?.error("\(#function, privacy: .public) - failed at (1)")
return false
}
let didStartAccessing = saveLocation.startAccessingSecurityScopedResource()
defer {
if didStartAccessing {saveLocation.stopAccessingSecurityScopedResource()}
}
let path = saveLocation.appendingPathComponent(filename).path
if !FileManager.default.fileExists(atPath: path) {
logger?.error("\(#function, privacy: .public) - failed at (2)")
return false
}
var manifest = getManifest()
// if file is already disabled
if action == "disable" && manifest.disabled.contains(filename) || action == "enabled" && !manifest.disabled.contains(filename) {
return true
}
// add filename to disabled array if disabling
if (action == "disable") {manifest.disabled.append(filename)}
// remove filename from disabled array if enabling
if (action == "enable") {
guard let index = manifest.disabled.firstIndex(of: filename) else {
logger?.error("\(#function, privacy: .public) - failed at (3)")
return false
}
manifest.disabled.remove(at: index)
}
if !updateManifest(with: manifest) {
logger?.error("\(#function, privacy: .public) - failed at (4)")
return false
}
return true
}
func checkDefaultDirectories() -> Bool {
let defaultSaveLocation = getDocumentsDirectory().appendingPathComponent("scripts")
let requireLocation = getRequireLocation()
let urls = [defaultSaveLocation, requireLocation]
for url in urls {
if !FileManager.default.fileExists(atPath: url.path) {
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
} catch {