Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d96ced48c9 | ||
|
|
0b6dbfd888 | ||
|
|
96656438c6 | ||
|
|
4b32df5683 | ||
|
|
0758bd7dec | ||
|
|
171dabd83a | ||
|
|
6182a99ebd | ||
|
|
8bfedda3ab | ||
|
|
26f6ea1a9a | ||
|
|
778f377e42 | ||
|
|
f284365469 | ||
|
|
5dfb7d4ba4 | ||
|
|
bb9c3a3034 | ||
|
|
8cf872a4b0 | ||
|
|
e813230824 | ||
|
|
e8bfde9243 | ||
|
|
e947ad6d4d | ||
|
|
0a53898797 | ||
|
|
946acc2460 | ||
|
|
e13b3df2c4 | ||
|
|
7df2fe421e | ||
|
|
b4b89f8bb4 | ||
|
|
db41e68f35 | ||
|
|
5acd9bbcc6 | ||
|
|
23eab2310f | ||
|
|
80829ad015 | ||
|
|
661bf5d30a | ||
|
|
38f4166503 | ||
|
|
d96038c7e3 | ||
|
|
7d6b071d8a | ||
|
|
b17fb3c354 | ||
|
|
10b43a0f67 | ||
|
|
4092a9ba55 | ||
|
|
2d35c863e4 | ||
|
|
8424c161b9 | ||
|
|
9485d7e9b5 | ||
|
|
9f26bdfba1 |
@@ -7,35 +7,40 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
540C6457240D929300E948F9 /* EditableRows.swift in Sources */ = {isa = PBXBuildFile; fileRef = 540C6456240D929300E948F9 /* EditableRows.swift */; };
|
||||
540E6780242D2CF100871BBE /* VCRecordings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 540E677F242D2CF100871BBE /* VCRecordings.swift */; };
|
||||
540E67822433483D00871BBE /* VCEditRecording.swift in Sources */ = {isa = PBXBuildFile; fileRef = 540E67812433483D00871BBE /* VCEditRecording.swift */; };
|
||||
540E67842433FAFE00871BBE /* TVCPreviousRecords.swift in Sources */ = {isa = PBXBuildFile; fileRef = 540E67832433FAFE00871BBE /* TVCPreviousRecords.swift */; };
|
||||
5412F8EE24571B8200A63D7A /* VCDateFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5412F8ED24571B8100A63D7A /* VCDateFilter.swift */; };
|
||||
541A957623E602DF00C09C19 /* LaunchIcon.png in Resources */ = {isa = PBXBuildFile; fileRef = 541A957523E602DF00C09C19 /* LaunchIcon.png */; };
|
||||
541AC5D82399498A00A769D7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 541AC5D72399498A00A769D7 /* AppDelegate.swift */; };
|
||||
541AC5DD2399498A00A769D7 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 541AC5DB2399498A00A769D7 /* Main.storyboard */; };
|
||||
541AC5DF2399498B00A769D7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 541AC5DE2399498B00A769D7 /* Assets.xcassets */; };
|
||||
541AC5E22399498B00A769D7 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 541AC5E02399498B00A769D7 /* LaunchScreen.storyboard */; };
|
||||
541FC47624A12D01009154D8 /* IBViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 541FC47524A12D01009154D8 /* IBViews.swift */; };
|
||||
541FC47824A1453F009154D8 /* VCCoOccurrence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 541FC47724A1453F009154D8 /* VCCoOccurrence.swift */; };
|
||||
541FC9872497D81C00962623 /* TheGreatDestroyer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 541FC9862497D81C00962623 /* TheGreatDestroyer.swift */; };
|
||||
542E2A982404973F001462DC /* TBCMain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 542E2A972404973F001462DC /* TBCMain.swift */; };
|
||||
542E2A9A24051556001462DC /* TVCSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 542E2A9924051556001462DC /* TVCSettings.swift */; };
|
||||
543CDB2023EEE61900B7F323 /* PacketTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 543CDB1F23EEE61900B7F323 /* PacketTunnelProvider.swift */; };
|
||||
543CDB2523EEE61900B7F323 /* GlassVPN.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 543CDB1D23EEE61900B7F323 /* GlassVPN.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
54448A2E2486464F00771C96 /* Array.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54448A2D2486464F00771C96 /* Array.swift */; };
|
||||
54448A30248647D900771C96 /* Time.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54448A2F248647D900771C96 /* Time.swift */; };
|
||||
54448A3224899A4000771C96 /* SearchBarManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54448A3124899A4000771C96 /* SearchBarManager.swift */; };
|
||||
544C95262407B1C700AB89D0 /* SharedState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 544C95252407B1C700AB89D0 /* SharedState.swift */; };
|
||||
5458EBC0243A3F2200CFEB15 /* TVCRecordingDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5458EBBF243A3F2200CFEB15 /* TVCRecordingDetails.swift */; };
|
||||
545DDDCF243E6267003B6544 /* TutorialSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 545DDDCE243E6267003B6544 /* TutorialSheet.swift */; };
|
||||
545DDDD124436983003B6544 /* QuickUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 545DDDD024436983003B6544 /* QuickUI.swift */; };
|
||||
545DDDD424466D37003B6544 /* AutoLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 545DDDD324466D37003B6544 /* AutoLayout.swift */; };
|
||||
546063E523FEFAFE008F505A /* SQDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B7562223D7B2DC008F0C41 /* SQDB.swift */; };
|
||||
546063E523FEFAFE008F505A /* DBCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B7562223D7B2DC008F0C41 /* DBCore.swift */; };
|
||||
54751E512423955100168273 /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54751E502423955000168273 /* URL.swift */; };
|
||||
54751E522423955100168273 /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54751E502423955000168273 /* URL.swift */; };
|
||||
54953E3323DC752E0054345C /* SQDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B7562223D7B2DC008F0C41 /* SQDB.swift */; };
|
||||
54953E3323DC752E0054345C /* DBCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B7562223D7B2DC008F0C41 /* DBCore.swift */; };
|
||||
54953E5F23DEBE840054345C /* TVCDomains.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54953E5E23DEBE840054345C /* TVCDomains.swift */; };
|
||||
54953E6123E0D69A0054345C /* TVCHosts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54953E6023E0D69A0054345C /* TVCHosts.swift */; };
|
||||
54953E6F23E44CD00054345C /* TVCHostDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54953E6E23E44CD00054345C /* TVCHostDetails.swift */; };
|
||||
54953E7123E473F10054345C /* Settings.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 54953E7023E473F10054345C /* Settings.bundle */; };
|
||||
54B34594240E6343004C53CC /* TVCFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B34593240E6343004C53CC /* TVCFilter.swift */; };
|
||||
54B34596240F0513004C53CC /* TableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B34595240F0513004C53CC /* TableView.swift */; };
|
||||
54B345992414F491004C53CC /* DBWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B345982414F491004C53CC /* DBWrapper.swift */; };
|
||||
54B345A6241BB982004C53CC /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B345A5241BB982004C53CC /* Notifications.swift */; };
|
||||
54B345A9241BBA0B004C53CC /* Generic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B345A8241BBA0B004C53CC /* Generic.swift */; };
|
||||
54B345AB241BBA5B004C53CC /* AlertSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B345AA241BBA5B004C53CC /* AlertSheet.swift */; };
|
||||
@@ -123,6 +128,18 @@
|
||||
54CA02BE2426D4F3003A5E04 /* DDLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54CA02BD2426D4F3003A5E04 /* DDLog.swift */; };
|
||||
54CA02C32426DCCD003A5E04 /* GCDAsyncSocket.m in Sources */ = {isa = PBXBuildFile; fileRef = 54CA02BF2426DCCC003A5E04 /* GCDAsyncSocket.m */; };
|
||||
54CA02C42426DCCD003A5E04 /* GCDAsyncUdpSocket.m in Sources */ = {isa = PBXBuildFile; fileRef = 54CA02C02426DCCD003A5E04 /* GCDAsyncUdpSocket.m */; };
|
||||
54D8B97A246C9F2000EB2414 /* FilterPipeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D8B979246C9F2000EB2414 /* FilterPipeline.swift */; };
|
||||
54D8B97C2471A7E000EB2414 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D8B97B2471A7E000EB2414 /* String.swift */; };
|
||||
54D8B97E2471B88900EB2414 /* DBCommon.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D8B97D2471B88900EB2414 /* DBCommon.swift */; };
|
||||
54D8B97F2471B89100EB2414 /* DBCommon.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D8B97D2471B88900EB2414 /* DBCommon.swift */; };
|
||||
54D8B9832471BD8100EB2414 /* DBAppOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D8B9822471BD8100EB2414 /* DBAppOnly.swift */; };
|
||||
54D8B98624796E9900EB2414 /* GroupedDomainDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D8B98524796E9800EB2414 /* GroupedDomainDataSource.swift */; };
|
||||
54E540F2247C423200F7C34A /* DomainFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54E540F1247C423200F7C34A /* DomainFilter.swift */; };
|
||||
54E540F4247D3F2600F7C34A /* TestDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54E540F3247D3F2600F7C34A /* TestDataSource.swift */; };
|
||||
54E540F8247DB90F00F7C34A /* RecordingsDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54E540F7247DB90F00F7C34A /* RecordingsDB.swift */; };
|
||||
54E540FA2482414800F7C34A /* SyncUpdate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54E540F92482414800F7C34A /* SyncUpdate.swift */; };
|
||||
54EFA4E6248EEE240022D618 /* DatePickerAlert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54EFA4E5248EEE240022D618 /* DatePickerAlert.swift */; };
|
||||
54EFA4E82491A16A0022D618 /* Font.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54EFA4E72491A16A0022D618 /* Font.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -150,10 +167,10 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
540C6456240D929300E948F9 /* EditableRows.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EditableRows.swift; sourceTree = "<group>"; };
|
||||
540E677F242D2CF100871BBE /* VCRecordings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VCRecordings.swift; sourceTree = "<group>"; };
|
||||
540E67812433483D00871BBE /* VCEditRecording.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VCEditRecording.swift; sourceTree = "<group>"; };
|
||||
540E67832433FAFE00871BBE /* TVCPreviousRecords.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TVCPreviousRecords.swift; sourceTree = "<group>"; };
|
||||
5412F8ED24571B8100A63D7A /* VCDateFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VCDateFilter.swift; sourceTree = "<group>"; };
|
||||
541A957523E602DF00C09C19 /* LaunchIcon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = LaunchIcon.png; sourceTree = "<group>"; };
|
||||
541AC5D42399498A00A769D7 /* AppCheck.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AppCheck.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
541AC5D72399498A00A769D7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
@@ -161,12 +178,18 @@
|
||||
541AC5DE2399498B00A769D7 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
541AC5E12399498B00A769D7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
541AC5E32399498B00A769D7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
541FC47524A12D01009154D8 /* IBViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IBViews.swift; sourceTree = "<group>"; };
|
||||
541FC47724A1453F009154D8 /* VCCoOccurrence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VCCoOccurrence.swift; sourceTree = "<group>"; };
|
||||
541FC9862497D81C00962623 /* TheGreatDestroyer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TheGreatDestroyer.swift; sourceTree = "<group>"; };
|
||||
542E2A972404973F001462DC /* TBCMain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TBCMain.swift; sourceTree = "<group>"; };
|
||||
542E2A9924051556001462DC /* TVCSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TVCSettings.swift; sourceTree = "<group>"; };
|
||||
543CDB1D23EEE61900B7F323 /* GlassVPN.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = GlassVPN.appex; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
543CDB1F23EEE61900B7F323 /* PacketTunnelProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PacketTunnelProvider.swift; sourceTree = "<group>"; };
|
||||
543CDB2123EEE61900B7F323 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
543CDB2223EEE61900B7F323 /* GlassVPN.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = GlassVPN.entitlements; sourceTree = "<group>"; };
|
||||
54448A2D2486464F00771C96 /* Array.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Array.swift; sourceTree = "<group>"; };
|
||||
54448A2F248647D900771C96 /* Time.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Time.swift; sourceTree = "<group>"; };
|
||||
54448A3124899A4000771C96 /* SearchBarManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchBarManager.swift; sourceTree = "<group>"; };
|
||||
544C95252407B1C700AB89D0 /* SharedState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedState.swift; sourceTree = "<group>"; };
|
||||
5458EBBF243A3F2200CFEB15 /* TVCRecordingDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TVCRecordingDetails.swift; sourceTree = "<group>"; };
|
||||
545DDDCE243E6267003B6544 /* TutorialSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TutorialSheet.swift; sourceTree = "<group>"; };
|
||||
@@ -180,13 +203,12 @@
|
||||
54953E7023E473F10054345C /* Settings.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = Settings.bundle; sourceTree = "<group>"; };
|
||||
54B34593240E6343004C53CC /* TVCFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TVCFilter.swift; sourceTree = "<group>"; };
|
||||
54B34595240F0513004C53CC /* TableView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableView.swift; sourceTree = "<group>"; };
|
||||
54B345982414F491004C53CC /* DBWrapper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DBWrapper.swift; sourceTree = "<group>"; };
|
||||
54B345A5241BB982004C53CC /* Notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notifications.swift; sourceTree = "<group>"; };
|
||||
54B345A8241BBA0B004C53CC /* Generic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Generic.swift; sourceTree = "<group>"; };
|
||||
54B345AA241BBA5B004C53CC /* AlertSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlertSheet.swift; sourceTree = "<group>"; };
|
||||
54B345AC241BBB00004C53CC /* DBExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DBExtensions.swift; sourceTree = "<group>"; };
|
||||
54B345AF242264F8004C53CC /* third-level.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "third-level.txt"; sourceTree = "<group>"; };
|
||||
54B7562223D7B2DC008F0C41 /* SQDB.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQDB.swift; sourceTree = "<group>"; };
|
||||
54B7562223D7B2DC008F0C41 /* DBCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DBCore.swift; sourceTree = "<group>"; };
|
||||
54C056DA23E9E36E00214A3F /* AppInfoType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppInfoType.swift; sourceTree = "<group>"; };
|
||||
54C056DC23E9EEF700214A3F /* BundleIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BundleIcon.swift; sourceTree = "<group>"; };
|
||||
54CA00D62426A803003A5E04 /* CocoaAsyncSocket.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CocoaAsyncSocket.h; sourceTree = "<group>"; };
|
||||
@@ -272,6 +294,17 @@
|
||||
54CA02C02426DCCD003A5E04 /* GCDAsyncUdpSocket.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDAsyncUdpSocket.m; sourceTree = "<group>"; };
|
||||
54CA02C12426DCCD003A5E04 /* GCDAsyncSocket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDAsyncSocket.h; sourceTree = "<group>"; };
|
||||
54CA02C22426DCCD003A5E04 /* GCDAsyncUdpSocket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDAsyncUdpSocket.h; sourceTree = "<group>"; };
|
||||
54D8B979246C9F2000EB2414 /* FilterPipeline.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilterPipeline.swift; sourceTree = "<group>"; };
|
||||
54D8B97B2471A7E000EB2414 /* String.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = String.swift; sourceTree = "<group>"; };
|
||||
54D8B97D2471B88900EB2414 /* DBCommon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DBCommon.swift; sourceTree = "<group>"; };
|
||||
54D8B9822471BD8100EB2414 /* DBAppOnly.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DBAppOnly.swift; sourceTree = "<group>"; };
|
||||
54D8B98524796E9800EB2414 /* GroupedDomainDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupedDomainDataSource.swift; sourceTree = "<group>"; };
|
||||
54E540F1247C423200F7C34A /* DomainFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainFilter.swift; sourceTree = "<group>"; };
|
||||
54E540F3247D3F2600F7C34A /* TestDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestDataSource.swift; sourceTree = "<group>"; };
|
||||
54E540F7247DB90F00F7C34A /* RecordingsDB.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordingsDB.swift; sourceTree = "<group>"; };
|
||||
54E540F92482414800F7C34A /* SyncUpdate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncUpdate.swift; sourceTree = "<group>"; };
|
||||
54EFA4E5248EEE240022D618 /* DatePickerAlert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatePickerAlert.swift; sourceTree = "<group>"; };
|
||||
54EFA4E72491A16A0022D618 /* Font.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Font.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -296,8 +329,10 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
54953E5E23DEBE840054345C /* TVCDomains.swift */,
|
||||
5412F8ED24571B8100A63D7A /* VCDateFilter.swift */,
|
||||
54953E6023E0D69A0054345C /* TVCHosts.swift */,
|
||||
54953E6E23E44CD00054345C /* TVCHostDetails.swift */,
|
||||
541FC47424A12CE9009154D8 /* Analytics */,
|
||||
);
|
||||
path = Requests;
|
||||
sourceTree = "<group>";
|
||||
@@ -345,6 +380,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
54B3459A2415651C004C53CC /* DB */,
|
||||
54E540F0247C386500F7C34A /* Data Source */,
|
||||
54B345A4241BB975004C53CC /* Extensions */,
|
||||
545DDDD224436A03003B6544 /* Common Classes */,
|
||||
548B1F9423D338EC005B047C /* main.entitlements */,
|
||||
@@ -354,8 +390,8 @@
|
||||
540E677E242D2CD200871BBE /* Recordings */,
|
||||
540C6455240D5BD200E948F9 /* Settings */,
|
||||
54B345B12422E029004C53CC /* unused */,
|
||||
541AC5DB2399498A00A769D7 /* Main.storyboard */,
|
||||
541AC5E02399498B00A769D7 /* LaunchScreen.storyboard */,
|
||||
541AC5DB2399498A00A769D7 /* Main.storyboard */,
|
||||
541AC5DE2399498B00A769D7 /* Assets.xcassets */,
|
||||
541AC5E32399498B00A769D7 /* Info.plist */,
|
||||
54953E7023E473F10054345C /* Settings.bundle */,
|
||||
@@ -363,6 +399,14 @@
|
||||
path = main;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
541FC47424A12CE9009154D8 /* Analytics */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
541FC47724A1453F009154D8 /* VCCoOccurrence.swift */,
|
||||
);
|
||||
path = Analytics;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
542E2A9B24051F79001462DC /* media */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -391,7 +435,10 @@
|
||||
children = (
|
||||
545DDDD024436983003B6544 /* QuickUI.swift */,
|
||||
545DDDCE243E6267003B6544 /* TutorialSheet.swift */,
|
||||
540C6456240D929300E948F9 /* EditableRows.swift */,
|
||||
54D8B979246C9F2000EB2414 /* FilterPipeline.swift */,
|
||||
54448A3124899A4000771C96 /* SearchBarManager.swift */,
|
||||
54EFA4E5248EEE240022D618 /* DatePickerAlert.swift */,
|
||||
541FC47524A12D01009154D8 /* IBViews.swift */,
|
||||
);
|
||||
path = "Common Classes";
|
||||
sourceTree = "<group>";
|
||||
@@ -399,8 +446,11 @@
|
||||
54B3459A2415651C004C53CC /* DB */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
54B7562223D7B2DC008F0C41 /* SQDB.swift */,
|
||||
54B345982414F491004C53CC /* DBWrapper.swift */,
|
||||
54B7562223D7B2DC008F0C41 /* DBCore.swift */,
|
||||
54D8B97D2471B88900EB2414 /* DBCommon.swift */,
|
||||
54D8B9822471BD8100EB2414 /* DBAppOnly.swift */,
|
||||
54B345AC241BBB00004C53CC /* DBExtensions.swift */,
|
||||
541FC9862497D81C00962623 /* TheGreatDestroyer.swift */,
|
||||
);
|
||||
path = DB;
|
||||
sourceTree = "<group>";
|
||||
@@ -411,10 +461,13 @@
|
||||
544C95252407B1C700AB89D0 /* SharedState.swift */,
|
||||
54B345A8241BBA0B004C53CC /* Generic.swift */,
|
||||
54B345A5241BB982004C53CC /* Notifications.swift */,
|
||||
54B345AC241BBB00004C53CC /* DBExtensions.swift */,
|
||||
54B345AA241BBA5B004C53CC /* AlertSheet.swift */,
|
||||
54B34595240F0513004C53CC /* TableView.swift */,
|
||||
54448A2F248647D900771C96 /* Time.swift */,
|
||||
54751E502423955000168273 /* URL.swift */,
|
||||
54EFA4E72491A16A0022D618 /* Font.swift */,
|
||||
54448A2D2486464F00771C96 /* Array.swift */,
|
||||
54D8B97B2471A7E000EB2414 /* String.swift */,
|
||||
54B34595240F0513004C53CC /* TableView.swift */,
|
||||
545DDDD324466D37003B6544 /* AutoLayout.swift */,
|
||||
);
|
||||
path = Extensions;
|
||||
@@ -652,6 +705,18 @@
|
||||
path = ProxySocket;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
54E540F0247C386500F7C34A /* Data Source */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
54E540F3247D3F2600F7C34A /* TestDataSource.swift */,
|
||||
54E540F92482414800F7C34A /* SyncUpdate.swift */,
|
||||
54D8B98524796E9800EB2414 /* GroupedDomainDataSource.swift */,
|
||||
54E540F1247C423200F7C34A /* DomainFilter.swift */,
|
||||
54E540F7247DB90F00F7C34A /* RecordingsDB.swift */,
|
||||
);
|
||||
path = "Data Source";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -769,32 +834,48 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
54E540F8247DB90F00F7C34A /* RecordingsDB.swift in Sources */,
|
||||
54E540F4247D3F2600F7C34A /* TestDataSource.swift in Sources */,
|
||||
545DDDD424466D37003B6544 /* AutoLayout.swift in Sources */,
|
||||
54B345AD241BBB00004C53CC /* DBExtensions.swift in Sources */,
|
||||
54E540F2247C423200F7C34A /* DomainFilter.swift in Sources */,
|
||||
54D8B97E2471B88900EB2414 /* DBCommon.swift in Sources */,
|
||||
54D8B9832471BD8100EB2414 /* DBAppOnly.swift in Sources */,
|
||||
540E67842433FAFE00871BBE /* TVCPreviousRecords.swift in Sources */,
|
||||
54B345A6241BB982004C53CC /* Notifications.swift in Sources */,
|
||||
54448A2E2486464F00771C96 /* Array.swift in Sources */,
|
||||
541FC47824A1453F009154D8 /* VCCoOccurrence.swift in Sources */,
|
||||
54B345AB241BBA5B004C53CC /* AlertSheet.swift in Sources */,
|
||||
544C95262407B1C700AB89D0 /* SharedState.swift in Sources */,
|
||||
545DDDCF243E6267003B6544 /* TutorialSheet.swift in Sources */,
|
||||
54B345A9241BBA0B004C53CC /* Generic.swift in Sources */,
|
||||
54B34596240F0513004C53CC /* TableView.swift in Sources */,
|
||||
540E6780242D2CF100871BBE /* VCRecordings.swift in Sources */,
|
||||
54953E3323DC752E0054345C /* SQDB.swift in Sources */,
|
||||
54953E3323DC752E0054345C /* DBCore.swift in Sources */,
|
||||
54448A30248647D900771C96 /* Time.swift in Sources */,
|
||||
54953E6123E0D69A0054345C /* TVCHosts.swift in Sources */,
|
||||
540C6457240D929300E948F9 /* EditableRows.swift in Sources */,
|
||||
54751E512423955100168273 /* URL.swift in Sources */,
|
||||
542E2A9A24051556001462DC /* TVCSettings.swift in Sources */,
|
||||
54953E5F23DEBE840054345C /* TVCDomains.swift in Sources */,
|
||||
54C056DB23E9E36E00214A3F /* AppInfoType.swift in Sources */,
|
||||
54D8B98624796E9900EB2414 /* GroupedDomainDataSource.swift in Sources */,
|
||||
54953E6F23E44CD00054345C /* TVCHostDetails.swift in Sources */,
|
||||
54D8B97C2471A7E000EB2414 /* String.swift in Sources */,
|
||||
54EFA4E6248EEE240022D618 /* DatePickerAlert.swift in Sources */,
|
||||
54C056DD23E9EEF700214A3F /* BundleIcon.swift in Sources */,
|
||||
542E2A982404973F001462DC /* TBCMain.swift in Sources */,
|
||||
54448A3224899A4000771C96 /* SearchBarManager.swift in Sources */,
|
||||
5458EBC0243A3F2200CFEB15 /* TVCRecordingDetails.swift in Sources */,
|
||||
541FC9872497D81C00962623 /* TheGreatDestroyer.swift in Sources */,
|
||||
5412F8EE24571B8200A63D7A /* VCDateFilter.swift in Sources */,
|
||||
545DDDD124436983003B6544 /* QuickUI.swift in Sources */,
|
||||
541AC5D82399498A00A769D7 /* AppDelegate.swift in Sources */,
|
||||
54B345992414F491004C53CC /* DBWrapper.swift in Sources */,
|
||||
541FC47624A12D01009154D8 /* IBViews.swift in Sources */,
|
||||
540E67822433483D00871BBE /* VCEditRecording.swift in Sources */,
|
||||
54EFA4E82491A16A0022D618 /* Font.swift in Sources */,
|
||||
54D8B97A246C9F2000EB2414 /* FilterPipeline.swift in Sources */,
|
||||
54B34594240E6343004C53CC /* TVCFilter.swift in Sources */,
|
||||
54E540FA2482414800F7C34A /* SyncUpdate.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -846,6 +927,7 @@
|
||||
54CA02A62426B2FD003A5E04 /* AdapterSocket.swift in Sources */,
|
||||
54CA02742426B2FD003A5E04 /* IPMask.swift in Sources */,
|
||||
54CA02BB2426B2FD003A5E04 /* SOCKS5ProxySocket.swift in Sources */,
|
||||
54D8B97F2471B89100EB2414 /* DBCommon.swift in Sources */,
|
||||
54CA02A42426B2FD003A5E04 /* SecureHTTPAdapter.swift in Sources */,
|
||||
54CA02942426B2FD003A5E04 /* DNSResolver.swift in Sources */,
|
||||
54CA025F2426B2FD003A5E04 /* ProxyServer.swift in Sources */,
|
||||
@@ -877,7 +959,7 @@
|
||||
54CA02972426B2FD003A5E04 /* IPPacket.swift in Sources */,
|
||||
54CA026A2426B2FD003A5E04 /* RawSocketFactory.swift in Sources */,
|
||||
54CA02A02426B2FD003A5E04 /* TunnelEvent.swift in Sources */,
|
||||
546063E523FEFAFE008F505A /* SQDB.swift in Sources */,
|
||||
546063E523FEFAFE008F505A /* DBCore.swift in Sources */,
|
||||
54CA02872426B2FD003A5E04 /* IPRangeListRule.swift in Sources */,
|
||||
54CA02922426B2FD003A5E04 /* DNSSession.swift in Sources */,
|
||||
54CA026D2426B2FD003A5E04 /* Opt.swift in Sources */,
|
||||
@@ -1045,7 +1127,7 @@
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_ENTITLEMENTS = main/main.entitlements;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 22;
|
||||
INFOPLIST_FILE = main/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
@@ -1064,7 +1146,7 @@
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_ENTITLEMENTS = main/main.entitlements;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 22;
|
||||
INFOPLIST_FILE = main/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
@@ -1083,7 +1165,7 @@
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = GlassVPN/GlassVPN.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 22;
|
||||
INFOPLIST_FILE = GlassVPN/Info.plist;
|
||||
MARKETING_VERSION = 1.0.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "de.uni-bamberg.psi.AppCheck.VPN";
|
||||
@@ -1101,7 +1183,7 @@
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = GlassVPN/GlassVPN.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 22;
|
||||
INFOPLIST_FILE = GlassVPN/Info.plist;
|
||||
MARKETING_VERSION = 1.0.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "de.uni-bamberg.psi.AppCheck.VPN";
|
||||
|
||||
@@ -1,13 +1,57 @@
|
||||
import NetworkExtension
|
||||
|
||||
fileprivate var db: SQLiteDatabase?
|
||||
fileprivate var domainFilters: [String : FilterOptions] = [:]
|
||||
fileprivate var filterDomains: [String]!
|
||||
fileprivate var filterOptions: [(block: Bool, ignore: Bool)]!
|
||||
|
||||
|
||||
// MARK: Backward DNS Binary Tree Lookup
|
||||
|
||||
fileprivate func reloadDomainFilter() {
|
||||
let tmp = AppDB?.loadFilters()?.map({
|
||||
(String($0.reversed()), $1)
|
||||
}).sorted(by: { $0.0 < $1.0 }) ?? []
|
||||
filterDomains = tmp.map { $0.0 }
|
||||
filterOptions = tmp.map { ($1.contains(.blocked), $1.contains(.ignored)) }
|
||||
}
|
||||
|
||||
fileprivate func filterIndex(for domain: String) -> Int {
|
||||
let reverseDomain = String(domain.reversed())
|
||||
var lo = 0, hi = filterDomains.count - 1
|
||||
while lo <= hi {
|
||||
let mid = (lo + hi)/2
|
||||
if filterDomains[mid] < reverseDomain {
|
||||
lo = mid + 1
|
||||
} else if reverseDomain < filterDomains[mid] {
|
||||
hi = mid - 1
|
||||
} else {
|
||||
return mid
|
||||
}
|
||||
}
|
||||
if lo > 0, reverseDomain.hasPrefix(filterDomains[lo - 1] + ".") {
|
||||
return lo - 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
private let queue = DispatchQueue.init(label: "PSIGlassDNSQueue", qos: .userInteractive, target: .main)
|
||||
|
||||
private func logAsync(_ domain: String, blocked: Bool) {
|
||||
queue.async {
|
||||
do {
|
||||
try AppDB?.logWrite(domain, blocked: blocked)
|
||||
} catch {
|
||||
DDLogWarn("Couldn't write: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: ObserverFactory
|
||||
|
||||
class LDObserverFactory: ObserverFactory {
|
||||
|
||||
|
||||
override func getObserverForProxySocket(_ socket: ProxySocket) -> Observer<ProxySocketEvent>? {
|
||||
// TODO: replace NEKit with custom proxy with minimal footprint
|
||||
return LDProxySocketObserver()
|
||||
}
|
||||
|
||||
@@ -15,66 +59,62 @@ class LDObserverFactory: ObserverFactory {
|
||||
override func signal(_ event: ProxySocketEvent) {
|
||||
switch event {
|
||||
case .receivedRequest(let session, let socket):
|
||||
DDLogDebug("DNS: \(session.host)")
|
||||
let match = domainFilters.first { session.host == $0.key || session.host.hasSuffix("." + $0.key) }
|
||||
let block = match?.value.contains(.blocked) ?? false
|
||||
let ignore = match?.value.contains(.ignored) ?? false
|
||||
if !ignore { try? db?.insertDNSQuery(session.host, blocked: block) }
|
||||
else { DDLogDebug("ignored") }
|
||||
if block { DDLogDebug("blocked"); socket.forceDisconnect() }
|
||||
let i = filterIndex(for: session.host)
|
||||
if i >= 0 {
|
||||
let (block, ignore) = filterOptions[i]
|
||||
if !ignore { logAsync(session.host, blocked: block) }
|
||||
if block { socket.forceDisconnect() }
|
||||
} else {
|
||||
// TODO: disable filter during recordings
|
||||
logAsync(session.host, blocked: false)
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: NEPacketTunnelProvider
|
||||
|
||||
class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
|
||||
let proxyServerPort: UInt16 = 9090
|
||||
let proxyServerAddress = "127.0.0.1"
|
||||
let proxyServerAddress = "127.0.0.1"
|
||||
var proxyServer: GCDHTTPProxyServer!
|
||||
|
||||
func reloadDomainFilter() {
|
||||
domainFilters = db?.loadFilters() ?? [:]
|
||||
}
|
||||
|
||||
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
|
||||
DDLogVerbose("startTunnel")
|
||||
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
|
||||
do {
|
||||
db = try SQLiteDatabase.open()
|
||||
db!.initScheme()
|
||||
try SQLiteDatabase.open().initCommonScheme()
|
||||
} catch {
|
||||
completionHandler(error)
|
||||
return
|
||||
}
|
||||
if proxyServer != nil {
|
||||
proxyServer.stop()
|
||||
}
|
||||
proxyServer = nil
|
||||
|
||||
reloadDomainFilter()
|
||||
|
||||
if proxyServer != nil {
|
||||
proxyServer.stop()
|
||||
}
|
||||
proxyServer = nil
|
||||
|
||||
// Create proxy
|
||||
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: proxyServerAddress)
|
||||
settings.mtu = NSNumber(value: 1500)
|
||||
|
||||
let proxySettings = NEProxySettings()
|
||||
proxySettings.httpEnabled = true;
|
||||
proxySettings.httpServer = NEProxyServer(address: proxyServerAddress, port: Int(proxyServerPort))
|
||||
proxySettings.httpsEnabled = true;
|
||||
proxySettings.httpsServer = NEProxyServer(address: proxyServerAddress, port: Int(proxyServerPort))
|
||||
proxySettings.excludeSimpleHostnames = false;
|
||||
proxySettings.exceptionList = []
|
||||
proxySettings.matchDomains = [""]
|
||||
|
||||
settings.dnsSettings = NEDNSSettings(servers: ["127.0.0.1"])
|
||||
settings.proxySettings = proxySettings;
|
||||
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: proxyServerAddress)
|
||||
settings.mtu = NSNumber(value: 1500)
|
||||
|
||||
let proxySettings = NEProxySettings()
|
||||
proxySettings.httpEnabled = true;
|
||||
proxySettings.httpServer = NEProxyServer(address: proxyServerAddress, port: Int(proxyServerPort))
|
||||
proxySettings.httpsEnabled = true;
|
||||
proxySettings.httpsServer = NEProxyServer(address: proxyServerAddress, port: Int(proxyServerPort))
|
||||
proxySettings.excludeSimpleHostnames = false;
|
||||
proxySettings.exceptionList = []
|
||||
proxySettings.matchDomains = [""]
|
||||
|
||||
settings.dnsSettings = NEDNSSettings(servers: ["127.0.0.1"])
|
||||
settings.proxySettings = proxySettings;
|
||||
RawSocketFactory.TunnelProvider = self
|
||||
ObserverFactory.currentFactory = LDObserverFactory()
|
||||
ObserverFactory.currentFactory = LDObserverFactory()
|
||||
|
||||
self.setTunnelNetworkSettings(settings) { error in
|
||||
guard error == nil else {
|
||||
@@ -82,36 +122,35 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
completionHandler(error)
|
||||
return
|
||||
}
|
||||
DDLogVerbose("setTunnelNetworkSettings success \(self.packetFlow)")
|
||||
completionHandler(nil)
|
||||
|
||||
self.proxyServer = GCDHTTPProxyServer(address: IPAddress(fromString: self.proxyServerAddress), port: Port(port: self.proxyServerPort))
|
||||
do {
|
||||
try self.proxyServer.start()
|
||||
completionHandler(nil)
|
||||
}
|
||||
catch let proxyError {
|
||||
DDLogError("Error starting proxy server \(proxyError)")
|
||||
completionHandler(proxyError)
|
||||
}
|
||||
do {
|
||||
try self.proxyServer.start()
|
||||
completionHandler(nil)
|
||||
}
|
||||
catch let proxyError {
|
||||
DDLogError("Error starting proxy server \(proxyError)")
|
||||
completionHandler(proxyError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
||||
DDLogVerbose("stopTunnel with reason: \(reason)")
|
||||
db = nil
|
||||
DNSServer.currentServer = nil
|
||||
RawSocketFactory.TunnelProvider = nil
|
||||
ObserverFactory.currentFactory = nil
|
||||
proxyServer.stop()
|
||||
proxyServer = nil
|
||||
completionHandler()
|
||||
exit(EXIT_SUCCESS)
|
||||
}
|
||||
|
||||
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
|
||||
DDLogVerbose("handleAppMessage")
|
||||
RawSocketFactory.TunnelProvider = nil
|
||||
ObserverFactory.currentFactory = nil
|
||||
proxyServer.stop()
|
||||
proxyServer = nil
|
||||
filterDomains = nil
|
||||
filterOptions = nil
|
||||
completionHandler()
|
||||
exit(EXIT_SUCCESS)
|
||||
}
|
||||
|
||||
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
|
||||
reloadDomainFilter()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
35
GlassVPN/robbiehanson-CocoaAsyncSocket/LICENSE.txt
Normal file
@@ -0,0 +1,35 @@
|
||||
This library is in the public domain.
|
||||
However, not all organizations are allowed to use such a license.
|
||||
For example, Germany doesn't recognize the Public Domain and one is not allowed to use libraries under such license (or similar).
|
||||
|
||||
Thus, the library is now dual licensed,
|
||||
and one is allowed to choose which license they would like to use.
|
||||
|
||||
##################################################
|
||||
License Option #1 :
|
||||
##################################################
|
||||
|
||||
Public Domain
|
||||
|
||||
##################################################
|
||||
License Option #2 :
|
||||
##################################################
|
||||
|
||||
Software License Agreement (BSD License)
|
||||
|
||||
Copyright (c) 2017, Deusty, LLC
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use of this software in source and binary forms,
|
||||
with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the
|
||||
following disclaimer.
|
||||
|
||||
* Neither the name of Deusty LLC nor the names of its
|
||||
contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior
|
||||
written permission of Deusty LLC.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
27
GlassVPN/zhuhaow-NEKit/LICENSE.md
Normal file
@@ -0,0 +1,27 @@
|
||||
Copyright (c) 2016, Zhuhao Wang
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of NEKit nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
9
GlassVPN/zhuhaow-Resolver/License
Normal file
@@ -0,0 +1,9 @@
|
||||
The MIT License
|
||||
|
||||
Copyright 2018 Zhuhao Wang
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
49
README.md
Normal file
@@ -0,0 +1,49 @@
|
||||
AppCheck – Privacy Monitor
|
||||
==========================
|
||||
|
||||
A pocket DNS monitor and network filter.
|
||||
|
||||

|
||||
|
||||
|
||||
## What is it?
|
||||
|
||||
AppCheck helps you identify which applications communicate with third parties.
|
||||
It does so by logging network requests.
|
||||
AppCheck learns only the destination addresses, not the actual data that is exchanged.
|
||||
|
||||
Your data belongs to you.
|
||||
Therefore, monitoring and analysis take place on your device only.
|
||||
The app does not share any data with us or any other third-party – unless you choose to.
|
||||
|
||||
|
||||
### How does it work?
|
||||
|
||||
AppCheck creates a local VPN tunnel to intercept all network connections.
|
||||
For each connection AppCheck looks into the DNS headers only, namely the domain names.
|
||||
These domain names are logged in the background while the VPN is active.
|
||||
That means, AppCheck does not have to be active in the foreground all the time.
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
- See outgoing (DNS) network requests in real-time
|
||||
- See history of previous connections
|
||||
- Block unwanted traffic based on domain names
|
||||
- Record app specific activity<sup>1</sup>
|
||||
- Apply logging filters
|
||||
|
||||
**… and soon:**
|
||||
|
||||
- Alert Monitor & reminder
|
||||
- Occurrence Context Analysis
|
||||
- Participate in privacy research
|
||||
|
||||
|
||||
<sup>1</sup> Due to technical limitations, recording is not limited to any single application. Remember to force-quit all other applications before starting a recording.
|
||||
|
||||
|
||||
## Research Project
|
||||
|
||||
*information will be added soon*
|
||||
|
||||
BIN
doc/screenshot.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
@@ -14,16 +14,23 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
UserDefaults.standard.set(false, forKey: "kill_db")
|
||||
SQLiteDatabase.destroyDatabase()
|
||||
}
|
||||
try? SQLiteDatabase.open().initScheme()
|
||||
if let db = AppDB {
|
||||
db.initCommonScheme()
|
||||
db.initAppOnlyScheme()
|
||||
}
|
||||
|
||||
DBWrp.initContentOfDB()
|
||||
#if IOS_SIMULATOR
|
||||
TestDataSource.load()
|
||||
#endif
|
||||
|
||||
loadVPN { mgr in
|
||||
self.managerVPN = mgr
|
||||
self.postVPNState()
|
||||
}
|
||||
NSNotification.Name.NEVPNStatusDidChange.observe(call: #selector(vpnStatusChanged(_:)), on: self)
|
||||
NotifyFilterChanged.observe(call: #selector(filterDidChange), on: self)
|
||||
NotifyDNSFilterChanged.observe(call: #selector(didChangeDomainFilter), on: self)
|
||||
|
||||
sync.start()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -31,7 +38,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
postRawVPNState((notification.object as? NETunnelProviderSession)?.status ?? .invalid)
|
||||
}
|
||||
|
||||
@objc private func filterDidChange() {
|
||||
@objc private func didChangeDomainFilter() {
|
||||
// Notify VPN extension about changes
|
||||
if let session = self.managerVPN?.connection as? NETunnelProviderSession,
|
||||
session.status == .connected {
|
||||
|
||||
BIN
main/Assets.xcassets/.DS_Store
vendored
Normal file
23
main/Assets.xcassets/filter-clear.imageset/Contents.json
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "img.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"filename" : "img@2x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"filename" : "img@3x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
BIN
main/Assets.xcassets/filter-clear.imageset/img.png
vendored
Normal file
|
After Width: | Height: | Size: 187 B |
BIN
main/Assets.xcassets/filter-clear.imageset/img@2x.png
vendored
Normal file
|
After Width: | Height: | Size: 289 B |
BIN
main/Assets.xcassets/filter-clear.imageset/img@3x.png
vendored
Normal file
|
After Width: | Height: | Size: 395 B |
23
main/Assets.xcassets/filter-filled.imageset/Contents.json
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "img.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"filename" : "img@2x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"filename" : "img@3x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
BIN
main/Assets.xcassets/filter-filled.imageset/img.png
vendored
Normal file
|
After Width: | Height: | Size: 155 B |
BIN
main/Assets.xcassets/filter-filled.imageset/img@2x.png
vendored
Normal file
|
After Width: | Height: | Size: 226 B |
BIN
main/Assets.xcassets/filter-filled.imageset/img@3x.png
vendored
Normal file
|
After Width: | Height: | Size: 302 B |
23
main/Assets.xcassets/intersection.imageset/Contents.json
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "img.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"filename" : "img@2x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"filename" : "img@3x.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
BIN
main/Assets.xcassets/intersection.imageset/img.png
vendored
Normal file
|
After Width: | Height: | Size: 385 B |
BIN
main/Assets.xcassets/intersection.imageset/img@2x.png
vendored
Normal file
|
After Width: | Height: | Size: 695 B |
BIN
main/Assets.xcassets/intersection.imageset/img@3x.png
vendored
Normal file
|
After Width: | Height: | Size: 1.0 KiB |
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16096" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="sfA-EG-18J">
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="sfA-EG-18J">
|
||||
<device id="retina4_0" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
@@ -44,6 +44,237 @@
|
||||
</objects>
|
||||
<point key="canvasLocation" x="0.0" y="-1250"/>
|
||||
</scene>
|
||||
<!--Date Filter-->
|
||||
<scene sceneID="GqC-c0-bWe">
|
||||
<objects>
|
||||
<viewController storyboardIdentifier="domainFilter" modalTransitionStyle="crossDissolve" id="r7v-PM-PrR" customClass="VCDateFilter" customModule="AppCheck" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<view key="view" contentMode="scaleToFill" id="QBv-5g-BTH">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<navigationBar hidden="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="jAM-LN-evh">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<items>
|
||||
<navigationItem title="Placeholder" id="s5o-aw-nIo">
|
||||
<barButtonItem key="leftBarButtonItem" title="Item" image="filter-clear" id="oMW-R3-3Eh"/>
|
||||
</navigationItem>
|
||||
</items>
|
||||
</navigationBar>
|
||||
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="pEc-vv-7Ts">
|
||||
<rect key="frame" x="8" y="64" width="233.5" height="391.5"/>
|
||||
<subviews>
|
||||
<segmentedControl opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="plain" selectedSegmentIndex="0" translatesAutoresizingMaskIntoConstraints="NO" id="UNT-qn-2cg">
|
||||
<rect key="frame" x="8" y="8" width="217.5" height="32"/>
|
||||
<segments>
|
||||
<segment title="Most recent"/>
|
||||
<segment title="Date Range"/>
|
||||
</segments>
|
||||
<connections>
|
||||
<action selector="didChangeFilterBy:" destination="r7v-PM-PrR" eventType="valueChanged" id="kM6-QE-ZGV"/>
|
||||
</connections>
|
||||
</segmentedControl>
|
||||
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="15" translatesAutoresizingMaskIntoConstraints="NO" id="gEf-Ra-RyA">
|
||||
<rect key="frame" x="10" y="47" width="213.5" height="334.5"/>
|
||||
<subviews>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Show entries no older than" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="UBq-oH-pKp">
|
||||
<rect key="frame" x="0.0" y="0.0" width="213.5" height="20.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleHeadline"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="ucF-MH-iRP">
|
||||
<rect key="frame" x="0.0" y="35.5" width="213.5" height="50"/>
|
||||
<subviews>
|
||||
<slider opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" value="0.5" minValue="0.0" maxValue="1" translatesAutoresizingMaskIntoConstraints="NO" id="qhe-6d-hGB">
|
||||
<rect key="frame" x="-2" y="0.0" width="155.5" height="51"/>
|
||||
<connections>
|
||||
<action selector="durationSliderChanged:" destination="r7v-PM-PrR" eventType="valueChanged" id="nQB-w9-dY1"/>
|
||||
</connections>
|
||||
</slider>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="7 days" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ika-su-PZQ">
|
||||
<rect key="frame" x="159.5" y="16" width="54" height="18"/>
|
||||
<constraints>
|
||||
<constraint firstAttribute="width" secondItem="ika-su-PZQ" secondAttribute="height" multiplier="3" id="o9m-cy-kkn"/>
|
||||
</constraints>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<constraints>
|
||||
<constraint firstItem="qhe-6d-hGB" firstAttribute="leading" secondItem="ucF-MH-iRP" secondAttribute="leading" id="EGU-ln-lJF"/>
|
||||
<constraint firstItem="ika-su-PZQ" firstAttribute="trailing" secondItem="ucF-MH-iRP" secondAttribute="trailing" id="KLs-Ft-wSo"/>
|
||||
<constraint firstItem="qhe-6d-hGB" firstAttribute="bottom" secondItem="ucF-MH-iRP" secondAttribute="bottom" id="PTR-Et-Klv"/>
|
||||
<constraint firstItem="ika-su-PZQ" firstAttribute="leading" secondItem="qhe-6d-hGB" secondAttribute="trailing" constant="8" symbolic="YES" id="aHy-IX-X4B"/>
|
||||
<constraint firstItem="ika-su-PZQ" firstAttribute="centerY" secondItem="qhe-6d-hGB" secondAttribute="centerY" id="cHs-5z-CHK"/>
|
||||
<constraint firstItem="qhe-6d-hGB" firstAttribute="top" secondItem="ucF-MH-iRP" secondAttribute="top" id="eJC-d4-zg0"/>
|
||||
</constraints>
|
||||
</view>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Show entries within range" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="rtf-o1-gk6">
|
||||
<rect key="frame" x="0.0" y="100.5" width="213.5" height="20.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleHeadline"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="9As-hA-MKt">
|
||||
<rect key="frame" x="0.0" y="136" width="213.5" height="74"/>
|
||||
<subviews>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="From:" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="wAd-o2-PHY">
|
||||
<rect key="frame" x="0.0" y="6.5" width="44" height="20.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="FVD-kB-91w">
|
||||
<rect key="frame" x="52" y="0.0" width="161.5" height="33"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleHeadline"/>
|
||||
<state key="normal" title="1970-01-01 01:00"/>
|
||||
<connections>
|
||||
<action selector="didTapRangeButton:" destination="r7v-PM-PrR" eventType="touchUpInside" id="g05-Sc-0P2"/>
|
||||
</connections>
|
||||
</button>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="To:" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fzL-94-c0l">
|
||||
<rect key="frame" x="0.0" y="47.5" width="44" height="20.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IG3-Wc-UI4">
|
||||
<rect key="frame" x="52" y="41" width="161.5" height="33"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleHeadline"/>
|
||||
<state key="normal" title="1970-01-01 01:00"/>
|
||||
<connections>
|
||||
<action selector="didTapRangeButton:" destination="r7v-PM-PrR" eventType="touchUpInside" id="63v-sy-Bpo"/>
|
||||
</connections>
|
||||
</button>
|
||||
</subviews>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<constraints>
|
||||
<constraint firstItem="FVD-kB-91w" firstAttribute="top" secondItem="9As-hA-MKt" secondAttribute="top" id="J2e-NO-NUD"/>
|
||||
<constraint firstItem="IG3-Wc-UI4" firstAttribute="top" secondItem="FVD-kB-91w" secondAttribute="bottom" constant="8" symbolic="YES" id="Jyg-b6-5rH"/>
|
||||
<constraint firstItem="fzL-94-c0l" firstAttribute="centerY" secondItem="IG3-Wc-UI4" secondAttribute="centerY" id="LAG-jg-nBi"/>
|
||||
<constraint firstItem="wAd-o2-PHY" firstAttribute="trailing" secondItem="fzL-94-c0l" secondAttribute="trailing" id="Lav-7y-PUJ"/>
|
||||
<constraint firstItem="IG3-Wc-UI4" firstAttribute="trailing" secondItem="9As-hA-MKt" secondAttribute="trailing" id="XqI-1p-FNv"/>
|
||||
<constraint firstItem="FVD-kB-91w" firstAttribute="leading" secondItem="wAd-o2-PHY" secondAttribute="trailing" constant="8" symbolic="YES" id="YlE-w7-CZ5"/>
|
||||
<constraint firstItem="FVD-kB-91w" firstAttribute="trailing" secondItem="9As-hA-MKt" secondAttribute="trailing" id="a6D-1D-HvF"/>
|
||||
<constraint firstItem="wAd-o2-PHY" firstAttribute="leading" secondItem="fzL-94-c0l" secondAttribute="leading" id="bM0-gJ-IW5"/>
|
||||
<constraint firstItem="wAd-o2-PHY" firstAttribute="centerY" secondItem="FVD-kB-91w" secondAttribute="centerY" id="g7F-LP-PQQ"/>
|
||||
<constraint firstItem="IG3-Wc-UI4" firstAttribute="bottom" secondItem="9As-hA-MKt" secondAttribute="bottom" priority="750" id="jlK-69-8hl"/>
|
||||
<constraint firstItem="IG3-Wc-UI4" firstAttribute="leading" secondItem="fzL-94-c0l" secondAttribute="trailing" constant="8" symbolic="YES" id="pcE-Gv-oj7"/>
|
||||
<constraint firstItem="wAd-o2-PHY" firstAttribute="leading" secondItem="9As-hA-MKt" secondAttribute="leading" id="zgR-pJ-vFs"/>
|
||||
</constraints>
|
||||
</view>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Order by" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="9Fe-5F-TVt">
|
||||
<rect key="frame" x="0.0" y="225" width="213.5" height="20.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleHeadline"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="cWy-un-IHC">
|
||||
<rect key="frame" x="0.0" y="260.5" width="213.5" height="74"/>
|
||||
<subviews>
|
||||
<segmentedControl opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="plain" selectedSegmentIndex="0" translatesAutoresizingMaskIntoConstraints="NO" id="UKE-MR-kRJ">
|
||||
<rect key="frame" x="-2" y="0.0" width="217.5" height="36"/>
|
||||
<segments>
|
||||
<segment title="Date"/>
|
||||
<segment title="Name"/>
|
||||
<segment title="Count"/>
|
||||
</segments>
|
||||
</segmentedControl>
|
||||
<segmentedControl opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="plain" selectedSegmentIndex="0" translatesAutoresizingMaskIntoConstraints="NO" id="eG2-a4-zm5">
|
||||
<rect key="frame" x="-2" y="43" width="217.5" height="32"/>
|
||||
<segments>
|
||||
<segment title="Ascending"/>
|
||||
<segment title="Descending"/>
|
||||
</segments>
|
||||
</segmentedControl>
|
||||
</subviews>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<constraints>
|
||||
<constraint firstItem="eG2-a4-zm5" firstAttribute="top" secondItem="UKE-MR-kRJ" secondAttribute="bottom" constant="8" symbolic="YES" id="6oC-bZ-XdM"/>
|
||||
<constraint firstItem="eG2-a4-zm5" firstAttribute="leading" secondItem="cWy-un-IHC" secondAttribute="leading" constant="-2" id="7R0-qB-J0u"/>
|
||||
<constraint firstAttribute="bottom" secondItem="eG2-a4-zm5" secondAttribute="bottom" id="JbN-vA-Rd5"/>
|
||||
<constraint firstItem="UKE-MR-kRJ" firstAttribute="top" secondItem="cWy-un-IHC" secondAttribute="top" id="L21-Kf-g2d"/>
|
||||
<constraint firstAttribute="trailing" secondItem="eG2-a4-zm5" secondAttribute="trailing" constant="-2" id="cbD-H9-e1Q"/>
|
||||
<constraint firstItem="UKE-MR-kRJ" firstAttribute="leading" secondItem="cWy-un-IHC" secondAttribute="leading" constant="-2" id="lKB-g4-asw"/>
|
||||
<constraint firstAttribute="trailing" secondItem="UKE-MR-kRJ" secondAttribute="trailing" constant="-2" id="xIa-X2-0Lp"/>
|
||||
</constraints>
|
||||
</view>
|
||||
</subviews>
|
||||
</stackView>
|
||||
</subviews>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<constraints>
|
||||
<constraint firstItem="UNT-qn-2cg" firstAttribute="top" secondItem="pEc-vv-7Ts" secondAttribute="top" constant="8" id="Awu-uv-9wF"/>
|
||||
<constraint firstItem="UNT-qn-2cg" firstAttribute="leading" secondItem="pEc-vv-7Ts" secondAttribute="leading" constant="8" id="Icx-YR-5bc"/>
|
||||
<constraint firstItem="gEf-Ra-RyA" firstAttribute="top" secondItem="UNT-qn-2cg" secondAttribute="bottom" constant="8" symbolic="YES" id="QPi-aa-6ff"/>
|
||||
<constraint firstItem="UNT-qn-2cg" firstAttribute="trailing" secondItem="pEc-vv-7Ts" secondAttribute="trailing" constant="-8" id="Sof-6L-T2D"/>
|
||||
<constraint firstItem="gEf-Ra-RyA" firstAttribute="bottom" secondItem="pEc-vv-7Ts" secondAttribute="bottom" constant="-10" id="TMx-5J-z2P"/>
|
||||
<constraint firstItem="gEf-Ra-RyA" firstAttribute="leading" secondItem="pEc-vv-7Ts" secondAttribute="leading" constant="10" id="U6l-7M-bm4"/>
|
||||
<constraint firstItem="gEf-Ra-RyA" firstAttribute="trailing" secondItem="pEc-vv-7Ts" secondAttribute="trailing" constant="-10" id="YKE-TR-fTB"/>
|
||||
</constraints>
|
||||
<userDefinedRuntimeAttributes>
|
||||
<userDefinedRuntimeAttribute type="number" keyPath="layer.cornerRadius">
|
||||
<integer key="value" value="12"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
</userDefinedRuntimeAttributes>
|
||||
</view>
|
||||
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="sAi-8j-0n1" customClass="PopupTriangle" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="14" y="46" width="28" height="22"/>
|
||||
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<constraints>
|
||||
<constraint firstAttribute="height" constant="22" id="MaD-aD-U8h"/>
|
||||
<constraint firstAttribute="width" constant="28" id="ntP-rP-UMh"/>
|
||||
</constraints>
|
||||
<userDefinedRuntimeAttributes>
|
||||
<userDefinedRuntimeAttribute type="color" keyPath="color">
|
||||
<color key="value" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
</userDefinedRuntimeAttributes>
|
||||
</view>
|
||||
</subviews>
|
||||
<color key="backgroundColor" white="0.0" alpha="0.2" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<gestureRecognizers/>
|
||||
<constraints>
|
||||
<constraint firstItem="sAi-8j-0n1" firstAttribute="bottom" secondItem="pEc-vv-7Ts" secondAttribute="top" constant="4" id="DCq-Ps-sQo"/>
|
||||
<constraint firstItem="pEc-vv-7Ts" firstAttribute="top" secondItem="jAM-LN-evh" secondAttribute="bottom" constant="20" id="EdA-nv-DEa"/>
|
||||
<constraint firstItem="pEc-vv-7Ts" firstAttribute="leading" secondItem="u0F-hK-vVD" secondAttribute="leading" constant="8" id="Iow-GV-Lxy"/>
|
||||
<constraint firstItem="jAM-LN-evh" firstAttribute="trailing" secondItem="u0F-hK-vVD" secondAttribute="trailing" id="Lju-K6-G89"/>
|
||||
<constraint firstItem="jAM-LN-evh" firstAttribute="top" secondItem="u0F-hK-vVD" secondAttribute="top" id="MqW-YU-POp"/>
|
||||
<constraint firstItem="u0F-hK-vVD" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="pEc-vv-7Ts" secondAttribute="trailing" constant="8" id="V9T-2Y-oNy"/>
|
||||
<constraint firstItem="sAi-8j-0n1" firstAttribute="leading" secondItem="pEc-vv-7Ts" secondAttribute="leading" constant="6" id="cXH-3c-s6t"/>
|
||||
<constraint firstItem="jAM-LN-evh" firstAttribute="leading" secondItem="u0F-hK-vVD" secondAttribute="leading" id="ula-eW-vAq"/>
|
||||
</constraints>
|
||||
<viewLayoutGuide key="safeArea" id="u0F-hK-vVD"/>
|
||||
<connections>
|
||||
<outletCollection property="gestureRecognizers" destination="oRi-17-cVM" appends="YES" id="2pk-5e-eJD"/>
|
||||
</connections>
|
||||
</view>
|
||||
<extendedEdge key="edgesForExtendedLayout" bottom="YES"/>
|
||||
<connections>
|
||||
<outlet property="buttonRangeEnd" destination="IG3-Wc-UI4" id="wAd-ca-bVQ"/>
|
||||
<outlet property="buttonRangeStart" destination="FVD-kB-91w" id="HbX-Vl-uBE"/>
|
||||
<outlet property="durationLabel" destination="ika-su-PZQ" id="1Br-vu-xir"/>
|
||||
<outlet property="durationSlider" destination="qhe-6d-hGB" id="wph-zX-WIz"/>
|
||||
<outlet property="durationTitle" destination="UBq-oH-pKp" id="BEd-Lo-a2v"/>
|
||||
<outlet property="durationView" destination="ucF-MH-iRP" id="TCI-Pp-drf"/>
|
||||
<outlet property="filterBy" destination="UNT-qn-2cg" id="M1J-n8-LHq"/>
|
||||
<outlet property="orderbyAsc" destination="eG2-a4-zm5" id="II1-hc-pyZ"/>
|
||||
<outlet property="orderbyType" destination="UKE-MR-kRJ" id="fK7-dW-MLd"/>
|
||||
<outlet property="rangeTitle" destination="rtf-o1-gk6" id="2DY-xP-VOg"/>
|
||||
<outlet property="rangeView" destination="9As-hA-MKt" id="0Mq-Gi-nF6"/>
|
||||
</connections>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="xTS-RW-xLN" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
|
||||
<tapGestureRecognizer id="oRi-17-cVM">
|
||||
<connections>
|
||||
<outlet property="delegate" destination="r7v-PM-PrR" id="JME-7W-w51"/>
|
||||
</connections>
|
||||
</tapGestureRecognizer>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="700" y="-1950"/>
|
||||
</scene>
|
||||
<!--Domains-->
|
||||
<scene sceneID="MN1-aZ-cZt">
|
||||
<objects>
|
||||
@@ -54,23 +285,23 @@
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" selectionStyle="default" accessoryType="disclosureIndicator" hidesAccessoryWhenEditing="NO" indentationWidth="10" reuseIdentifier="DomainCell" textLabel="0HB-5f-eB1" detailTextLabel="MRe-Eq-gvc" style="IBUITableViewCellStyleSubtitle" id="F8D-aK-j1W">
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="55.5"/>
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="57.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="F8D-aK-j1W" id="FY2-xr-hqh">
|
||||
<rect key="frame" x="0.0" y="0.0" width="293" height="55.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="293" height="57.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="0HB-5f-eB1">
|
||||
<rect key="frame" x="16" y="10" width="33.5" height="20.5"/>
|
||||
<rect key="frame" x="16" y="9" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="MRe-Eq-gvc">
|
||||
<rect key="frame" x="16" y="31.5" width="44" height="14.5"/>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="MRe-Eq-gvc">
|
||||
<rect key="frame" x="16" y="32.5" width="44" height="14.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="12"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleCaption1"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -86,7 +317,20 @@
|
||||
<outlet property="delegate" destination="pdd-aM-sKl" id="3RN-az-SYU"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" title="Domains" id="nY5-jL-QT9"/>
|
||||
<navigationItem key="navigationItem" title="Domains" id="nY5-jL-QT9">
|
||||
<leftBarButtonItems>
|
||||
<barButtonItem image="filter-clear" id="FZm-Ld-jJE">
|
||||
<connections>
|
||||
<action selector="filterButtonTapped:" destination="pdd-aM-sKl" id="Xyy-LF-eCF"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
<barButtonItem enabled="NO" title="7 days" id="wxA-bC-1pN"/>
|
||||
</leftBarButtonItems>
|
||||
</navigationItem>
|
||||
<connections>
|
||||
<outlet property="filterButton" destination="FZm-Ld-jJE" id="g96-Q2-cYX"/>
|
||||
<outlet property="filterButtonDetail" destination="wxA-bC-1pN" id="CgP-oz-aXa"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="jfx-iA-E0v" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
@@ -102,23 +346,23 @@
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="HostCell" textLabel="Rnk-SP-UHm" detailTextLabel="ovQ-lJ-hWJ" style="IBUITableViewCellStyleSubtitle" id="uv0-9B-Zbb">
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="55.5"/>
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="57.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="uv0-9B-Zbb" id="6vH-Du-gCg">
|
||||
<rect key="frame" x="0.0" y="0.0" width="293" height="55.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="293" height="57.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Rnk-SP-UHm">
|
||||
<rect key="frame" x="16" y="10" width="33.5" height="20.5"/>
|
||||
<rect key="frame" x="16" y="9" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="ovQ-lJ-hWJ">
|
||||
<rect key="frame" x="16" y="31.5" width="44" height="14.5"/>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="ovQ-lJ-hWJ">
|
||||
<rect key="frame" x="16" y="32.5" width="44" height="14.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="12"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleCaption1"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -148,21 +392,39 @@
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<tabBar key="tableHeaderView" contentMode="scaleToFill" fixedFrame="YES" translucent="NO" translatesAutoresizingMaskIntoConstraints="NO" id="1Jy-zg-CXR">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="49"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMaxY="YES"/>
|
||||
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<items>
|
||||
<tabBarItem title="Co-Occurrence" image="intersection" id="KXh-kQ-rAF"/>
|
||||
</items>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="h7Z-Qr-pJ5" id="qNN-nI-Kub"/>
|
||||
</connections>
|
||||
</tabBar>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="HostDetailCell" textLabel="J2P-mU-Vad" style="IBUITableViewCellStyleDefault" id="ZCA-Dz-i92">
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="43.5"/>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="HostDetailCell" textLabel="J2P-mU-Vad" detailTextLabel="eWb-mX-udN" style="IBUITableViewCellStyleValue1" id="ZCA-Dz-i92">
|
||||
<rect key="frame" x="0.0" y="77" width="320" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="ZCA-Dz-i92" id="nxe-48-jAQ">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" enabled="NO" adjustsFontSizeToFit="NO" id="J2P-mU-Vad">
|
||||
<rect key="frame" x="16" y="0.0" width="288" height="43.5"/>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="J2P-mU-Vad">
|
||||
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="eWb-mX-udN">
|
||||
<rect key="frame" x="260" y="12" width="44" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
@@ -173,11 +435,211 @@
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" title="Occurrences" prompt="com.domain.network.cdn" id="bys-2u-rHs"/>
|
||||
<connections>
|
||||
<outlet property="actionsBar" destination="1Jy-zg-CXR" id="7x3-Vy-i9C"/>
|
||||
<segue destination="W5Q-oz-bFb" kind="modal" identifier="segueAnalysisCoOccurrence" id="ukY-Dy-AIA"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="UxH-PH-KQy" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="2100" y="-1250"/>
|
||||
</scene>
|
||||
<!--Co Occurrence-->
|
||||
<scene sceneID="Gbm-AP-b72">
|
||||
<objects>
|
||||
<viewController id="W5Q-oz-bFb" customClass="VCCoOccurrence" customModule="AppCheck" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<view key="view" contentMode="scaleToFill" id="f34-NO-d8f">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="548"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="rvt-nC-2Zr">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="56"/>
|
||||
<items>
|
||||
<navigationItem title="Co-Occurrence" id="csY-x8-Rpe">
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="done" id="eg9-p3-Xas">
|
||||
<connections>
|
||||
<action selector="didClose:" destination="W5Q-oz-bFb" id="wyw-vo-6xL"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
<barButtonItem key="rightBarButtonItem" id="bTi-7F-CFS">
|
||||
<button key="customView" opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="infoLight" showsTouchWhenHighlighted="YES" lineBreakMode="middleTruncation" id="kqK-SL-CxZ">
|
||||
<rect key="frame" x="279" y="16" width="25" height="24"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<connections>
|
||||
<action selector="showInfoScreen" destination="W5Q-oz-bFb" eventType="touchUpInside" id="TuI-R9-PNr"/>
|
||||
</connections>
|
||||
</button>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
</items>
|
||||
</navigationBar>
|
||||
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" allowsSelection="NO" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="PGb-pB-cfO">
|
||||
<rect key="frame" x="0.0" y="56" width="320" height="492"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<segmentedControl key="tableHeaderView" opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="plain" selectedSegmentIndex="0" id="7ye-tU-pdo">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="32"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<segments>
|
||||
<segment title="10s"/>
|
||||
<segment title="30s"/>
|
||||
</segments>
|
||||
<connections>
|
||||
<action selector="didChangeTime:" destination="W5Q-oz-bFb" eventType="valueChanged" id="c5h-JG-S19"/>
|
||||
</connections>
|
||||
</segmentedControl>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="CoOccurrenceCell" rowHeight="72" id="2qH-Bh-644" customClass="CoOccurrenceCell" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="0.0" y="60" width="320" height="72"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="2qH-Bh-644" id="Lwk-Uj-viQ">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="72"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="99." textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qaw-ql-zIB" customClass="TagLabel" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="15" y="39.5" width="32" height="21.5"/>
|
||||
<color key="backgroundColor" systemColor="secondarySystemBackgroundColor" red="0.94901960780000005" green="0.94901960780000005" blue="0.96862745100000003" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<constraints>
|
||||
<constraint firstAttribute="width" secondItem="qaw-ql-zIB" secondAttribute="height" multiplier="3:2" id="VOJ-f5-xhk"/>
|
||||
</constraints>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleFootnote"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="zbU-wC-qJG">
|
||||
<rect key="frame" x="15" y="11" width="290" height="20.5"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" horizontalCompressionResistancePriority="500" insetsLayoutMarginsFromSafeArea="NO" text="Count" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="JWp-6l-HTJ">
|
||||
<rect key="frame" x="109.5" y="42.5" width="37" height="16"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleFootnote"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="5900" textAlignment="natural" lineBreakMode="clip" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="q5v-FM-iGo" customClass="TagLabel" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="150.5" y="39.5" width="42.5" height="21.5"/>
|
||||
<color key="backgroundColor" systemColor="secondarySystemBackgroundColor" red="0.94901960780000005" green="0.94901960780000005" blue="0.96862745100000003" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleFootnote"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
<userDefinedRuntimeAttributes>
|
||||
<userDefinedRuntimeAttribute type="number" keyPath="padRight">
|
||||
<real key="value" value="1"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
</userDefinedRuntimeAttributes>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="10.35s" textAlignment="natural" lineBreakMode="clip" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="zCg-I0-4Tz" customClass="TagLabel" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="255.5" y="39.5" width="49.5" height="21.5"/>
|
||||
<color key="backgroundColor" systemColor="secondarySystemBackgroundColor" red="0.94901960780000005" green="0.94901960780000005" blue="0.96862745100000003" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleFootnote"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
<userDefinedRuntimeAttributes>
|
||||
<userDefinedRuntimeAttribute type="number" keyPath="padRight">
|
||||
<real key="value" value="1"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
</userDefinedRuntimeAttributes>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" horizontalHuggingPriority="750" horizontalCompressionResistancePriority="400" insetsLayoutMarginsFromSafeArea="NO" text="Diverge" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="T4X-cn-msT">
|
||||
<rect key="frame" x="205" y="42.5" width="46.5" height="16"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleFootnote"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<view opaque="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="9Bb-e5-D3O" customClass="MeterBar" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="190" y="39.5" width="3" height="21.5"/>
|
||||
<constraints>
|
||||
<constraint firstAttribute="width" constant="3" id="wWb-VG-Kqa"/>
|
||||
</constraints>
|
||||
<userDefinedRuntimeAttributes>
|
||||
<userDefinedRuntimeAttribute type="number" keyPath="percent">
|
||||
<real key="value" value="1"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
<userDefinedRuntimeAttribute type="color" keyPath="barColor">
|
||||
<color key="value" systemColor="systemOrangeColor" red="1" green="0.58431372550000005" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
</userDefinedRuntimeAttributes>
|
||||
</view>
|
||||
<view opaque="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="JwY-mq-rYZ" customClass="MeterBar" customModule="AppCheck" customModuleProvider="target">
|
||||
<rect key="frame" x="302" y="39.5" width="3" height="21.5"/>
|
||||
<constraints>
|
||||
<constraint firstAttribute="width" constant="3" id="Tta-m5-vwa"/>
|
||||
</constraints>
|
||||
<userDefinedRuntimeAttributes>
|
||||
<userDefinedRuntimeAttribute type="number" keyPath="percent">
|
||||
<real key="value" value="1"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
<userDefinedRuntimeAttribute type="color" keyPath="barColor">
|
||||
<color key="value" systemColor="systemOrangeColor" red="1" green="0.58431372550000005" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</userDefinedRuntimeAttribute>
|
||||
</userDefinedRuntimeAttributes>
|
||||
</view>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="qaw-ql-zIB" firstAttribute="height" secondItem="q5v-FM-iGo" secondAttribute="height" id="2Ug-qN-ido"/>
|
||||
<constraint firstItem="zbU-wC-qJG" firstAttribute="leading" secondItem="Lwk-Uj-viQ" secondAttribute="leadingMargin" id="2Zo-jC-08y"/>
|
||||
<constraint firstItem="JwY-mq-rYZ" firstAttribute="top" secondItem="zCg-I0-4Tz" secondAttribute="top" id="3MU-gk-eUU"/>
|
||||
<constraint firstItem="T4X-cn-msT" firstAttribute="height" secondItem="zCg-I0-4Tz" secondAttribute="height" multiplier="0.75" id="AwE-JC-MFF"/>
|
||||
<constraint firstAttribute="bottomMargin" secondItem="q5v-FM-iGo" secondAttribute="bottom" id="B2M-MQ-kAw"/>
|
||||
<constraint firstItem="9Bb-e5-D3O" firstAttribute="bottom" secondItem="q5v-FM-iGo" secondAttribute="bottom" id="Efb-Ud-lxb"/>
|
||||
<constraint firstItem="JWp-6l-HTJ" firstAttribute="height" secondItem="q5v-FM-iGo" secondAttribute="height" multiplier="0.75" id="Gfb-up-g1b"/>
|
||||
<constraint firstItem="JwY-mq-rYZ" firstAttribute="trailing" secondItem="zCg-I0-4Tz" secondAttribute="trailing" id="RlS-DQ-pdh"/>
|
||||
<constraint firstItem="zCg-I0-4Tz" firstAttribute="leading" secondItem="T4X-cn-msT" secondAttribute="trailing" constant="4" id="VpT-5w-aKh"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="zCg-I0-4Tz" secondAttribute="trailing" id="ai7-PW-ISq"/>
|
||||
<constraint firstItem="qaw-ql-zIB" firstAttribute="leading" secondItem="Lwk-Uj-viQ" secondAttribute="leadingMargin" id="bGT-hc-lSG"/>
|
||||
<constraint firstItem="JWp-6l-HTJ" firstAttribute="height" secondItem="T4X-cn-msT" secondAttribute="height" id="cKO-4d-ikl"/>
|
||||
<constraint firstItem="JWp-6l-HTJ" firstAttribute="centerY" secondItem="q5v-FM-iGo" secondAttribute="centerY" id="dZr-0G-1sp"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="zbU-wC-qJG" secondAttribute="trailing" id="e7x-RS-YWo"/>
|
||||
<constraint firstItem="JwY-mq-rYZ" firstAttribute="bottom" secondItem="zCg-I0-4Tz" secondAttribute="bottom" id="fAV-yh-H1r"/>
|
||||
<constraint firstItem="9Bb-e5-D3O" firstAttribute="trailing" secondItem="q5v-FM-iGo" secondAttribute="trailing" id="fFF-y3-qOe"/>
|
||||
<constraint firstItem="qaw-ql-zIB" firstAttribute="top" secondItem="zbU-wC-qJG" secondAttribute="bottom" constant="8" symbolic="YES" id="fgw-q8-YRD"/>
|
||||
<constraint firstItem="9Bb-e5-D3O" firstAttribute="top" secondItem="q5v-FM-iGo" secondAttribute="top" id="idg-nm-vIj"/>
|
||||
<constraint firstItem="T4X-cn-msT" firstAttribute="leading" secondItem="q5v-FM-iGo" secondAttribute="trailing" constant="12" id="kZj-Tn-BQ3"/>
|
||||
<constraint firstItem="zbU-wC-qJG" firstAttribute="top" secondItem="Lwk-Uj-viQ" secondAttribute="top" constant="11" id="o7o-M0-sA2"/>
|
||||
<constraint firstItem="q5v-FM-iGo" firstAttribute="top" secondItem="zbU-wC-qJG" secondAttribute="bottom" constant="8" symbolic="YES" id="peW-Pg-5WC"/>
|
||||
<constraint firstItem="zCg-I0-4Tz" firstAttribute="top" secondItem="zbU-wC-qJG" secondAttribute="bottom" constant="8" symbolic="YES" id="ttp-yA-tsi"/>
|
||||
<constraint firstItem="T4X-cn-msT" firstAttribute="centerY" secondItem="zCg-I0-4Tz" secondAttribute="centerY" id="tz9-Vr-fB6"/>
|
||||
<constraint firstItem="JWp-6l-HTJ" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="qaw-ql-zIB" secondAttribute="trailing" constant="8" symbolic="YES" id="xFl-RU-Ynw"/>
|
||||
<constraint firstItem="q5v-FM-iGo" firstAttribute="leading" secondItem="JWp-6l-HTJ" secondAttribute="trailing" constant="4" id="xHw-Pf-daH"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<outlet property="avgdiff" destination="zCg-I0-4Tz" id="Jno-Yc-ngL"/>
|
||||
<outlet property="avgdiffMeter" destination="JwY-mq-rYZ" id="QNx-rP-17Z"/>
|
||||
<outlet property="count" destination="q5v-FM-iGo" id="AFk-93-mhs"/>
|
||||
<outlet property="countMeter" destination="9Bb-e5-D3O" id="zqt-dT-ecT"/>
|
||||
<outlet property="rank" destination="qaw-ql-zIB" id="q6Y-JS-NFU"/>
|
||||
<outlet property="title" destination="zbU-wC-qJG" id="hgV-L0-blX"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="W5Q-oz-bFb" id="7lD-aQ-QhQ"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
</subviews>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<constraints>
|
||||
<constraint firstItem="PGb-pB-cfO" firstAttribute="top" secondItem="rvt-nC-2Zr" secondAttribute="bottom" id="Edp-lx-Xld"/>
|
||||
<constraint firstItem="4eZ-5P-8sz" firstAttribute="bottom" secondItem="PGb-pB-cfO" secondAttribute="bottom" id="OAG-HL-4N4"/>
|
||||
<constraint firstItem="PGb-pB-cfO" firstAttribute="leading" secondItem="4eZ-5P-8sz" secondAttribute="leading" id="V6d-HM-JzJ"/>
|
||||
<constraint firstItem="4eZ-5P-8sz" firstAttribute="trailing" secondItem="rvt-nC-2Zr" secondAttribute="trailing" id="cmE-iH-06W"/>
|
||||
<constraint firstItem="rvt-nC-2Zr" firstAttribute="top" secondItem="4eZ-5P-8sz" secondAttribute="top" id="epT-LW-CJV"/>
|
||||
<constraint firstItem="4eZ-5P-8sz" firstAttribute="trailing" secondItem="PGb-pB-cfO" secondAttribute="trailing" id="j8i-8q-qGS"/>
|
||||
<constraint firstItem="rvt-nC-2Zr" firstAttribute="leading" secondItem="4eZ-5P-8sz" secondAttribute="leading" id="skN-SN-Wu7"/>
|
||||
</constraints>
|
||||
<viewLayoutGuide key="safeArea" id="4eZ-5P-8sz"/>
|
||||
</view>
|
||||
<connections>
|
||||
<outlet property="tableView" destination="PGb-pB-cfO" id="5gT-KC-ce5"/>
|
||||
<outlet property="timeSegment" destination="7ye-tU-pdo" id="2ys-X4-Jff"/>
|
||||
</connections>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="yYY-5U-gct" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="2800" y="-1250"/>
|
||||
</scene>
|
||||
<!--Recordings-->
|
||||
<scene sceneID="ODR-PD-nTU">
|
||||
<objects>
|
||||
@@ -278,23 +740,23 @@
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" accessoryType="detailButton" indentationWidth="10" reuseIdentifier="PreviousRecordCell" textLabel="hr0-Xt-5gV" detailTextLabel="Xav-Ub-clj" style="IBUITableViewCellStyleSubtitle" id="3kW-3B-1bx">
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="55.5"/>
|
||||
<rect key="frame" x="0.0" y="28" width="320" height="57.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="3kW-3B-1bx" id="OKV-a6-jjd">
|
||||
<rect key="frame" x="0.0" y="0.0" width="280" height="55.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="280" height="57.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="hr0-Xt-5gV">
|
||||
<rect key="frame" x="16" y="10" width="33.5" height="20.5"/>
|
||||
<rect key="frame" x="16" y="9" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Xav-Ub-clj">
|
||||
<rect key="frame" x="16" y="31.5" width="44" height="14.5"/>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Xav-Ub-clj">
|
||||
<rect key="frame" x="16" y="32.5" width="44" height="14.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="12"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleCaption1"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -394,7 +856,7 @@
|
||||
3. Line
|
||||
4. Line</string>
|
||||
<color key="textColor" systemColor="labelColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="14"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleFootnote"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="VRk-wv-rhk" id="vej-jI-13V"/>
|
||||
@@ -494,14 +956,14 @@ Duration: 60:00</string>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="rN0-kA-Eln">
|
||||
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="xRp-XG-oKf">
|
||||
<rect key="frame" x="260" y="12" width="44" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -541,7 +1003,7 @@ Duration: 60:00</string>
|
||||
<scene sceneID="gEe-ny-NaU">
|
||||
<objects>
|
||||
<tableViewController id="qdB-ZO-LHY" customClass="TVCSettings" customModule="AppCheck" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" bounces="NO" alwaysBounceVertical="YES" dataMode="static" style="grouped" separatorStyle="default" rowHeight="44" estimatedRowHeight="-1" sectionHeaderHeight="18" sectionFooterHeight="18" id="8kq-PY-wp7">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="grouped" separatorStyle="default" rowHeight="44" estimatedRowHeight="-1" sectionHeaderHeight="18" sectionFooterHeight="18" id="8kq-PY-wp7">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
@@ -563,7 +1025,7 @@ Duration: 60:00</string>
|
||||
</switch>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="VPN Proxy enabled" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Qha-4I-go0">
|
||||
<rect key="frame" x="16" y="12" width="147" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -589,16 +1051,16 @@ Duration: 60:00</string>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Ignore" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="UdM-Zm-G9p">
|
||||
<rect key="frame" x="16" y="14" width="91" height="16"/>
|
||||
<rect key="frame" x="16" y="13" width="91" height="18"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="13"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="0 Domains" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="bHb-Tw-nPR">
|
||||
<rect key="frame" x="113" y="14" width="64.5" height="16"/>
|
||||
<rect key="frame" x="113" y="13" width="73" height="18"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="13"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -616,16 +1078,16 @@ Duration: 60:00</string>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Block" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="fI0-Nt-Ucf">
|
||||
<rect key="frame" x="16" y="14" width="91" height="16"/>
|
||||
<rect key="frame" x="16" y="13" width="91" height="18"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="13"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="0 Domains" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="CGG-47-cdc">
|
||||
<rect key="frame" x="113" y="14" width="64.5" height="16"/>
|
||||
<rect key="frame" x="113" y="13" width="73" height="18"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="13"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -637,10 +1099,60 @@ Duration: 60:00</string>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
<tableViewSection headerTitle="Other Settings" id="wLR-T2-Qxm">
|
||||
<tableViewSection headerTitle="Reset Settings" id="tBs-BI-JqN">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="none" indentationWidth="10" id="Uii-Jp-53c">
|
||||
<rect key="frame" x="0.0" y="299.5" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="Uii-Jp-53c" id="4Fp-Ox-yrk">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="6B5-l4-Hgz">
|
||||
<rect key="frame" x="74.5" y="7" width="171" height="30"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<state key="normal" title="Reset Introduction Alerts"/>
|
||||
<connections>
|
||||
<action selector="resetTutorialAlerts:" destination="qdB-ZO-LHY" eventType="touchUpInside" id="hw8-as-4PZ"/>
|
||||
</connections>
|
||||
</button>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="6B5-l4-Hgz" firstAttribute="centerY" secondItem="4Fp-Ox-yrk" secondAttribute="centerY" id="h2Y-P2-Feo"/>
|
||||
<constraint firstItem="6B5-l4-Hgz" firstAttribute="centerX" secondItem="4Fp-Ox-yrk" secondAttribute="centerX" id="jpA-gA-3jY"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="none" indentationWidth="10" id="Xgc-6Z-IlH">
|
||||
<rect key="frame" x="0.0" y="343.5" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="Xgc-6Z-IlH" id="efR-vn-6MX">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="sE3-Vh-0lM">
|
||||
<rect key="frame" x="111.5" y="7" width="97" height="30"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<state key="normal" title="Delete all logs">
|
||||
<color key="titleColor" systemColor="systemRedColor" red="1" green="0.23137254900000001" blue="0.18823529410000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</state>
|
||||
<connections>
|
||||
<action selector="clearDatabaseResults:" destination="qdB-ZO-LHY" eventType="touchUpInside" id="adR-Yk-zsB"/>
|
||||
</connections>
|
||||
</button>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="sE3-Vh-0lM" firstAttribute="centerX" secondItem="efR-vn-6MX" secondAttribute="centerX" id="TvC-jA-Wp5"/>
|
||||
<constraint firstItem="sE3-Vh-0lM" firstAttribute="centerY" secondItem="efR-vn-6MX" secondAttribute="centerY" id="WoM-cy-cAY"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
<tableViewSection headerTitle="Advanced" id="wLR-T2-Qxm">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="none" indentationWidth="10" id="Qyy-0U-yhd">
|
||||
<rect key="frame" x="0.0" y="299.5" width="320" height="44"/>
|
||||
<rect key="frame" x="0.0" y="443.5" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="Qyy-0U-yhd" id="Mfs-fu-W5k">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
@@ -648,6 +1160,7 @@ Duration: 60:00</string>
|
||||
<subviews>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="9Ko-sD-7x0">
|
||||
<rect key="frame" x="125" y="7" width="70" height="30"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleSubhead"/>
|
||||
<state key="normal" title="Export DB"/>
|
||||
<connections>
|
||||
<action selector="exportDB:" destination="qdB-ZO-LHY" eventType="touchUpInside" id="3gu-WF-3Xa"/>
|
||||
@@ -660,50 +1173,6 @@ Duration: 60:00</string>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="none" indentationWidth="10" id="wzU-8s-HGb">
|
||||
<rect key="frame" x="0.0" y="343.5" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="wzU-8s-HGb" id="aNM-6U-bho">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="S6B-i8-CoC">
|
||||
<rect key="frame" x="74.5" y="7" width="171" height="30"/>
|
||||
<state key="normal" title="Reset Introduction Alerts"/>
|
||||
<connections>
|
||||
<action selector="resetTutorialAlerts:" destination="qdB-ZO-LHY" eventType="touchUpInside" id="0GX-Ko-bk2"/>
|
||||
</connections>
|
||||
</button>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="S6B-i8-CoC" firstAttribute="centerY" secondItem="aNM-6U-bho" secondAttribute="centerY" id="Wet-iT-mke"/>
|
||||
<constraint firstItem="S6B-i8-CoC" firstAttribute="centerX" secondItem="aNM-6U-bho" secondAttribute="centerX" id="qM6-0t-1m4"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="none" indentationWidth="10" id="a9C-Qy-pOf">
|
||||
<rect key="frame" x="0.0" y="387.5" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="a9C-Qy-pOf" id="cUk-4x-Weg">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="17e-nR-aCh">
|
||||
<rect key="frame" x="111.5" y="7" width="97" height="30"/>
|
||||
<state key="normal" title="Delete all logs">
|
||||
<color key="titleColor" systemColor="systemRedColor" red="1" green="0.23137254900000001" blue="0.18823529410000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</state>
|
||||
<connections>
|
||||
<action selector="clearDatabaseResults:" destination="qdB-ZO-LHY" eventType="touchUpInside" id="Rep-Do-4OQ"/>
|
||||
</connections>
|
||||
</button>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="17e-nR-aCh" firstAttribute="centerX" secondItem="cUk-4x-Weg" secondAttribute="centerX" id="dU5-1x-ETF"/>
|
||||
<constraint firstItem="17e-nR-aCh" firstAttribute="centerY" secondItem="cUk-4x-Weg" secondAttribute="centerY" id="nLq-yi-u2E"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
</sections>
|
||||
@@ -742,7 +1211,7 @@ Duration: 60:00</string>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" insetsLayoutMarginsFromSafeArea="NO" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="MrS-rb-RLB">
|
||||
<rect key="frame" x="16" y="0.0" width="288" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
@@ -772,6 +1241,8 @@ Duration: 60:00</string>
|
||||
<segue reference="EzT-Xq-wka"/>
|
||||
</inferredMetricsTieBreakers>
|
||||
<resources>
|
||||
<image name="filter-clear" width="20" height="20"/>
|
||||
<image name="intersection" width="25" height="25"/>
|
||||
<image name="journal" width="25" height="25"/>
|
||||
<image name="settings" width="25" height="25"/>
|
||||
<image name="tag" width="25" height="25"/>
|
||||
|
||||
102
main/Common Classes/DatePickerAlert.swift
Normal file
@@ -0,0 +1,102 @@
|
||||
import UIKit
|
||||
|
||||
class DatePickerAlert: UIViewController {
|
||||
|
||||
override var keyCommands: [UIKeyCommand]? {
|
||||
[UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(didTapCancel))]
|
||||
}
|
||||
|
||||
private var callback: (Date) -> Void
|
||||
private let picker: UIDatePicker = {
|
||||
let x = UIDatePicker()
|
||||
let h = x.sizeThatFits(.zero).height
|
||||
x.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: h)
|
||||
return x
|
||||
}()
|
||||
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
@discardableResult required init(presentIn viewController: UIViewController, configure: ((UIDatePicker) -> Void)? = nil, onSuccess: @escaping (Date) -> Void) {
|
||||
callback = onSuccess
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .custom
|
||||
if #available(iOS 13.0, *) {
|
||||
isModalInPresentation = true
|
||||
}
|
||||
presentIn(viewController, configure)
|
||||
}
|
||||
|
||||
internal override func loadView() {
|
||||
let cancel = QuickUI.button("Discard", target: self, action: #selector(didTapCancel))
|
||||
let save = QuickUI.button("Save", target: self, action: #selector(didTapSave))
|
||||
let now = QuickUI.button("Now", target: self, action: #selector(didTapNow))
|
||||
save.titleLabel?.font = save.titleLabel?.font.bold()
|
||||
now.titleLabel?.font = now.titleLabel?.font.bold()
|
||||
now.setTitleColor(.sysFg, for: .normal)
|
||||
//cancel.setTitleColor(.systemRed, for: .normal)
|
||||
|
||||
let buttons = UIStackView(arrangedSubviews: [cancel, now, save])
|
||||
buttons.axis = .horizontal
|
||||
buttons.distribution = .equalSpacing
|
||||
|
||||
let bg = UIView(frame: picker.frame)
|
||||
bg.frame.size.height += buttons.frame.height + 15
|
||||
bg.frame.origin.y = UIScreen.main.bounds.height - bg.frame.height - 15
|
||||
bg.backgroundColor = .sysBg
|
||||
bg.addSubview(picker)
|
||||
bg.addSubview(buttons)
|
||||
|
||||
let clearBg = UIView()
|
||||
clearBg.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
clearBg.addSubview(bg)
|
||||
|
||||
picker.anchor([.leading, .trailing, .top], to: bg)
|
||||
picker.bottomAnchor =&= buttons.topAnchor
|
||||
buttons.anchor([.leading, .trailing], to: bg, margin: 25)
|
||||
buttons.bottomAnchor =&= bg.bottomAnchor - 15
|
||||
bg.anchor([.leading, .trailing, .bottom], to: clearBg)
|
||||
|
||||
view = clearBg
|
||||
view.isHidden = true // otherwise picker will flash on present
|
||||
}
|
||||
|
||||
@objc private func didTapNow() {
|
||||
picker.date = Date()
|
||||
}
|
||||
|
||||
@objc private func didTapSave() {
|
||||
dismiss(animated: true) {
|
||||
self.callback(self.picker.date)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func didTapCancel() {
|
||||
dismiss(animated: true)
|
||||
}
|
||||
|
||||
private func presentIn(_ viewController: UIViewController, _ configure: ((UIDatePicker) -> Void)? = nil) {
|
||||
viewController.present(self, animated: false) {
|
||||
let control = self.view.subviews.first!
|
||||
let prev = control.frame.origin.y
|
||||
control.frame.origin.y += control.frame.height
|
||||
self.view.isHidden = false
|
||||
|
||||
configure?(self.picker)
|
||||
|
||||
UIView.animate(withDuration: 0.3) {
|
||||
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
|
||||
control.frame.origin.y = prev
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
|
||||
UIView.animate(withDuration: 0.3, animations: {
|
||||
let control = self.view.subviews.first!
|
||||
self.view.backgroundColor = .clear
|
||||
control.frame.origin.y += control.frame.height
|
||||
}) { _ in
|
||||
super.dismiss(animated: false, completion: completion)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
public enum RowAction {
|
||||
case ignore, block, delete
|
||||
// static let all: [RowAction] = [.ignore, .block, .delete]
|
||||
}
|
||||
|
||||
// MARK: - Generic
|
||||
|
||||
protocol EditableRows {
|
||||
func editableRowUserInfo(_ index: IndexPath) -> Any?
|
||||
func editableRowActions(_ index: IndexPath) -> [(RowAction, String)]
|
||||
func editableRowActionColor(_ index: IndexPath, _ action: RowAction) -> UIColor?
|
||||
@discardableResult func editableRowCallback(_ atIndexPath: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool
|
||||
}
|
||||
|
||||
extension EditableRows where Self: UITableViewController {
|
||||
fileprivate func getRowActionsIOS9(_ index: IndexPath) -> [UITableViewRowAction]? {
|
||||
let userInfo = editableRowUserInfo(index)
|
||||
return editableRowActions(index).compactMap { a,t in
|
||||
let x = UITableViewRowAction(style: a == .delete ? .destructive : .normal, title: t) { self.editableRowCallback($1, a, userInfo) }
|
||||
if let color = editableRowActionColor(index, a) {
|
||||
x.backgroundColor = color
|
||||
}
|
||||
return x
|
||||
}
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
fileprivate func getRowActionsIOS11(_ index: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
let userInfo = editableRowUserInfo(index)
|
||||
return UISwipeActionsConfiguration(actions: editableRowActions(index).compactMap { a,t in
|
||||
let x = UIContextualAction(style: a == .delete ? .destructive : .normal, title: t) { $2(self.editableRowCallback(index, a, userInfo)) }
|
||||
x.backgroundColor = editableRowActionColor(index, a)
|
||||
return x
|
||||
})
|
||||
}
|
||||
func editableRowUserInfo(_ index: IndexPath) -> Any? { nil }
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Edit Ignore-Block-Delete
|
||||
|
||||
protocol EditActionsIgnoreBlockDelete : EditableRows {
|
||||
var dataSource: [GroupedDomain] { get set }
|
||||
}
|
||||
extension EditActionsIgnoreBlockDelete where Self: UITableViewController {
|
||||
func editableRowActions(_ index: IndexPath) -> [(RowAction, String)] {
|
||||
let x = dataSource[index.row]
|
||||
if x.domain.starts(with: "#") {
|
||||
return [(.delete, "Delete")]
|
||||
}
|
||||
let b = x.options?.contains(.blocked) ?? false
|
||||
let i = x.options?.contains(.ignored) ?? false
|
||||
return [(.delete, "Delete"), (.block, b ? "Unblock" : "Block"), (.ignore, i ? "Unignore" : "Ignore")]
|
||||
}
|
||||
|
||||
func editableRowActionColor(_: IndexPath, _ action: RowAction) -> UIColor? {
|
||||
action == .block ? .systemOrange : nil
|
||||
}
|
||||
|
||||
func editableRowUserInfo(_ index: IndexPath) -> Any? { dataSource[index.row] }
|
||||
|
||||
func editableRowCallback(_ index: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool {
|
||||
let entry = userInfo as! GroupedDomain
|
||||
switch action {
|
||||
case .ignore: showFilterSheet(entry, .ignored)
|
||||
case .block: showFilterSheet(entry, .blocked)
|
||||
case .delete:
|
||||
AlertDeleteLogs(entry.domain, latest: entry.lastModified) {
|
||||
DBWrp.deleteHistory(domain: entry.domain, since: $0)
|
||||
}.presentIn(self)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func showFilterSheet(_ entry: GroupedDomain, _ filter: FilterOptions) {
|
||||
if entry.options?.contains(filter) ?? false {
|
||||
DBWrp.updateFilter(entry.domain, remove: filter)
|
||||
} else {
|
||||
// TODO: alert sheet
|
||||
DBWrp.updateFilter(entry.domain, add: filter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Extensions
|
||||
extension TVCDomains : EditActionsIgnoreBlockDelete {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
|
||||
extension TVCHosts : EditActionsIgnoreBlockDelete {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Edit Remove
|
||||
|
||||
protocol EditActionsRemove : EditableRows {}
|
||||
extension EditActionsRemove where Self: UITableViewController {
|
||||
func editableRowActions(_: IndexPath) -> [(RowAction, String)] { [(.delete, "Remove")] }
|
||||
func editableRowActionColor(_: IndexPath, _: RowAction) -> UIColor? { nil }
|
||||
}
|
||||
|
||||
// MARK: Extensions
|
||||
extension TVCFilter : EditableRows {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
|
||||
extension TVCPreviousRecords : EditableRows {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
|
||||
extension TVCRecordingDetails : EditableRows {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
418
main/Common Classes/FilterPipeline.swift
Normal file
@@ -0,0 +1,418 @@
|
||||
import UIKit
|
||||
|
||||
protocol FilterPipelineDelegate: AnyObject {
|
||||
/// Call `reloadData()`
|
||||
func filterPipelineDidReset()
|
||||
/// Call `safeDeleteRows()`
|
||||
func filterPipeline(delete rows: [Int])
|
||||
/// Call `safeInsertRow()`
|
||||
func filterPipeline(insert row: Int)
|
||||
/// Call `safeReloadRow()`
|
||||
func filterPipeline(update row: Int)
|
||||
/// Call `safeMoveRow()`
|
||||
func filterPipeline(move oldRow: Int, to newRow: Int)
|
||||
}
|
||||
|
||||
// MARK: - FilterPipeline
|
||||
|
||||
class FilterPipeline<T> {
|
||||
|
||||
private(set) fileprivate var dataSource: [T] = []
|
||||
|
||||
private var pipeline: [PipelineFilter<T>] = []
|
||||
private var display: PipelineSorting<T>!
|
||||
weak var delegate: FilterPipelineDelegate?
|
||||
|
||||
/// - Returns: Number of elements in `projection`
|
||||
@inline(__always) func displayObjectCount() -> Int { display.projection.count }
|
||||
|
||||
/// Dereference `projection` index to `dataSource` index
|
||||
/// - Complexity: O(1)
|
||||
@inline(__always) func displayObject(at index: Int) -> T { dataSource[display.projection[index]] }
|
||||
|
||||
/// Search and return first element in `dataSource` that matches `predicate`.
|
||||
/// - Returns: Index in `dataSource` and found object or `nil` if no matching item found.
|
||||
/// - Complexity: O(*n*), where *n* is the length of the `dataSource`.
|
||||
func dataSourceGet(where predicate: ((T) -> Bool)) -> (index: Int, object: T)? {
|
||||
// TODO: use sorted dataSource for binary lookup?
|
||||
// would require to shift filter and sorting indices for every new element
|
||||
guard let i = dataSource.firstIndex(where: predicate) else {
|
||||
return nil
|
||||
}
|
||||
return (i, dataSource[i])
|
||||
}
|
||||
|
||||
/// Set new data source and re-built filter and display sorting order.
|
||||
/// - Note: Will call `filterPipelineDidReset()`
|
||||
func reset(dataSource: [T]) {
|
||||
self.dataSource = dataSource
|
||||
self.resetFilters()
|
||||
delegate?.filterPipelineDidReset()
|
||||
}
|
||||
|
||||
/// Returns the index set of either the last filter layer, or `dataSource` if no filter is set.
|
||||
fileprivate func lastLayerIndices() -> [Int] {
|
||||
pipeline.last?.selection ?? dataSource.indices.arr()
|
||||
}
|
||||
|
||||
/// Get pipeline index of filter with given identifier
|
||||
private func indexOfFilter(_ identifier: String) -> Int? {
|
||||
pipeline.firstIndex(where: {$0.id == identifier})
|
||||
}
|
||||
|
||||
|
||||
// MARK: manage pipeline
|
||||
|
||||
/// Add new filter layer. Each layer is applied upon the previous layer. Therefore, each filter
|
||||
/// can only restrict the display further. A filter cannot introduce previously removed elements.
|
||||
/// - Warning: Use `[unowned self]` to prevent retain cycles!
|
||||
/// - Note: Will call `filterPipelineDidReset()`
|
||||
/// - Parameters:
|
||||
/// - identifier: Use this id to find the filter again. For reload and remove operations.
|
||||
/// - otherId: If `nil` or non-existent the new filter will be appended at the end.
|
||||
/// - predicate: Return `true` if you want to keep the element.
|
||||
func addFilter(_ identifier: String, before otherId: String? = nil, _ predicate: @escaping PipelineFilter<T>.Predicate) {
|
||||
guard indexOfFilter(identifier) == nil else { return }
|
||||
let newFilter = PipelineFilter(identifier, predicate)
|
||||
if let other = otherId, let i = indexOfFilter(other) {
|
||||
pipeline.insert(newFilter, at: i)
|
||||
resetFilters(startingAt: i)
|
||||
} else {
|
||||
newFilter.reset(to: dataSource, previous: lastLayerIndices())
|
||||
pipeline.append(newFilter)
|
||||
display?.apply(moreRestrictive: newFilter.selection)
|
||||
}
|
||||
delegate?.filterPipelineDidReset()
|
||||
}
|
||||
|
||||
/// Find and remove filter with given identifier. Will automatically update remaining filters and display sorting.
|
||||
/// - Note: Will call `filterPipelineDidReset()`
|
||||
func removeFilter(withId ident: String) {
|
||||
guard let i = indexOfFilter(ident) else { return }
|
||||
pipeline.remove(at: i)
|
||||
if i == pipeline.count {
|
||||
// only if we don't reset other layers we can assure `toLessRestrictive`
|
||||
display?.apply(lessRestrictive: lastLayerIndices())
|
||||
} else {
|
||||
resetFilters(startingAt: i)
|
||||
}
|
||||
delegate?.filterPipelineDidReset()
|
||||
}
|
||||
|
||||
/// Start filter evaluation on all entries from previous filter.
|
||||
/// - Note: Will call `filterPipelineDidReset()`
|
||||
func reloadFilter(withId ident: String) {
|
||||
guard let i = indexOfFilter(ident) else { return }
|
||||
resetFilters(startingAt: i)
|
||||
delegate?.filterPipelineDidReset()
|
||||
}
|
||||
|
||||
/// Sets the sort and display order. You should set the `delegate` to automatically update your `tableView`.
|
||||
/// - Warning: Use `[unowned self]` to prevent retain cycles!
|
||||
/// - Note: Will call `filterPipelineDidReset()`
|
||||
/// - Parameter predicate: Return `true` if first element should be sorted before second element.
|
||||
func setSorting(_ predicate: @escaping PipelineSorting<T>.Predicate) {
|
||||
display = .init(predicate, pipe: self)
|
||||
delegate?.filterPipelineDidReset()
|
||||
}
|
||||
|
||||
/// Will reverse the current display order without resorting. This is faster than setting a new sorting `predicate`.
|
||||
/// However, the `predicate` must be dynamic and support a sort order flag.
|
||||
/// - Note: Will call `filterPipelineDidReset()`
|
||||
/// - Warning: Make sure `predicate` does reflect the change or it will lead to data inconsistency!
|
||||
func reverseSorting() {
|
||||
// TODO: use semaphore to prevent concurrent edits
|
||||
display?.reverseOrder()
|
||||
delegate?.filterPipelineDidReset()
|
||||
}
|
||||
|
||||
/// Re-built filter and display sorting order.
|
||||
/// - Parameter index: Must be: `index <= pipeline.count`
|
||||
private func resetFilters(startingAt index: Int = 0) {
|
||||
for i in index..<pipeline.count {
|
||||
pipeline[i].reset(to: dataSource, previous: (i>0)
|
||||
? pipeline[i-1].selection : dataSource.indices.arr())
|
||||
}
|
||||
// Reset is NOT less-restrictive because filters are dynamic
|
||||
// Calling reset on a filter twice may yield different results
|
||||
// E.g. if filter uses variables outside of scope (current time, search term)
|
||||
display?.reset(to: lastLayerIndices())
|
||||
}
|
||||
|
||||
/// Push object through filter pipeline to check whether it survives all filters.
|
||||
/// - Parameter index: The index of the object in the original `dataSource`
|
||||
/// - Returns: `changed` is `true` if element persists or should be removed with this update.
|
||||
/// `display` indicates whther element should be shown (`true`) or hidden (`false`).
|
||||
/// - Complexity: O(*m* log *n*), where *m* is the number of filters and *n* the number of elements in each filter.
|
||||
private func processPipeline(with obj: T, at index: Int) -> (changed: Bool, display: Bool) {
|
||||
var keepGoing = true
|
||||
for filter in pipeline {
|
||||
let lastIndex: Int?
|
||||
if keepGoing {
|
||||
(keepGoing, lastIndex) = filter.update(obj, at: index)
|
||||
} else {
|
||||
lastIndex = filter.remove(dataSource: index)
|
||||
}
|
||||
// if it isnt in this layer, it wont appear in the following either
|
||||
if lastIndex == nil { return (false, false) }
|
||||
}
|
||||
return (true, keepGoing)
|
||||
}
|
||||
|
||||
|
||||
// MARK: data updates
|
||||
|
||||
/// Add new element to the original `dataSource` and immediately apply filter and sorting.
|
||||
/// - Note: Will call `filterPipeline(insert:)` if not filtered.
|
||||
/// - Complexity: O((*m*+1) log *n*), where *m* is the number of filters and *n* the number of elements in each filter.
|
||||
func addNew(_ obj: T) {
|
||||
let index = dataSource.count
|
||||
dataSource.append(obj)
|
||||
for filter in pipeline {
|
||||
if filter.add(obj, at: index) == nil { return }
|
||||
}
|
||||
// survived all filters
|
||||
let displayIndex = display.insertNew(index)
|
||||
delegate?.filterPipeline(insert: displayIndex)
|
||||
}
|
||||
|
||||
/// Update element at `index` in the original `dataSource` and immediately re-apply filter and sorting.
|
||||
/// - Note: Will call `filterPipeline(delete:)`, `(insert:)`, `(update:)`, or `(move:)`
|
||||
/// - Parameters:
|
||||
/// - obj: Element to be added. Will overwrite previous `dataSource` object.
|
||||
/// - index: Index in the original `dataSource`
|
||||
/// - Complexity: O(*n* + (*m*+1) log *n*), where *m* is the number of filters and *n* the number of elements in each filter / projection.
|
||||
func update(_ obj: T, at index: Int) {
|
||||
let status = processPipeline(with: obj, at: index)
|
||||
guard status.changed else {
|
||||
dataSource[index] = obj // we need to update anyway
|
||||
return
|
||||
}
|
||||
let oldPos = display.deleteOld(index)
|
||||
dataSource[index] = obj
|
||||
guard status.display else {
|
||||
if oldPos != -1 { delegate?.filterPipeline(delete: [oldPos]) }
|
||||
return
|
||||
}
|
||||
let newPos = display.insertNew(index, previousIndex: oldPos)
|
||||
if oldPos == -1 {
|
||||
delegate?.filterPipeline(insert: newPos)
|
||||
} else {
|
||||
if oldPos == newPos {
|
||||
delegate?.filterPipeline(update: oldPos)
|
||||
} else {
|
||||
delegate?.filterPipeline(move: oldPos, to: newPos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove elements from the original `dataSource`, from all filters, and from display sorting.
|
||||
/// - Note: Will call `filterPipeline(delete:)` if `sorted` array is not empty.
|
||||
/// - Parameter sorted: Indices in the original `dataSource`
|
||||
/// - Complexity: O(*t*(*m*+*n*) + *m* log *n*), where *t* is the number of filters,
|
||||
/// *m* the number of elements in each filter / projection, and *n* the length of `sorted` indices.
|
||||
func remove(indices sorted: [Int]) {
|
||||
guard sorted.count > 0 else { return }
|
||||
for i in sorted.reversed() {
|
||||
dataSource.remove(at: i)
|
||||
}
|
||||
for filter in pipeline {
|
||||
filter.shiftRemove(indices: sorted)
|
||||
}
|
||||
let indices = display.shiftRemove(indices: sorted)
|
||||
delegate?.filterPipeline(delete: indices)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Filter
|
||||
|
||||
class PipelineFilter<T>: CustomStringConvertible {
|
||||
var description: String { "\(Self.self)(id: \(id))" }
|
||||
|
||||
typealias Predicate = (T) -> Bool
|
||||
|
||||
let id: String
|
||||
private(set) var selection: [Int] = []
|
||||
private let shouldPersist: Predicate
|
||||
|
||||
/// - Parameter predicate: Return `true` if you want to keep the element
|
||||
required init(_ identifier: String, _ predicate: @escaping Predicate) {
|
||||
self.id = identifier
|
||||
shouldPersist = predicate
|
||||
}
|
||||
|
||||
/// Reset `selection` by copying the indices and applying the filter function
|
||||
fileprivate func reset(to dataSource: [T], previous filterIndices: [Int]) {
|
||||
selection = filterIndices
|
||||
selection.removeAll { !shouldPersist(dataSource[$0]) }
|
||||
}
|
||||
|
||||
/// Apply filter to `obj` and either insert or do nothing.
|
||||
/// - Parameters:
|
||||
/// - obj: Object that should be inserted if filter allows.
|
||||
/// - index: Index of object in original `dataSource`
|
||||
/// - Returns: Index in `selection` or `nil` if `obj` is removed by the filter.
|
||||
/// - Complexity:
|
||||
/// * O(1), if `index` is appended at end.
|
||||
/// * O(log *n*), where *n* is the length of the `selection`.
|
||||
fileprivate func add(_ obj: T, at index: Int) -> Int? {
|
||||
guard shouldPersist(obj) else {
|
||||
return nil
|
||||
}
|
||||
if selection.last ?? 0 < index { // in case we only append at end
|
||||
selection.append(index)
|
||||
return selection.count - 1
|
||||
}
|
||||
return selection.binTreeInsert(index, compare: (<))
|
||||
}
|
||||
|
||||
/// Search and remove original `dataSource` index
|
||||
/// - Parameter index: Index of object in original `dataSource`
|
||||
/// - Returns: Index of removed element in `selection` or `nil` if element does not exist
|
||||
/// - Complexity: O(log *n*), where *n* is the length of the `selection`.
|
||||
fileprivate func remove(dataSource index: Int) -> Int? {
|
||||
selection.binTreeRemove(index, compare: (<))
|
||||
}
|
||||
|
||||
/// Perform filter check and update internal `selection` indices.
|
||||
/// - Parameters:
|
||||
/// - obj: Object that was inserted or updated.
|
||||
/// - index: Index where the object is located after the update.
|
||||
/// - Returns: `keep` indicates whether the value should be displayed (`true`) or hidden (`false`).
|
||||
/// `idx` contains the selection filter index or `nil` if the value should be removed.
|
||||
/// - Complexity: O(log *n*), where *n* is the length of the `selection`.
|
||||
fileprivate func update(_ obj: T, at index: Int) -> (keep: Bool, idx: Int?) {
|
||||
let currentIndex = selection.binTreeIndex(of: index, compare: (<), mustExist: true)
|
||||
if shouldPersist(obj) {
|
||||
return (true, currentIndex ?? selection.binTreeInsert(index, compare: (<)))
|
||||
}
|
||||
if let i = currentIndex { selection.remove(at: i) }
|
||||
return (false, currentIndex)
|
||||
}
|
||||
|
||||
/// Instead of re-sorting we can decrement all remaining elements after X.
|
||||
/// - Parameter sorted: Elements to remove from collection
|
||||
/// - Complexity: O(*m*+*n*), where *m* is the length of the `selection`.
|
||||
/// *n* is equal to: *length of selection* `-` *index of first element* of `sorted` indices
|
||||
fileprivate func shiftRemove(indices sorted: [Int]) {
|
||||
guard sorted.count > 0 else {
|
||||
return
|
||||
}
|
||||
var list = sorted
|
||||
var del = list.popLast()
|
||||
for (i, val) in selection.enumerated().reversed() {
|
||||
while let d = del, d > val {
|
||||
del = list.popLast()
|
||||
}
|
||||
guard let d = del else { break }
|
||||
if d < val { selection[i] -= (list.count + 1) }
|
||||
else if d == val { selection.remove(at: i) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Sorting
|
||||
|
||||
class PipelineSorting<T> {
|
||||
typealias Predicate = (T, T) -> Bool
|
||||
|
||||
private(set) var projection: [Int] = []
|
||||
private let comperator: (Int, Int) -> Bool // links to pipeline.dataSource
|
||||
|
||||
/// Create a fresh, already sorted, display order projection.
|
||||
/// - Parameter predicate: Return `true` if first element should be sorted before second element.
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of the `filter`.
|
||||
required init(_ predicate: @escaping Predicate, pipe: FilterPipeline<T>) {
|
||||
comperator = { [unowned pipe] in
|
||||
predicate(pipe.dataSource[$0], pipe.dataSource[$1])
|
||||
}
|
||||
reset(to: pipe.lastLayerIndices())
|
||||
}
|
||||
|
||||
/// - Warning: Make sure `predicate` does reflect the change. Or it will lead to data inconsistency.
|
||||
/// - Complexity: O(*n*), where *n* is the length of the `filter`.
|
||||
fileprivate func reverseOrder() {
|
||||
projection.reverse()
|
||||
}
|
||||
|
||||
/// Replace current `projection` with new filter indices and apply sorting.
|
||||
/// - Complexity: O(*n* log *n*), where *n* is the length of the `filter`.
|
||||
fileprivate func reset(to filterIndices: [Int]) {
|
||||
projection = filterIndices.sorted(by: comperator)
|
||||
}
|
||||
|
||||
/// After adding a new layer of filtering the new layer can only restrict the display even further.
|
||||
/// Therefore, indices that were removed in the last layer will be removed from the projection too.
|
||||
/// - Complexity: O(*m* log *n*), where *m* is the length of the `projection` and *n* the length of the `filter`.
|
||||
fileprivate func apply(moreRestrictive filterIndices: [Int]) {
|
||||
projection.removeAll { !filterIndices.binTreeExists($0, compare: (<)) }
|
||||
}
|
||||
|
||||
/// After removing a layer of filtering the previous layers are less restrictive and thus contain more indices.
|
||||
/// Therefore, the difference between both index sets will be inserted into the projection.
|
||||
/// - Complexity: O(*m* log *n*), where *m* is the difference to the previous layer and *n* is the length of the `projection`.
|
||||
fileprivate func apply(lessRestrictive filterIndices: [Int]) {
|
||||
for x in filterIndices.difference(toSubset: projection.sorted(), compare: (<)) {
|
||||
insertNew(x)
|
||||
}
|
||||
}
|
||||
|
||||
/// Add new element and automatically sort according to predicate
|
||||
/// - Parameters:
|
||||
/// - index: Index of the element position in the original `dataSource`
|
||||
/// - prev: If greater than `0`, try re-insert at the same position.
|
||||
/// - Returns: Index in the projection
|
||||
/// - Complexity: O(log *n*), where *n* is the length of the `projection`.
|
||||
@discardableResult fileprivate func insertNew(_ index: Int, previousIndex prev: Int = -1) -> Int {
|
||||
if prev >= 0, prev <= projection.count { // '<=' because previous delete removed one element
|
||||
if (prev == 0 || !comperator(index, projection[prev - 1])),
|
||||
(prev == projection.count || !comperator(projection[prev], index)) {
|
||||
// If element can be inserted at the same position without resorting, do that
|
||||
projection.insert(index, at: prev)
|
||||
return prev
|
||||
}
|
||||
}
|
||||
return projection.binTreeInsert(index, compare: comperator)
|
||||
}
|
||||
|
||||
/// Remove element from projection
|
||||
/// - Parameter index: Index of the element position in the original `dataSource`
|
||||
/// - Returns: Index in the projection or `-1` if element did not exist
|
||||
/// - Complexity: O(*n*), where *n* is the length of the `projection`.
|
||||
fileprivate func deleteOld(_ index: Int) -> Int {
|
||||
guard let i = projection.firstIndex(of: index) else {
|
||||
return -1
|
||||
}
|
||||
projection.remove(at: i)
|
||||
return i
|
||||
}
|
||||
|
||||
/// Instead of re-sorting we can decrement all remaining elements after X.
|
||||
/// - Parameter sorted: Elements to remove from collection
|
||||
/// - Returns: List of `projection` indices that were removed (reverse sort order)
|
||||
/// - Complexity: O(*m* log *n*), where *m* is the length of the `projection` and *n* is the length of `sorted`.
|
||||
@discardableResult fileprivate func shiftRemove(indices sorted: [Int]) -> [Int] {
|
||||
guard sorted.count > 0 else {
|
||||
return []
|
||||
}
|
||||
var listOfDeletes: [Int] = []
|
||||
let min = sorted.first!, max = sorted.last!
|
||||
for (i, val) in projection.enumerated().reversed() {
|
||||
guard val >= min else { continue }
|
||||
if val > max {
|
||||
projection[i] -= sorted.count
|
||||
} else {
|
||||
let c = sorted.binTreeIndex(of: val, compare: (<))!
|
||||
if val == sorted[c] {
|
||||
projection.remove(at: i)
|
||||
listOfDeletes.append(i)
|
||||
} else {
|
||||
projection[i] -= c
|
||||
}
|
||||
}
|
||||
}
|
||||
return listOfDeletes
|
||||
}
|
||||
}
|
||||
83
main/Common Classes/IBViews.swift
Normal file
@@ -0,0 +1,83 @@
|
||||
import UIKit
|
||||
import CoreGraphics
|
||||
|
||||
// MARK: White Triangle Popup Arrow
|
||||
|
||||
@IBDesignable
|
||||
class PopupTriangle: UIView {
|
||||
@IBInspectable var rotation: CGFloat = 0
|
||||
@IBInspectable var color: UIColor = .black
|
||||
|
||||
override func draw(_ rect: CGRect) {
|
||||
guard let c = UIGraphicsGetCurrentContext() else { return }
|
||||
let w = rect.width, h = rect.height
|
||||
switch rotation {
|
||||
case 90: // right
|
||||
c.lineFromTo(x1: 0, y1: 0, x2: w, y2: h/2)
|
||||
c.addLine(to: CGPoint(x: 0, y: h))
|
||||
case 180: // bottom
|
||||
c.lineFromTo(x1: w, y1: 0, x2: w/2, y2: h)
|
||||
c.addLine(to: CGPoint(x: 0, y: 0))
|
||||
case 270: // left
|
||||
c.lineFromTo(x1: w, y1: h, x2: 0, y2: h/2)
|
||||
c.addLine(to: CGPoint(x: w, y: 0))
|
||||
default: // top
|
||||
c.lineFromTo(x1: 0, y1: h, x2: w/2, y2: 0)
|
||||
c.addLine(to: CGPoint(x: w, y: h))
|
||||
}
|
||||
c.closePath()
|
||||
c.setFillColor(color.cgColor)
|
||||
c.fillPath()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: Label as Tag Bubble
|
||||
|
||||
@IBDesignable
|
||||
class TagLabel: UILabel {
|
||||
private var em: CGFloat { font.pointSize }
|
||||
@IBInspectable var padTop: CGFloat = 0
|
||||
@IBInspectable var padLeft: CGFloat = 0
|
||||
@IBInspectable var padRight: CGFloat = 0
|
||||
@IBInspectable var padBottom: CGFloat = 0
|
||||
private var padding: UIEdgeInsets {
|
||||
.init(top: padTop + em/6, left: padLeft + em/3,
|
||||
bottom: padBottom + em/6, right: padRight + em/3)
|
||||
}
|
||||
|
||||
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
|
||||
let i = padding
|
||||
let ii = UIEdgeInsets(top: -i.top, left: -i.left, bottom: -i.bottom, right: -i.right)
|
||||
return super.textRect(forBounds: bounds.inset(by: i),
|
||||
limitedToNumberOfLines: numberOfLines).inset(by: ii)
|
||||
}
|
||||
|
||||
override func drawText(in rect: CGRect) {
|
||||
layer.masksToBounds = true
|
||||
layer.cornerRadius = em/2.5
|
||||
super.drawText(in: rect.inset(by: padding))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: Percentage meter
|
||||
|
||||
@IBDesignable
|
||||
class MeterBar: UIView {
|
||||
@IBInspectable var percent: CGFloat = 0 { didSet { setNeedsDisplay() } }
|
||||
@IBInspectable var barColor: UIColor = .sysFg
|
||||
@IBInspectable var horizontal: Bool = false
|
||||
|
||||
private var normPercent: CGFloat { 1 - max(0, min(percent, 1)) }
|
||||
|
||||
override func draw(_ rect: CGRect) {
|
||||
let c = UIGraphicsGetCurrentContext()
|
||||
c?.setFillColor(barColor.cgColor)
|
||||
if horizontal {
|
||||
c?.fill(rect.insetBy(dx: normPercent * (rect.width/2), dy: 0))
|
||||
} else {
|
||||
c?.fill(rect.insetBy(dx: 0, dy: normPercent * (rect.height/2)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,35 +36,8 @@ struct QuickUI {
|
||||
static func text(attributed: NSAttributedString, frame: CGRect = CGRect.zero) -> UITextView {
|
||||
let txt = self.text("", frame: frame)
|
||||
txt.attributedText = attributed
|
||||
txt.textContainerInset = .zero
|
||||
//txt.textContainer.lineFragmentPadding = 0 // remove left right padding
|
||||
return txt
|
||||
}
|
||||
}
|
||||
|
||||
extension NSMutableAttributedString {
|
||||
static private var def: UIFont = .preferredFont(forTextStyle: .body)
|
||||
|
||||
func normal(_ str: String, _ style: UIFont.TextStyle = .body) -> Self { append(str, withFont: .preferredFont(forTextStyle: style)) }
|
||||
func bold(_ str: String, _ style: UIFont.TextStyle = .body) -> Self { append(str, withFont: UIFont.preferredFont(forTextStyle: style).bold()) }
|
||||
func italic(_ str: String, _ style: UIFont.TextStyle = .body) -> Self { append(str, withFont: UIFont.preferredFont(forTextStyle: style).italic()) }
|
||||
|
||||
func h1(_ str: String) -> Self { normal(str, .title1) }
|
||||
func h2(_ str: String) -> Self { normal(str, .title2) }
|
||||
func h3(_ str: String) -> Self { normal(str, .title3) }
|
||||
|
||||
private func append(_ str: String, withFont: UIFont) -> Self {
|
||||
append(NSAttributedString(string: str, attributes: [
|
||||
.font : withFont,
|
||||
.foregroundColor : UIColor.sysFg
|
||||
]))
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension UIFont {
|
||||
func withTraits(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
|
||||
UIFont(descriptor: fontDescriptor.withSymbolicTraits(traits)!, size: 0) // keep size as is
|
||||
}
|
||||
func bold() -> UIFont { withTraits(traits: .traitBold) }
|
||||
func italic() -> UIFont { withTraits(traits: .traitItalic) }
|
||||
}
|
||||
|
||||
57
main/Common Classes/SearchBarManager.swift
Normal file
@@ -0,0 +1,57 @@
|
||||
import UIKit
|
||||
|
||||
class SearchBarManager: NSObject, UISearchResultsUpdating {
|
||||
|
||||
private(set) var isActive = false
|
||||
private(set) var term = ""
|
||||
private lazy var controller: UISearchController = {
|
||||
let x = UISearchController(searchResultsController: nil)
|
||||
x.searchBar.autocapitalizationType = .none
|
||||
x.searchBar.autocorrectionType = .no
|
||||
x.obscuresBackgroundDuringPresentation = false
|
||||
x.searchResultsUpdater = self
|
||||
return x
|
||||
}()
|
||||
private weak var tvc: UITableViewController?
|
||||
private let onChangeCallback: (String) -> Void
|
||||
|
||||
/// Prepare `UISearchBar` for user input
|
||||
/// - Parameter onChange: Code that will be executed every time the user changes the text (with 0.2s delay)
|
||||
required init(onChange: @escaping (String) -> Void) {
|
||||
onChangeCallback = onChange
|
||||
super.init()
|
||||
|
||||
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
|
||||
.defaultTextAttributes = [.font: UIFont.preferredFont(forTextStyle: .body)]
|
||||
}
|
||||
|
||||
/// Assigns the `UISearchBar` to `tableView.tableHeaderView` (iOS 9) or `navigationItem.searchController` (iOS 11).
|
||||
func fuseWith(tableViewController: UITableViewController?) {
|
||||
guard tvc !== tableViewController else { return }
|
||||
tvc = tableViewController
|
||||
|
||||
if #available(iOS 11.0, *) {
|
||||
tvc?.navigationItem.searchController = controller
|
||||
} else {
|
||||
controller.loadViewIfNeeded() // Fix: "Attempting to load the view of a view controller while it is deallocating"
|
||||
tvc?.definesPresentationContext = true // make search bar disappear if user changes scene (eg. select cell)
|
||||
//tvc?.tableView.backgroundView = UIView() // iOS 11+ bug: bright white background in dark mode
|
||||
tvc?.tableView.tableHeaderView = controller.searchBar
|
||||
tvc?.tableView.setContentOffset(.init(x: 0, y: controller.searchBar.frame.height), animated: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Search callback
|
||||
func updateSearchResults(for controller: UISearchController) {
|
||||
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(performSearch), object: nil)
|
||||
perform(#selector(performSearch), with: nil, afterDelay: 0.2)
|
||||
}
|
||||
|
||||
/// Internal callback function for delayed text evaluation.
|
||||
/// This way we can avoid unnecessary searches while user is typing.
|
||||
@objc private func performSearch() {
|
||||
term = controller.searchBar.text?.lowercased() ?? ""
|
||||
isActive = term.count > 0
|
||||
onChangeCallback(term)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,18 @@
|
||||
import UIKit
|
||||
|
||||
fileprivate let margin: CGFloat = 20
|
||||
fileprivate let cornerRadius: CGFloat = 15
|
||||
fileprivate let uniRect = CGRect(x: 0, y: 0, width: 500, height: 500)
|
||||
fileprivate var margin: CGFloat { 20 }
|
||||
fileprivate var sheetInset: CGFloat { cornerRadius/2 }
|
||||
fileprivate var cornerRadius: CGFloat { 15 }
|
||||
fileprivate var uniRect: CGRect { CGRect(x: 0, y: 0, width: 500, height: 500) }
|
||||
|
||||
class TutorialSheet: UIViewController, UIScrollViewDelegate {
|
||||
|
||||
/// Maximum displayable width of a Tutorial Sheet in portrait mode.
|
||||
public static var verticalWidth: CGFloat {
|
||||
let s = UIScreen.main.bounds.size
|
||||
return min(s.width, s.height) - 2 * (margin + sheetInset)
|
||||
}
|
||||
|
||||
public var buttonTitleNext: String = "Next"
|
||||
public var buttonTitleDone: String = "Close"
|
||||
|
||||
@@ -47,7 +54,6 @@ class TutorialSheet: UIViewController, UIScrollViewDelegate {
|
||||
|
||||
let content = UIView()
|
||||
x.addSubview(content)
|
||||
content.translatesAutoresizingMaskIntoConstraints = false
|
||||
content.anchor([.left, .right, .top, .bottom], to: x)
|
||||
content.anchor([.width, .height], to: x) | .defaultLow
|
||||
return x
|
||||
@@ -62,7 +68,7 @@ class TutorialSheet: UIViewController, UIScrollViewDelegate {
|
||||
|
||||
// MARK: Init
|
||||
|
||||
required init?(coder: NSCoder) { super.init(coder: coder) }
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
required init() {
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
@@ -98,7 +104,6 @@ class TutorialSheet: UIViewController, UIScrollViewDelegate {
|
||||
pager.numberOfPages += 1
|
||||
updateButtonTitle()
|
||||
let x = UIStackView(frame: pageScroll.bounds)
|
||||
x.translatesAutoresizingMaskIntoConstraints = false
|
||||
x.axis = .vertical
|
||||
x.backgroundColor = UIColor.black
|
||||
x.isOpaque = true
|
||||
@@ -107,7 +112,8 @@ class TutorialSheet: UIViewController, UIScrollViewDelegate {
|
||||
}
|
||||
let prev = content.subviews.last
|
||||
content.addSubview(x)
|
||||
x.anchor([.top, .width, .height], to: pageScroll)
|
||||
x.anchor([.top, .height], to: pageScroll)
|
||||
x.widthAnchor =&= sheetBg.widthAnchor - 2 * sheetInset
|
||||
x.leadingAnchor =&= (prev==nil ? content.leadingAnchor : prev!.trailingAnchor)
|
||||
lastAnchor?.isActive = false
|
||||
lastAnchor = (x.trailingAnchor =&= pageScroll.trailingAnchor)
|
||||
@@ -125,11 +131,9 @@ class TutorialSheet: UIViewController, UIScrollViewDelegate {
|
||||
sheetBg.addSubview(pageScroll)
|
||||
sheetBg.addSubview(button)
|
||||
|
||||
for x in sheetBg.subviews { x.translatesAutoresizingMaskIntoConstraints = false }
|
||||
|
||||
pager.anchor([.top, .left, .right], to: sheetBg)
|
||||
pageScroll.topAnchor =&= pager.bottomAnchor
|
||||
pageScroll.anchor([.left, .right, .top, .bottom], to: sheetBg, margin: cornerRadius/2) | .defaultHigh
|
||||
pageScroll.anchor([.left, .right, .top, .bottom], to: sheetBg, margin: sheetInset) | .defaultHigh
|
||||
button.topAnchor =&= pageScroll.bottomAnchor
|
||||
button.anchor([.bottom, .centerX], to: sheetBg)
|
||||
// button.bottomAnchor =&= sheetBg.bottomAnchor - 30
|
||||
|
||||
464
main/DB/DBAppOnly.swift
Normal file
@@ -0,0 +1,464 @@
|
||||
import Foundation
|
||||
import SQLite3
|
||||
|
||||
typealias Timestamp = sqlite3_int64
|
||||
|
||||
extension SQLiteDatabase {
|
||||
func initAppOnlyScheme() {
|
||||
try? run(sql: CreateTable.heap)
|
||||
try? run(sql: CreateTable.rec)
|
||||
try? run(sql: CreateTable.recLog)
|
||||
do {
|
||||
try migrateDB()
|
||||
} catch {
|
||||
QLog.Error("during migration: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func migrateDB() throws {
|
||||
let version = try run(sql: "PRAGMA user_version;") { stmt -> Int32 in
|
||||
try ifStep(stmt, SQLITE_ROW)
|
||||
return sqlite3_column_int(stmt, 0)
|
||||
}
|
||||
if version != 1 {
|
||||
// version 0 -> 1: req(domain) -> heap(fqdn, domain)
|
||||
if version == 0 {
|
||||
try tempMigrate()
|
||||
}
|
||||
try run(sql: "PRAGMA user_version = 1;")
|
||||
}
|
||||
}
|
||||
|
||||
private func tempMigrate() throws { // TODO: remove with next internal release
|
||||
do {
|
||||
try run(sql: "SELECT 1 FROM req LIMIT 1;") // fails if req doesnt exist
|
||||
createFunction("domainof") { ($0.first as! String).extractDomain() }
|
||||
try run(sql: """
|
||||
BEGIN TRANSACTION;
|
||||
INSERT INTO heap(ts,fqdn,domain,opt) SELECT ts,domain,domainof(domain),nullif(logOpt,0) FROM req;
|
||||
DROP TABLE req;
|
||||
COMMIT;
|
||||
""")
|
||||
} catch { /* no need to migrate */ }
|
||||
}
|
||||
}
|
||||
|
||||
private enum TableName: String {
|
||||
case heap, cache
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
fileprivate func lastRowId(_ table: TableName) -> SQLiteRowID {
|
||||
(try? run(sql:"SELECT rowid FROM \(table.rawValue) ORDER BY rowid DESC LIMIT 1;") {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return sqlite3_column_int64($0, 0)
|
||||
}) ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
class WhereClauseBuilder: CustomStringConvertible {
|
||||
var description: String = ""
|
||||
private let prefix: String
|
||||
private(set) var bindings: [DBBinding] = []
|
||||
|
||||
init(prefix p: String = "WHERE") { prefix = "\(p) " }
|
||||
|
||||
/// Append new clause by either prepending `WHERE` prefix or placing `AND` between clauses.
|
||||
@discardableResult func and(_ clause: String, _ bind: DBBinding ...) -> Self {
|
||||
description.append((description=="" ? prefix : " AND ") + clause)
|
||||
bindings.append(contentsOf: bind)
|
||||
return self
|
||||
}
|
||||
/// Restrict to `rowid >= {range}.start AND rowid <= {range}.end`.
|
||||
/// Omitted if range is `nil` or individually if a value is `0`.
|
||||
@discardableResult func and(in range: SQLiteRowRange) -> Self {
|
||||
if range.start != 0 { and("rowid >= ?", BindInt64(range.start)) }
|
||||
if range.end != 0 { and("rowid <= ?", BindInt64(range.end)) }
|
||||
return self
|
||||
}
|
||||
/// Restrict to `ts >= {min} AND ts < {max}`. Omit one or the other if value is `0`.
|
||||
@discardableResult func and(min: Timestamp = 0, max: Timestamp = 0) -> Self {
|
||||
if min != 0 { and("ts >= ?", BindInt64(min)) }
|
||||
if max != 0 { and("ts < ?", BindInt64(max)) }
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - DNSLog
|
||||
|
||||
extension CreateTable {
|
||||
/// `ts`: Timestamp, `fqdn`: String, `domain`: String, `opt`: Int
|
||||
static var heap: String {"""
|
||||
CREATE TABLE IF NOT EXISTS heap(
|
||||
ts INTEGER DEFAULT (strftime('%s','now')),
|
||||
fqdn TEXT NOT NULL,
|
||||
domain TEXT NOT NULL,
|
||||
opt INTEGER
|
||||
);
|
||||
"""} // opt currently only used as "blocked" flag
|
||||
}
|
||||
|
||||
struct GroupedDomain {
|
||||
let domain: String, total: Int32, blocked: Int32, lastModified: Timestamp
|
||||
var options: FilterOptions? = nil
|
||||
}
|
||||
typealias GroupedTsOccurrence = (ts: Timestamp, total: Int32, blocked: Int32)
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: write
|
||||
|
||||
/// Move newest entries from `cache` to `heap` and return range (in `heap`) of newly inserted entries.
|
||||
/// - Returns: `nil` in case no entries were transmitted.
|
||||
@discardableResult func dnsLogsPersist() -> SQLiteRowRange? {
|
||||
guard lastRowId(.cache) > 0 else { return nil }
|
||||
let before = lastRowId(.heap) + 1
|
||||
createFunction("domainof") { ($0.first as! String).extractDomain() }
|
||||
try? run(sql:"""
|
||||
BEGIN TRANSACTION;
|
||||
INSERT INTO heap(ts,fqdn,domain,opt) SELECT ts,dns,domainof(dns),nullif(opt&1,0) FROM cache;
|
||||
DELETE FROM cache;
|
||||
COMMIT;
|
||||
""")
|
||||
let after = lastRowId(.heap)
|
||||
return (before > after) ? nil : (before, after)
|
||||
}
|
||||
|
||||
/// `DELETE FROM cache; DELETE FROM heap;`
|
||||
func dnsLogsDeleteAll() throws {
|
||||
try? run(sql: "DELETE FROM cache; DELETE FROM heap;")
|
||||
vacuum()
|
||||
}
|
||||
|
||||
/// Delete rows matching `ts >= ? AND domain = ?`
|
||||
/// - Parameter strict: If `true`, use `fqdn` instead of `domain` column
|
||||
/// - Returns: Number of changes aka. Number of rows deleted
|
||||
@discardableResult func dnsLogsDelete(_ domain: String, strict: Bool, since ts: Timestamp = 0) -> Int32 {
|
||||
let Where = WhereClauseBuilder().and(min: ts)
|
||||
Where.and("\(strict ? "fqdn" : "domain") = ?", BindText(domain)) // (fqdn = ? OR fqdn LIKE '%.' || ?)
|
||||
return (try? run(sql: "DELETE FROM heap \(Where);", bind: Where.bindings) { stmt -> Int32 in
|
||||
try ifStep(stmt, SQLITE_DONE)
|
||||
return numberOfChanges
|
||||
}) ?? 0
|
||||
}
|
||||
|
||||
// MARK: read
|
||||
|
||||
/// `SELECT min(ts) FROM heap`
|
||||
func dnsLogsMinDate() -> Timestamp? {
|
||||
try? run(sql:"SELECT min(ts) FROM heap") {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return sqlite3_column_int64($0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Select min and max row id with given condition `ts >= ? AND ts < ?`
|
||||
/// - Parameters:
|
||||
/// - ts1: Restrict min `rowid` to `ts >= ?`. Pass `0` to omit restriction.
|
||||
/// - ts2: Restrict max `rowid` to `ts < ?`. Pass `0` to omit restriction.
|
||||
/// - range: If set, only look at the specified range. Default: `(0,0)`
|
||||
/// - Returns: `nil` in case no rows are matching the condition
|
||||
func dnsLogsRowRange(between ts1: Timestamp, and ts2: Timestamp, within range: SQLiteRowRange = (0,0)) -> SQLiteRowRange? {
|
||||
let Where = WhereClauseBuilder().and(in: range).and(min: ts1, max: ts2)
|
||||
return try? run(sql:"SELECT min(rowid), max(rowid) FROM heap \(Where);", bind: Where.bindings) {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
let max = sqlite3_column_int64($0, 1)
|
||||
return (max == 0) ? nil : (sqlite3_column_int64($0, 0), max)
|
||||
}
|
||||
}
|
||||
|
||||
/// Group DNS logs by domain, count occurences and number of blocked requests.
|
||||
/// - Parameters:
|
||||
/// - range: Whenever possible set range to improve SQL lookup times. `start <= rowid <= end `
|
||||
/// - matchingDomain: Restrict `(fqdn|domain) = ?`. Which column is used is determined by `parentDomain`.
|
||||
/// - parentDomain: If `nil` returns `domain` column. Else returns `fqdn` column with restriction on `domain == parentDomain`.
|
||||
/// - Returns: List of grouped domains with no particular sorting order.
|
||||
func dnsLogsGrouped(range: SQLiteRowRange, matchingDomain: String? = nil, parentDomain: String? = nil) -> [GroupedDomain]? {
|
||||
let Where = WhereClauseBuilder().and(in: range)
|
||||
let col: String // fqdn or domain
|
||||
if let parent = parentDomain { // is subdomain
|
||||
col = "fqdn"
|
||||
Where.and("domain = ?", BindText(parent))
|
||||
} else {
|
||||
col = "domain"
|
||||
}
|
||||
if let matching = matchingDomain { // (fqdn = ? OR fqdn LIKE '%.' || ?)
|
||||
Where.and("\(col) = ?", BindText(matching))
|
||||
}
|
||||
return try? run(sql: "SELECT \(col), COUNT(*), COUNT(opt), MAX(ts) FROM heap \(Where) GROUP BY \(col);", bind: Where.bindings) {
|
||||
allRows($0) {
|
||||
GroupedDomain(domain: readText($0, 0) ?? "",
|
||||
total: sqlite3_column_int($0, 1),
|
||||
blocked: sqlite3_column_int($0, 2),
|
||||
lastModified: sqlite3_column_int64($0, 3))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get list or individual DNS entries. Mutliple entries in the very same second are grouped.
|
||||
/// - Parameters:
|
||||
/// - fqdn: Exact match for domain name `fqdn = ?`
|
||||
/// - range: Whenever possible set range to improve SQL lookup times. `start <= rowid <= end `
|
||||
/// - Returns: List sorted by reverse timestamp order (newest first)
|
||||
func timesForDomain(_ fqdn: String, range: SQLiteRowRange) -> [GroupedTsOccurrence]? {
|
||||
let Where = WhereClauseBuilder().and(in: range).and("fqdn = ?", BindText(fqdn))
|
||||
return try? run(sql: "SELECT ts, COUNT(ts), COUNT(opt) FROM heap \(Where) GROUP BY ts ORDER BY ts DESC;", bind: Where.bindings) {
|
||||
allRows($0) {
|
||||
(sqlite3_column_int64($0, 0), sqlite3_column_int($0, 1), sqlite3_column_int($0, 2))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Context Analysis
|
||||
|
||||
typealias ContextAnalysisResult = (domain: String, count: Int32, avg: Double, rank: Double)
|
||||
|
||||
extension SQLiteDatabase {
|
||||
/// Number of times how often given `fqdn` appears in the database
|
||||
func dnsLogsCount(fqdn: String) -> Int? {
|
||||
try? run(sql: "SELECT COUNT(*) FROM heap WHERE fqdn = ?;", bind: [BindText(fqdn)]) {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return Int(sqlite3_column_int($0, 0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Get sorted, unique list of `ts` with given `fqdn`.
|
||||
func dnsLogsUniqTs(_ fqdn: String) -> [Timestamp]? {
|
||||
try? run(sql: "SELECT DISTINCT ts FROM heap WHERE fqdn = ? ORDER BY ts;", bind: [BindText(fqdn)]) {
|
||||
allRows($0) { sqlite3_column_int64($0, 0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Find other domains occurring regularly at roughly the same time as `fqdn`.
|
||||
/// - Warning: `times` list must be **sorted** by time in ascending order.
|
||||
/// - Parameters:
|
||||
/// - times: List of `ts` from `dnsLogsUniqTs(fqdn)`
|
||||
/// - dt: Search for `ts - dt <= X <= ts + dt`
|
||||
/// - fqdn: Rows matching this domain will be excluded from the result set.
|
||||
/// - Returns: List of tuples ordered by rank (ASC).
|
||||
func contextAnalysis(coOccurrence times: [Timestamp], plusMinus dt: Timestamp, exclude fqdn: String) -> [ContextAnalysisResult]? {
|
||||
guard times.count > 0 else { return nil }
|
||||
createFunction("fnDist") {
|
||||
let x = $0.first as! Timestamp
|
||||
let i = times.binTreeIndex(of: x, compare: <)!
|
||||
let dist: Timestamp
|
||||
switch i {
|
||||
case 0: dist = times[0] - x
|
||||
case times.count: dist = x - times[i-1]
|
||||
default: dist = min(times[i] - x, x - times[i-1])
|
||||
}
|
||||
return dist
|
||||
}
|
||||
// `avg ^ 2`: prefer results that are closer to `times`
|
||||
// `_ / count`: prefer results with higher occurrence count
|
||||
// `time / 2`: Weighting factor (low: prefer close, high: prefer count)
|
||||
// `time` helpful esp. for smaller spans. `avg^2` will raise faster anyway.
|
||||
let fnRank = "(avg * avg + (? / 2.0) + 1) / count" // +1 in case time == 0 -> avg^2 == 0
|
||||
// improve query by excluding entries that are: before the first, or after the last ts
|
||||
let low = times.first! - dt
|
||||
let high = times.last! + dt
|
||||
return try? run(sql: """
|
||||
SELECT fqdn, count, avg, (\(fnRank)) rank FROM (
|
||||
SELECT fqdn, COUNT(*) count, AVG(dist) avg FROM (
|
||||
SELECT fqdn, fnDist(ts) dist FROM heap
|
||||
WHERE ts BETWEEN ? AND ? AND fqdn != ? AND dist <= ?
|
||||
) GROUP BY fqdn
|
||||
) ORDER BY rank ASC LIMIT 99;
|
||||
""", bind: [BindInt64(dt), BindInt64(low), BindInt64(high), BindText(fqdn), BindInt64(dt)]) {
|
||||
allRows($0) {
|
||||
(readText($0, 0) ?? "", sqlite3_column_int($0, 1), sqlite3_column_double($0, 2), sqlite3_column_double($0, 3))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Recordings
|
||||
|
||||
extension CreateTable {
|
||||
/// `id`: Primary, `start`: Timestamp, `stop`: Timestamp, `appid`: String, `title`: String, `notes`: String
|
||||
static var rec: String {"""
|
||||
CREATE TABLE IF NOT EXISTS rec(
|
||||
id INTEGER PRIMARY KEY,
|
||||
start INTEGER DEFAULT (strftime('%s','now')),
|
||||
stop INTEGER,
|
||||
appid TEXT,
|
||||
title TEXT,
|
||||
notes TEXT
|
||||
);
|
||||
"""}
|
||||
}
|
||||
|
||||
struct Recording {
|
||||
let id: sqlite3_int64
|
||||
let start: Timestamp
|
||||
let stop: Timestamp?
|
||||
var appId: String? = nil
|
||||
var title: String? = nil
|
||||
var notes: String? = nil
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: write
|
||||
|
||||
/// Create new recording with `stop` set to `NULL`.
|
||||
func recordingStartNew() throws -> Recording {
|
||||
try run(sql: "INSERT INTO rec (stop) VALUES (NULL);") { stmt -> Recording in
|
||||
try ifStep(stmt, SQLITE_DONE)
|
||||
return try recordingGet(withID: lastInsertedRow)
|
||||
}
|
||||
}
|
||||
|
||||
/// Update given recording by setting `stop` to current time.
|
||||
func recordingStop(_ r: inout Recording) {
|
||||
guard r.stop == nil else { return }
|
||||
let theID = r.id
|
||||
try? run(sql: "UPDATE rec SET stop = (strftime('%s','now')) WHERE id = ? LIMIT 1;",
|
||||
bind: [BindInt64(theID)]) { stmt -> Void in
|
||||
try ifStep(stmt, SQLITE_DONE)
|
||||
r = try recordingGet(withID: theID)
|
||||
}
|
||||
}
|
||||
|
||||
/// Update given recording by replacing `title`, `appid`, and `notes` with new values.
|
||||
func recordingUpdate(_ r: Recording) {
|
||||
try? run(sql: "UPDATE rec SET title = ?, appid = ?, notes = ? WHERE id = ? LIMIT 1;",
|
||||
bind: [BindTextOrNil(r.title), BindTextOrNil(r.appId), BindTextOrNil(r.notes), BindInt64(r.id)]) { stmt -> Void in
|
||||
sqlite3_step(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete recording and all of its entries.
|
||||
/// - Returns: `true` on success
|
||||
func recordingDelete(_ r: Recording) throws -> Bool {
|
||||
_ = try? recordingLogsDelete(r.id)
|
||||
return try run(sql: "DELETE FROM rec WHERE id = ? LIMIT 1;", bind: [BindInt64(r.id)]) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
return numberOfChanges > 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: read
|
||||
|
||||
private func readRecording(_ stmt: OpaquePointer) -> Recording {
|
||||
let end = sqlite3_column_int64(stmt, 2)
|
||||
return Recording(id: sqlite3_column_int64(stmt, 0),
|
||||
start: sqlite3_column_int64(stmt, 1),
|
||||
stop: end == 0 ? nil : end,
|
||||
appId: readText(stmt, 3),
|
||||
title: readText(stmt, 4),
|
||||
notes: readText(stmt, 5))
|
||||
}
|
||||
|
||||
/// `WHERE stop IS NULL`
|
||||
func recordingGetOngoing() -> Recording? {
|
||||
try? run(sql: "SELECT * FROM rec WHERE stop IS NULL LIMIT 1;") {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return readRecording($0)
|
||||
}
|
||||
}
|
||||
|
||||
/// `WHERE stop IS NOT NULL`
|
||||
func recordingGetAll() -> [Recording]? {
|
||||
try? run(sql: "SELECT * FROM rec WHERE stop IS NOT NULL;") {
|
||||
allRows($0) { readRecording($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// `WHERE id = ?`
|
||||
private func recordingGet(withID: sqlite3_int64) throws -> Recording {
|
||||
try run(sql: "SELECT * FROM rec WHERE id = ? LIMIT 1;", bind: [BindInt64(withID)]) {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return readRecording($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - RecordingLog
|
||||
|
||||
extension CreateTable {
|
||||
/// `rid`: Reference `rec(id)`, `ts`: Timestamp, `domain`: String
|
||||
static var recLog: String {"""
|
||||
CREATE TABLE IF NOT EXISTS recLog(
|
||||
rid INTEGER REFERENCES rec(id) ON DELETE CASCADE,
|
||||
ts INTEGER,
|
||||
domain TEXT
|
||||
);
|
||||
"""}
|
||||
}
|
||||
|
||||
typealias RecordLog = (domain: String, count: Int32)
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: write
|
||||
|
||||
/// Duplicate and copy all log entries for given recording to `recLog` table
|
||||
func recordingLogsPersist(_ r: Recording) {
|
||||
guard let end = r.stop else { return }
|
||||
// TODO: make sure cache entries get copied too.
|
||||
// either by copying them directly from cache or perform sync first
|
||||
try? run(sql: """
|
||||
INSERT INTO recLog (rid, ts, domain) SELECT ?, ts, fqdn FROM heap
|
||||
WHERE heap.ts >= ? AND heap.ts <= ?
|
||||
""", bind: [BindInt64(r.id), BindInt64(r.start), BindInt64(end)]) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete all log entries with given recording id. Optional: only delete entries for a single domain
|
||||
/// - Parameter d: If `nil` remove all entries for given recording
|
||||
/// - Returns: Number of deleted rows
|
||||
func recordingLogsDelete(_ recId: sqlite3_int64, matchingDomain d: String? = nil) throws -> Int32 {
|
||||
try run(sql: "DELETE FROM recLog WHERE rid = ? \(d==nil ? "" : "AND domain = ?");",
|
||||
bind: [BindInt64(recId), d==nil ? nil : BindText(d!)]) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
return numberOfChanges
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: read
|
||||
|
||||
/// List of domains and count occurences for given recording.
|
||||
func recordingLogsGetGrouped(_ r: Recording) -> [RecordLog]? {
|
||||
try? run(sql: "SELECT domain, COUNT() FROM recLog WHERE rid = ? GROUP BY domain;",
|
||||
bind: [BindInt64(r.id)]) {
|
||||
allRows($0) { (readText($0, 0) ?? "", sqlite3_column_int($0, 1)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - DBSettings
|
||||
|
||||
//extension CreateTable {
|
||||
// static var settings: String {
|
||||
// "CREATE TABLE IF NOT EXISTS settings(key TEXT UNIQUE NOT NULL, val TEXT);"
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//extension SQLiteDatabase {
|
||||
// func getSetting(for key: String) -> String? {
|
||||
// try? run(sql: "SELECT val FROM settings WHERE key = ?;",
|
||||
// bind: [BindText(key)]) { readText($0, 0) }
|
||||
// }
|
||||
// func setSetting(_ value: String?, for key: String) {
|
||||
// if let value = value {
|
||||
// try? run(sql: "INSERT OR REPLACE INTO settings (key, val) VALUES (?, ?);",
|
||||
// bind: [BindText(value), BindText(key)]) { step($0) }
|
||||
// } else {
|
||||
// try? run(sql: "DELETE FROM settings WHERE key = ?;",
|
||||
// bind: [BindText(key)]) { step($0) }
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
94
main/DB/DBCommon.swift
Normal file
@@ -0,0 +1,94 @@
|
||||
import Foundation
|
||||
import SQLite3
|
||||
|
||||
enum CreateTable {} // used for CREATE TABLE statements
|
||||
|
||||
extension SQLiteDatabase {
|
||||
func initCommonScheme() {
|
||||
try? run(sql: CreateTable.cache)
|
||||
try? run(sql: CreateTable.filter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - transit
|
||||
|
||||
extension CreateTable {
|
||||
/// `ts`: Timestamp, `dns`: String, `opt`: Int
|
||||
static var cache: String {"""
|
||||
CREATE TABLE IF NOT EXISTS cache(
|
||||
ts INTEGER DEFAULT (strftime('%s','now')),
|
||||
dns TEXT NOT NULL,
|
||||
opt INTEGER
|
||||
);
|
||||
"""}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
// /// `INSERT INTO cache (dns, opt) VALUES (?, ?);`
|
||||
// func logWritePrepare() throws -> OpaquePointer {
|
||||
// try prepare(sql: "INSERT INTO cache (dns, opt) VALUES (?, ?);")
|
||||
// }
|
||||
// /// `prep` must exist and be initialized with `logWritePrepare()`
|
||||
// func logWrite(_ pStmt: OpaquePointer!, _ domain: String, blocked: Bool = false) throws {
|
||||
// guard let prep = pStmt else {
|
||||
// return
|
||||
// }
|
||||
// try prepared(run: prep, bind: [BindText(domain), BindInt32(blocked ? 1 : 0)])
|
||||
// }
|
||||
/// `INSERT INTO cache (dns, opt) VALUES (?, ?);`
|
||||
func logWrite(_ domain: String, blocked: Bool = false) throws {
|
||||
try self.run(sql: "INSERT INTO cache (dns, opt) VALUES (?, ?);",
|
||||
bind: [BindText(domain), BindInt32(blocked ? 1 : 0)])
|
||||
{ try ifStep($0, SQLITE_DONE) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - filter
|
||||
|
||||
extension CreateTable {
|
||||
/// `domain`: String, `opt`: Int
|
||||
static var filter: String {"""
|
||||
CREATE TABLE IF NOT EXISTS filter(
|
||||
domain TEXT UNIQUE NOT NULL,
|
||||
opt INTEGER
|
||||
);
|
||||
"""}
|
||||
}
|
||||
|
||||
struct FilterOptions: OptionSet {
|
||||
let rawValue: Int32
|
||||
static let none = FilterOptions([])
|
||||
static let blocked = FilterOptions(rawValue: 1 << 0)
|
||||
static let ignored = FilterOptions(rawValue: 1 << 1)
|
||||
static let any = FilterOptions(rawValue: 0b11)
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
func loadFilters(where matching: FilterOptions? = nil) -> [String : FilterOptions]? {
|
||||
let rv = matching?.rawValue ?? 0
|
||||
return try? run(sql: "SELECT domain, opt FROM filter \(rv>0 ? "WHERE opt & ?" : "");",
|
||||
bind: rv>0 ? [BindInt32(rv)] : []) {
|
||||
allRowsKeyed($0) {
|
||||
(key: readText($0, 0) ?? "",
|
||||
value: FilterOptions(rawValue: sqlite3_column_int($0, 1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
func setFilter(_ domain: String, _ value: FilterOptions?) {
|
||||
if let rv = value?.rawValue, rv > 0 {
|
||||
try? run(sql: "INSERT OR REPLACE INTO filter (domain, opt) VALUES (?, ?);",
|
||||
bind: [BindText(domain), BindInt32(rv)]) { _ = sqlite3_step($0) }
|
||||
} else {
|
||||
try? run(sql: "DELETE FROM filter WHERE domain = ? LIMIT 1;",
|
||||
bind: [BindText(domain)]) { _ = sqlite3_step($0) }
|
||||
}
|
||||
}
|
||||
// func loadFilterCount() -> (blocked: Int32, ignored: Int32)? {
|
||||
// try? run(sql: "SELECT SUM(opt&1), SUM(opt&2)/2 FROM filter;") {
|
||||
// try ifStep($0, SQLITE_ROW)
|
||||
// return (sqlite3_column_int($0, 0), sqlite3_column_int($0, 1))
|
||||
// }
|
||||
// }
|
||||
}
|
||||
242
main/DB/DBCore.swift
Normal file
@@ -0,0 +1,242 @@
|
||||
import Foundation
|
||||
import SQLite3
|
||||
|
||||
// iOS 9.3 uses SQLite 3.8.10
|
||||
|
||||
enum SQLiteError: Error {
|
||||
case OpenDatabase(message: String)
|
||||
case Prepare(message: String)
|
||||
case Step(message: String)
|
||||
case Bind(message: String)
|
||||
}
|
||||
|
||||
/// `try? SQLiteDatabase.open()`
|
||||
var AppDB: SQLiteDatabase? { get { try? SQLiteDatabase.open() } }
|
||||
typealias SQLiteRowID = sqlite3_int64
|
||||
/// `0` indicates an unbound edge.
|
||||
typealias SQLiteRowRange = (start: SQLiteRowID, end: SQLiteRowID)
|
||||
|
||||
// MARK: - SQLiteDatabase
|
||||
|
||||
class SQLiteDatabase {
|
||||
fileprivate var functions = [String: [Int: Function]]()
|
||||
private let dbPointer: OpaquePointer?
|
||||
private init(dbPointer: OpaquePointer?) {
|
||||
self.dbPointer = dbPointer
|
||||
}
|
||||
|
||||
fileprivate var errorMessage: String {
|
||||
if let errorPointer = sqlite3_errmsg(dbPointer) {
|
||||
let errorMessage = String(cString: errorPointer)
|
||||
return errorMessage
|
||||
} else {
|
||||
return "No error message provided from sqlite."
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
sqlite3_close_v2(dbPointer)
|
||||
}
|
||||
|
||||
static func destroyDatabase(path: String = URL.internalDB().relativePath) {
|
||||
if FileManager.default.fileExists(atPath: path) {
|
||||
do { try FileManager.default.removeItem(atPath: path) }
|
||||
catch { print("Could not destroy database file: \(path)") }
|
||||
}
|
||||
}
|
||||
|
||||
static func open(path: String = URL.internalDB().relativePath) throws -> SQLiteDatabase {
|
||||
var db: OpaquePointer?
|
||||
if sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK {
|
||||
return SQLiteDatabase(dbPointer: db)
|
||||
} else {
|
||||
defer { sqlite3_close_v2(db) }
|
||||
if let errorPointer = sqlite3_errmsg(db) {
|
||||
let message = String(cString: errorPointer)
|
||||
throw SQLiteError.OpenDatabase(message: message)
|
||||
} else {
|
||||
throw SQLiteError.OpenDatabase(message: "No error message provided from sqlite.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run<T>(sql: String, bind: [DBBinding?] = [], step: (OpaquePointer) throws -> T) throws -> T {
|
||||
// print("SQL run: \(sql)")
|
||||
// for x in bind where x != nil {
|
||||
// print(" -> \(x!)")
|
||||
// }
|
||||
var statement: OpaquePointer?
|
||||
guard sqlite3_prepare_v2(dbPointer, sql, -1, &statement, nil) == SQLITE_OK,
|
||||
let stmt = statement else {
|
||||
throw SQLiteError.Prepare(message: errorMessage)
|
||||
}
|
||||
defer { sqlite3_finalize(stmt) }
|
||||
var col: Int32 = 0
|
||||
for b in bind.compactMap({$0}) {
|
||||
col += 1
|
||||
guard b.bind(stmt, col) == SQLITE_OK else {
|
||||
throw SQLiteError.Bind(message: errorMessage)
|
||||
}
|
||||
}
|
||||
return try step(stmt)
|
||||
}
|
||||
|
||||
func run(sql: String) throws {
|
||||
// print("SQL exec: \(sql)")
|
||||
var err: UnsafeMutablePointer<Int8>? = nil
|
||||
if sqlite3_exec(dbPointer, sql, nil, nil, &err) != SQLITE_OK {
|
||||
let errMsg = (err != nil) ? String(cString: err!) : "Unknown execution error"
|
||||
sqlite3_free(err);
|
||||
throw SQLiteError.Step(message: errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func ifStep(_ stmt: OpaquePointer, _ expected: Int32) throws {
|
||||
guard sqlite3_step(stmt) == expected else {
|
||||
throw SQLiteError.Step(message: errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
func vacuum() {
|
||||
try? run(sql: "VACUUM;")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Custom Functions
|
||||
|
||||
// let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self)
|
||||
let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
||||
|
||||
public struct Blob {
|
||||
public let bytes: [UInt8]
|
||||
public init(bytes: [UInt8]) { self.bytes = bytes }
|
||||
public init(bytes: UnsafeRawPointer, length: Int) {
|
||||
let i8bufptr = UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: length)
|
||||
self.init(bytes: [UInt8](i8bufptr))
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
fileprivate typealias Function = @convention(block) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void
|
||||
|
||||
func createFunction(_ function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: @escaping (_ args: [Any?]) -> Any?) {
|
||||
let argc = argumentCount.map { Int($0) } ?? -1
|
||||
let box: Function = { context, argc, argv in
|
||||
let arguments: [Any?] = (0..<Int(argc)).map {
|
||||
let value = argv![$0]
|
||||
switch sqlite3_value_type(value) {
|
||||
case SQLITE_BLOB: return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value)))
|
||||
case SQLITE_FLOAT: return sqlite3_value_double(value)
|
||||
case SQLITE_INTEGER: return sqlite3_value_int64(value)
|
||||
case SQLITE_NULL: return nil
|
||||
case SQLITE_TEXT: return String(cString: UnsafePointer(sqlite3_value_text(value)))
|
||||
case let type: fatalError("unsupported value type: \(type)")
|
||||
}
|
||||
}
|
||||
let result = block(arguments)
|
||||
if let r = result as? Blob { sqlite3_result_blob(context, r.bytes, Int32(r.bytes.count), nil) }
|
||||
else if let r = result as? Double { sqlite3_result_double(context, r) }
|
||||
else if let r = result as? Int64 { sqlite3_result_int64(context, r) }
|
||||
else if let r = result as? Bool { sqlite3_result_int(context, r ? 1 : 0) }
|
||||
else if let r = result as? String { sqlite3_result_text(context, r, Int32(r.count), SQLITE_TRANSIENT) }
|
||||
else if result == nil { sqlite3_result_null(context) }
|
||||
else { fatalError("unsupported result type: \(String(describing: result))") }
|
||||
}
|
||||
var flags = SQLITE_UTF8
|
||||
if deterministic {
|
||||
flags |= SQLITE_DETERMINISTIC
|
||||
}
|
||||
sqlite3_create_function_v2(dbPointer, function, Int32(argc), flags, unsafeBitCast(box, to: UnsafeMutableRawPointer.self), { context, argc, value in
|
||||
let function = unsafeBitCast(sqlite3_user_data(context), to: Function.self)
|
||||
function(context, argc, value)
|
||||
}, nil, nil, nil)
|
||||
if functions[function] == nil { functions[function] = [:] }
|
||||
functions[function]?[argc] = box
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Bindings
|
||||
|
||||
protocol DBBinding {
|
||||
func bind(_ stmt: OpaquePointer!, _ col: Int32) -> Int32
|
||||
}
|
||||
|
||||
struct BindInt32 : DBBinding {
|
||||
let raw: Int32
|
||||
init(_ value: Int32) { raw = value }
|
||||
func bind(_ stmt: OpaquePointer!, _ col: Int32) -> Int32 { sqlite3_bind_int(stmt, col, raw) }
|
||||
}
|
||||
|
||||
struct BindInt64 : DBBinding {
|
||||
let raw: sqlite3_int64
|
||||
init(_ value: sqlite3_int64) { raw = value }
|
||||
func bind(_ stmt: OpaquePointer!, _ col: Int32) -> Int32 { sqlite3_bind_int64(stmt, col, raw) }
|
||||
}
|
||||
|
||||
struct BindText : DBBinding {
|
||||
let raw: String
|
||||
init(_ value: String) { raw = value }
|
||||
func bind(_ stmt: OpaquePointer!, _ col: Int32) -> Int32 { sqlite3_bind_text(stmt, col, (raw as NSString).utf8String, -1, nil) }
|
||||
}
|
||||
|
||||
struct BindTextOrNil : DBBinding {
|
||||
let raw: String?
|
||||
init(_ value: String?) { raw = value }
|
||||
func bind(_ stmt: OpaquePointer!, _ col: Int32) -> Int32 { sqlite3_bind_text(stmt, col, (raw == nil) ? nil : (raw! as NSString).utf8String, -1, nil) }
|
||||
}
|
||||
|
||||
// MARK: - Easy Access func
|
||||
|
||||
extension SQLiteDatabase {
|
||||
var numberOfChanges: Int32 { get { sqlite3_changes(dbPointer) } }
|
||||
var lastInsertedRow: SQLiteRowID { get { sqlite3_last_insert_rowid(dbPointer) } }
|
||||
|
||||
func readText(_ stmt: OpaquePointer, _ col: Int32) -> String? {
|
||||
let val = sqlite3_column_text(stmt, col)
|
||||
return (val != nil ? String(cString: val!) : nil)
|
||||
}
|
||||
|
||||
func allRows<T>(_ stmt: OpaquePointer, _ fn: (OpaquePointer) -> T) -> [T] {
|
||||
var r: [T] = []
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) { r.append(fn(stmt)) }
|
||||
return r
|
||||
}
|
||||
|
||||
func allRowsKeyed<T,U>(_ stmt: OpaquePointer, _ fn: (OpaquePointer) -> (key: T, value: U)) -> [T:U] {
|
||||
var r: [T:U] = [:]
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) { let (k,v) = fn(stmt); r[k] = v }
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Prepared Statement
|
||||
|
||||
extension SQLiteDatabase {
|
||||
func prepare(sql: String) throws -> OpaquePointer {
|
||||
var pStmt: OpaquePointer?
|
||||
guard sqlite3_prepare_v2(dbPointer, sql, -1, &pStmt, nil) == SQLITE_OK, let S = pStmt else {
|
||||
sqlite3_finalize(pStmt)
|
||||
throw SQLiteError.Prepare(message: errorMessage)
|
||||
}
|
||||
return S
|
||||
}
|
||||
|
||||
@discardableResult func prepared(run pStmt: OpaquePointer!, bind: [DBBinding?] = []) throws -> Int32 {
|
||||
defer { sqlite3_reset(pStmt) }
|
||||
var col: Int32 = 0
|
||||
for b in bind.compactMap({$0}) {
|
||||
col += 1
|
||||
guard b.bind(pStmt, col) == SQLITE_OK else {
|
||||
throw SQLiteError.Bind(message: errorMessage)
|
||||
}
|
||||
}
|
||||
return sqlite3_step(pStmt)
|
||||
}
|
||||
|
||||
func prepared(finalize pStmt: OpaquePointer!) {
|
||||
sqlite3_finalize(pStmt)
|
||||
}
|
||||
}
|
||||
40
main/DB/DBExtensions.swift
Normal file
@@ -0,0 +1,40 @@
|
||||
import UIKit
|
||||
|
||||
extension GroupedDomain {
|
||||
/// Return new `GroupedDomain` by adding `total` and `blocked` counts. Set `lastModified` to the maximum of the two.
|
||||
static func +(a: GroupedDomain, b: GroupedDomain) -> Self {
|
||||
GroupedDomain(domain: a.domain, total: a.total + b.total, blocked: a.blocked + b.blocked,
|
||||
lastModified: max(a.lastModified, b.lastModified), options: a.options ?? b.options )
|
||||
}
|
||||
/// Return new `GroupedDomain` by subtracting `total` and `blocked` counts.
|
||||
static func -(a: GroupedDomain, b: GroupedDomain) -> Self {
|
||||
GroupedDomain(domain: a.domain, total: a.total - b.total, blocked: a.blocked - b.blocked,
|
||||
lastModified: a.lastModified, options: a.options )
|
||||
}
|
||||
}
|
||||
|
||||
extension GroupedDomain {
|
||||
var detailCellText: String { get {
|
||||
return blocked > 0
|
||||
? "\(DateFormat.seconds(lastModified)) — \(blocked)/\(total) blocked"
|
||||
: "\(DateFormat.seconds(lastModified)) — \(total)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FilterOptions {
|
||||
func tableRowImage() -> UIImage? {
|
||||
let blocked = contains(.blocked)
|
||||
let ignored = contains(.ignored)
|
||||
if blocked { return UIImage(named: ignored ? "block_ignore" : "shield-x") }
|
||||
if ignored { return UIImage(named: "quicklook-not") }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension Recording {
|
||||
var fallbackTitle: String { get { "Unnamed Recording #\(id)" } }
|
||||
var duration: Timestamp? { get { stop == nil ? nil : stop! - start } }
|
||||
var durationString: String? { get { stop == nil ? nil : TimeFormat.from(duration!) } }
|
||||
}
|
||||
|
||||
@@ -1,304 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
let DBWrp = DBWrapper()
|
||||
fileprivate var AppDB: SQLiteDatabase? { get { try? SQLiteDatabase.open() } }
|
||||
|
||||
class DBWrapper {
|
||||
private var latestModification: Timestamp = 0
|
||||
private var dataA: [GroupedDomain] = [] // Domains
|
||||
private var dataB: [[GroupedDomain]] = [] // Hosts
|
||||
private var dataF: [String : FilterOptions] = [:] // Filters
|
||||
private let Q = DispatchQueue(label: "de.uni-bamberg.psi.AppCheck.db-wrapper-queue", attributes: .concurrent)
|
||||
|
||||
// auto update rows callback
|
||||
var currentlyOpenParent: String?
|
||||
weak var dataA_delegate: IncrementalDataSourceUpdate?
|
||||
weak var dataB_delegate: IncrementalDataSourceUpdate?
|
||||
func dataB_delegate(_ parent: String) -> IncrementalDataSourceUpdate? {
|
||||
(currentlyOpenParent == parent) ? dataB_delegate : nil
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Data Source Getter
|
||||
|
||||
func listOfDomains() -> [GroupedDomain] {
|
||||
Q.sync() { dataA }
|
||||
}
|
||||
|
||||
func listOfHosts(_ parent: String) -> [GroupedDomain] {
|
||||
Q.sync() { dataB[ifExist: dataA_index(of: parent)] ?? [] }
|
||||
}
|
||||
|
||||
func dataF_list(_ filter: FilterOptions) -> [String] {
|
||||
Q.sync() { dataF.compactMap { $1.contains(filter) ? $0 : nil } }.sorted()
|
||||
}
|
||||
|
||||
func dataF_counts() -> (blocked: Int, ignored: Int) {
|
||||
Q.sync() { dataF.reduce((0, 0)) {
|
||||
($0.0 + ($1.1.contains(.blocked) ? 1 : 0),
|
||||
$0.1 + ($1.1.contains(.ignored) ? 1 : 0)) }}
|
||||
}
|
||||
|
||||
func listOfTimes(_ domain: String?) -> [(Timestamp, Bool)] {
|
||||
guard let domain = domain else { return [] }
|
||||
return AppDB?.timesForDomain(domain)?.reversed() ?? []
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
func initContentOfDB() {
|
||||
QLog.Debug("SQLite path: \(URL.internalDB())")
|
||||
DispatchQueue.global().async {
|
||||
#if IOS_SIMULATOR
|
||||
self.generateTestData()
|
||||
DispatchQueue.main.async {
|
||||
// dont know why main queue is needed, wont start otherwise
|
||||
Timer.repeating(2, call: #selector(self.insertRandomEntry), on: self)
|
||||
}
|
||||
#endif
|
||||
self.dataF_init()
|
||||
self.dataAB_init()
|
||||
self.autoSyncTimer_init()
|
||||
}
|
||||
}
|
||||
|
||||
private func dataF_init() {
|
||||
let list = AppDB?.loadFilters() ?? [:]
|
||||
Q.async(flags: .barrier) {
|
||||
self.dataF = list
|
||||
NotifyFilterChanged.postAsyncMain()
|
||||
}
|
||||
}
|
||||
|
||||
private func dataAB_init() {
|
||||
let list = AppDB?.domainList()
|
||||
Q.async(flags: .barrier) {
|
||||
self.dataA = []
|
||||
self.dataB = []
|
||||
self.latestModification = 0
|
||||
if let allDomains = list {
|
||||
for (parent, parts) in self.groupBySubdomains(allDomains) {
|
||||
self.dataA.append(parent)
|
||||
self.dataB.append(parts)
|
||||
self.latestModification = max(parent.lastModified, self.latestModification)
|
||||
}
|
||||
}
|
||||
NotifyLogHistoryReset.postAsyncMain()
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto sync new logs every 7 seconds.
|
||||
private func autoSyncTimer_init() {
|
||||
Q.async() { // using Q to start timer only after init data A,B,F
|
||||
DispatchQueue.main.async {
|
||||
// dont know why main queue is needed, wont start otherwise
|
||||
Timer.repeating(7, call: #selector(self.syncNewestLogs), on: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Partial Update History
|
||||
|
||||
@objc private func syncNewestLogs() {
|
||||
//QLog.Debug("\(#function)")
|
||||
#if !IOS_SIMULATOR
|
||||
guard currentVPNState == .on else { return }
|
||||
#endif
|
||||
guard let res = AppDB?.domainList(since: latestModification), res.count > 0 else {
|
||||
return
|
||||
}
|
||||
QLog.Info("auto sync \(res.count) new logs")
|
||||
Q.async(flags: .barrier) {
|
||||
var c = 0
|
||||
for (parent, parts) in self.groupBySubdomains(res) {
|
||||
if let i = self.dataA_index(of: parent.domain) {
|
||||
self.mergeExistingParts(parent.domain, at: i, newChildren: parts)
|
||||
|
||||
let merged = parent + self.dataA.remove(at: i)
|
||||
self.dataA.insert(merged, at: c)
|
||||
self.dataB.insert(self.dataB.remove(at: i), at: c)
|
||||
self.dataA_delegate?.moveRow(merged, from: i, to: c)
|
||||
} else {
|
||||
self.dataA.insert(parent, at: c)
|
||||
self.dataB.insert(parts, at: c)
|
||||
self.dataA_delegate?.insertRow(parent, at: c)
|
||||
}
|
||||
c += 1
|
||||
self.latestModification = max(parent.lastModified, self.latestModification)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func mergeExistingParts(_ dom: String, at index: Int, newChildren: [GroupedDomain]) {
|
||||
let tvc = dataB_delegate(dom)
|
||||
var i = 0
|
||||
for child in newChildren {
|
||||
if let u = dataB[index].firstIndex(where: { $0.domain == child.domain }) {
|
||||
let merged = child + dataB[index].remove(at: u)
|
||||
dataB[index].insert(merged, at: i)
|
||||
tvc?.moveRow(merged, from: u, to: i)
|
||||
} else {
|
||||
dataB[index].insert(child, at: i)
|
||||
tvc?.insertRow(child, at: i)
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Delete History
|
||||
|
||||
func deleteHistory() {
|
||||
DispatchQueue.global().async {
|
||||
try? AppDB?.destroyContent()
|
||||
AppDB?.vacuum()
|
||||
self.dataAB_init()
|
||||
}
|
||||
}
|
||||
|
||||
func deleteHistory(domain: String, since ts: Timestamp) {
|
||||
DispatchQueue.global().async {
|
||||
let modified = (try? AppDB?.deleteRows(matching: domain, since: ts)) ?? 0
|
||||
guard modified > 0 else {
|
||||
return // nothing has changed
|
||||
}
|
||||
AppDB?.vacuum()
|
||||
self.Q.async(flags: .barrier) {
|
||||
guard let index = self.dataA_index(of: domain) else {
|
||||
return // nothing has changed
|
||||
}
|
||||
let parentDom = self.dataA[index].domain
|
||||
guard let list = AppDB?.domainList(matching: parentDom), list.count > 0 else {
|
||||
self.dataA.remove(at: index)
|
||||
self.dataB.remove(at: index)
|
||||
self.dataA_delegate?.deleteRow(at: index)
|
||||
self.dataB_delegate(parentDom)?.replaceData(with: [])
|
||||
return // nothing left, after deleting matching rows
|
||||
}
|
||||
// else: incremental update, replace whole list
|
||||
self.dataA[index] = list.merge(parentDom, options: self.dataF[parentDom])
|
||||
self.dataA_delegate?.replaceRow(self.dataA[index], at: index)
|
||||
self.dataB[index].removeAll()
|
||||
for var child in list {
|
||||
child.options = self.dataF[child.domain]
|
||||
self.dataB[index].append(child)
|
||||
}
|
||||
self.dataB_delegate(parentDom)?.replaceData(with: self.dataB[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Partial Update Filter
|
||||
|
||||
func updateFilter(_ domain: String, add: FilterOptions) {
|
||||
updateFilter(domain, set: (dataF[domain] ?? FilterOptions()).union(add))
|
||||
}
|
||||
|
||||
func updateFilter(_ domain: String, remove: FilterOptions) {
|
||||
updateFilter(domain, set: dataF[domain]?.subtracting(remove))
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - set: Remove a filter with `nil` or `.none`
|
||||
private func updateFilter(_ domain: String, set: FilterOptions?) {
|
||||
AppDB?.setFilter(domain, set)
|
||||
Q.async(flags: .barrier) {
|
||||
self.dataF[domain] = set
|
||||
if let i = self.dataA_index(of: domain) {
|
||||
if domain == self.dataA[i].domain {
|
||||
self.dataA[i].options = (set == FilterOptions.none) ? nil : set
|
||||
self.dataA_delegate?.replaceRow(self.dataA[i], at: i)
|
||||
}
|
||||
if let u = self.dataB[i].firstIndex(where: { $0.domain == domain }) {
|
||||
self.dataB[i][u].options = (set == FilterOptions.none) ? nil : set
|
||||
self.dataB_delegate(self.dataA[i].domain)?.replaceRow(self.dataB[i][u], at: u)
|
||||
}
|
||||
}
|
||||
NotifyFilterChanged.postAsyncMain()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Recordings
|
||||
|
||||
func listOfRecordings() -> [Recording] { AppDB?.allRecordings() ?? [] }
|
||||
func recordingGetCurrent() -> Recording? { AppDB?.ongoingRecording() }
|
||||
func recordingStartNew() -> Recording? { try? AppDB?.startNewRecording() }
|
||||
|
||||
func recordingStop(_ r: inout Recording) { AppDB?.stopRecording(&r) }
|
||||
func recordingPersist(_ r: Recording) { AppDB?.persistRecordingLogs(r) }
|
||||
func recordingDetails(_ r: Recording) -> [RecordLog] { AppDB?.getRecordingsLogs(r) ?? [] }
|
||||
|
||||
func recordingUpdate(_ r: Recording) {
|
||||
AppDB?.updateRecording(r)
|
||||
NotifyRecordingChanged.post((r, false))
|
||||
}
|
||||
|
||||
func recordingDelete(_ r: Recording) {
|
||||
if (try? AppDB?.deleteRecording(r)) == true {
|
||||
NotifyRecordingChanged.post((r, true))
|
||||
}
|
||||
}
|
||||
|
||||
func recordingDeleteDetails(_ r: Recording, domain: String?) -> Bool {
|
||||
((try? AppDB?.deleteRecordingLogs(r.id, matchingDomain: domain)) ?? 0) > 0
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Helper methods
|
||||
|
||||
private func dataA_index(of domain: String) -> Int? {
|
||||
dataA.firstIndex { domain.isSubdomain(of: $0.domain) }
|
||||
}
|
||||
|
||||
private func groupBySubdomains(_ allDomains: [GroupedDomain]) -> [(parent: GroupedDomain, parts: [GroupedDomain])] {
|
||||
var i: Int = 0
|
||||
var indexOf: [String: Int] = [:]
|
||||
var res: [(domain: String, list: [GroupedDomain])] = []
|
||||
for var x in allDomains {
|
||||
let domain = x.domain.splitDomainAndHost().domain
|
||||
x.options = dataF[x.domain]
|
||||
if let y = indexOf[domain] {
|
||||
res[y].list.append(x)
|
||||
} else {
|
||||
res.append((domain, [x]))
|
||||
indexOf[domain] = i
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
return res.map { ($1.merge($0, options: self.dataF[$0]), $1) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Test Data
|
||||
|
||||
extension DBWrapper {
|
||||
private func generateTestData() {
|
||||
guard let db = AppDB else { return }
|
||||
let deleted = (try? db.deleteRows(matching: "test.com")) ?? 0
|
||||
QLog.Debug("Deleting \(deleted) rows matching 'test.com'")
|
||||
|
||||
QLog.Debug("Writing 33 test logs")
|
||||
try? db.insertDNSQuery("keeptest.com", blocked: false)
|
||||
for _ in 1...4 { try? db.insertDNSQuery("test.com", blocked: false) }
|
||||
for _ in 1...7 { try? db.insertDNSQuery("i.test.com", blocked: false) }
|
||||
for i in 1...8 { try? db.insertDNSQuery("b.test.com", blocked: i>5) }
|
||||
for i in 1...13 { try? db.insertDNSQuery("bi.test.com", blocked: i%2==0) }
|
||||
|
||||
QLog.Debug("Creating 4 filters")
|
||||
db.setFilter("b.test.com", .blocked)
|
||||
db.setFilter("i.test.com", .ignored)
|
||||
db.setFilter("bi.test.com", [.blocked, .ignored])
|
||||
|
||||
QLog.Debug("Done")
|
||||
}
|
||||
|
||||
@objc private func insertRandomEntry() {
|
||||
//QLog.Debug("Inserting 1 periodic log entry")
|
||||
try? AppDB?.insertDNSQuery("\(arc4random() % 5).count.test.com", blocked: true)
|
||||
}
|
||||
}
|
||||
@@ -1,464 +0,0 @@
|
||||
import Foundation
|
||||
import SQLite3
|
||||
|
||||
typealias Timestamp = Int64
|
||||
struct GroupedDomain {
|
||||
let domain: String, total: Int32, blocked: Int32, lastModified: Timestamp
|
||||
var options: FilterOptions? = nil
|
||||
}
|
||||
|
||||
struct FilterOptions: OptionSet {
|
||||
let rawValue: Int32
|
||||
static let none = FilterOptions([])
|
||||
static let blocked = FilterOptions(rawValue: 1 << 0)
|
||||
static let ignored = FilterOptions(rawValue: 1 << 1)
|
||||
static let any = FilterOptions(rawValue: 0b11)
|
||||
}
|
||||
|
||||
enum SQLiteError: Error {
|
||||
case OpenDatabase(message: String)
|
||||
case Prepare(message: String)
|
||||
case Step(message: String)
|
||||
case Bind(message: String)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLiteDatabase
|
||||
|
||||
class SQLiteDatabase {
|
||||
private let dbPointer: OpaquePointer?
|
||||
private init(dbPointer: OpaquePointer?) {
|
||||
self.dbPointer = dbPointer
|
||||
}
|
||||
|
||||
fileprivate var errorMessage: String {
|
||||
if let errorPointer = sqlite3_errmsg(dbPointer) {
|
||||
let errorMessage = String(cString: errorPointer)
|
||||
return errorMessage
|
||||
} else {
|
||||
return "No error message provided from sqlite."
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
sqlite3_close(dbPointer)
|
||||
}
|
||||
|
||||
static func destroyDatabase(path: String = URL.internalDB().relativePath) {
|
||||
if FileManager.default.fileExists(atPath: path) {
|
||||
do { try FileManager.default.removeItem(atPath: path) }
|
||||
catch { print("Could not destroy database file: \(path)") }
|
||||
}
|
||||
}
|
||||
|
||||
// static func export() throws -> URL {
|
||||
// let fmt = DateFormatter()
|
||||
// fmt.dateFormat = "yyyy-MM-dd"
|
||||
// let dest = FileManager.default.exportDir().appendingPathComponent("\(fmt.string(from: Date()))-dns-log.sqlite")
|
||||
// try? FileManager.default.removeItem(at: dest)
|
||||
// try FileManager.default.copyItem(at: FileManager.default.internalDB(), to: dest)
|
||||
// return dest
|
||||
// }
|
||||
|
||||
static func open(path: String = URL.internalDB().relativePath) throws -> SQLiteDatabase {
|
||||
var db: OpaquePointer?
|
||||
//sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE, nil)
|
||||
if sqlite3_open(path, &db) == SQLITE_OK {
|
||||
return SQLiteDatabase(dbPointer: db)
|
||||
} else {
|
||||
defer {
|
||||
if db != nil {
|
||||
sqlite3_close(db)
|
||||
}
|
||||
}
|
||||
if let errorPointer = sqlite3_errmsg(db) {
|
||||
let message = String(cString: errorPointer)
|
||||
throw SQLiteError.OpenDatabase(message: message)
|
||||
} else {
|
||||
throw SQLiteError.OpenDatabase(message: "No error message provided from sqlite.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run<T>(sql: String, bind: ((OpaquePointer) -> Bool)?, step: (OpaquePointer) throws -> T) throws -> T {
|
||||
var statement: OpaquePointer?
|
||||
guard sqlite3_prepare_v2(dbPointer, sql, -1, &statement, nil) == SQLITE_OK,
|
||||
let stmt = statement else {
|
||||
throw SQLiteError.Prepare(message: errorMessage)
|
||||
}
|
||||
defer { sqlite3_finalize(stmt) }
|
||||
guard bind?(stmt) ?? true else {
|
||||
throw SQLiteError.Bind(message: errorMessage)
|
||||
}
|
||||
return try step(stmt)
|
||||
}
|
||||
|
||||
func ifStep(_ stmt: OpaquePointer, _ expected: Int32) throws {
|
||||
guard sqlite3_step(stmt) == expected else {
|
||||
throw SQLiteError.Step(message: errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
func createTable(table: SQLTable.Type) throws {
|
||||
try run(sql: table.createStatement, bind: nil) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
}
|
||||
}
|
||||
|
||||
func vacuum() {
|
||||
try? run(sql: "VACUUM;", bind: nil) { try ifStep($0, SQLITE_DONE) }
|
||||
}
|
||||
}
|
||||
|
||||
protocol SQLTable {
|
||||
static var createStatement: String { get }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Easy Access func
|
||||
|
||||
private extension SQLiteDatabase {
|
||||
func bindInt(_ stmt: OpaquePointer, _ col: Int32, _ value: Int32) -> Bool {
|
||||
sqlite3_bind_int(stmt, col, value) == SQLITE_OK
|
||||
}
|
||||
|
||||
func bindInt64(_ stmt: OpaquePointer, _ col: Int32, _ value: sqlite3_int64) -> Bool {
|
||||
sqlite3_bind_int64(stmt, col, value) == SQLITE_OK
|
||||
}
|
||||
|
||||
func bindText(_ stmt: OpaquePointer, _ col: Int32, _ value: String) -> Bool {
|
||||
sqlite3_bind_text(stmt, col, (value as NSString).utf8String, -1, nil) == SQLITE_OK
|
||||
}
|
||||
|
||||
func bindTextOrNil(_ stmt: OpaquePointer, _ col: Int32, _ value: String?) -> Bool {
|
||||
sqlite3_bind_text(stmt, col, (value == nil) ? nil : (value! as NSString).utf8String, -1, nil) == SQLITE_OK
|
||||
}
|
||||
|
||||
func readText(_ stmt: OpaquePointer, _ col: Int32) -> String? {
|
||||
let val = sqlite3_column_text(stmt, col)
|
||||
return (val != nil ? String(cString: val!) : nil)
|
||||
}
|
||||
|
||||
func allRows<T>(_ stmt: OpaquePointer, _ fn: (OpaquePointer) -> T) -> [T] {
|
||||
var r: [T] = []
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) { r.append(fn(stmt)) }
|
||||
return r
|
||||
}
|
||||
|
||||
func allRowsKeyed<T,U>(_ stmt: OpaquePointer, _ fn: (OpaquePointer) -> (key: T, value: U)) -> [T:U] {
|
||||
var r: [T:U] = [:]
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) { let (k,v) = fn(stmt); r[k] = v }
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
func initScheme() {
|
||||
try? self.createTable(table: DNSQueryT.self)
|
||||
try? self.createTable(table: DNSFilterT.self)
|
||||
try? self.createTable(table: Recording.self)
|
||||
try? self.createTable(table: RecordingLog.self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DNSQueryT
|
||||
|
||||
private struct DNSQueryT: SQLTable {
|
||||
let ts: Timestamp
|
||||
let domain: String
|
||||
let wasBlocked: Bool
|
||||
let options: FilterOptions
|
||||
static var createStatement: String {
|
||||
return """
|
||||
CREATE TABLE IF NOT EXISTS req(
|
||||
ts INTEGER DEFAULT (strftime('%s','now')),
|
||||
domain TEXT NOT NULL,
|
||||
logOpt INTEGER DEFAULT 0
|
||||
);
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: insert
|
||||
|
||||
func insertDNSQuery(_ domain: String, blocked: Bool) throws {
|
||||
try? run(sql: "INSERT INTO req (domain, logOpt) VALUES (?, ?);", bind: {
|
||||
self.bindText($0, 1, domain) && self.bindInt($0, 2, blocked ? 1 : 0)
|
||||
}) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: delete
|
||||
|
||||
func destroyContent() throws {
|
||||
try? run(sql: "DROP TABLE IF EXISTS req;", bind: nil) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
}
|
||||
try? createTable(table: DNSQueryT.self)
|
||||
}
|
||||
|
||||
/// Delete rows matching `ts >= ? AND "domain" OR "*.domain"`
|
||||
@discardableResult func deleteRows(matching domain: String, since ts: Timestamp = 0) throws -> Int32 {
|
||||
try run(sql: "DELETE FROM req WHERE ts >= ? AND (domain = ? OR domain LIKE '%.' || ?);", bind: {
|
||||
self.bindInt64($0, 1, ts) && self.bindText($0, 2, domain) && self.bindText($0, 3, domain)
|
||||
}) { stmt -> Int32 in
|
||||
try ifStep(stmt, SQLITE_DONE)
|
||||
return sqlite3_changes(dbPointer)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: read
|
||||
|
||||
func readGroupedDomain(_ stmt: OpaquePointer) -> GroupedDomain {
|
||||
GroupedDomain(domain: readText(stmt, 0) ?? "",
|
||||
total: sqlite3_column_int(stmt, 1),
|
||||
blocked: sqlite3_column_int(stmt, 2),
|
||||
lastModified: sqlite3_column_int64(stmt, 3))
|
||||
}
|
||||
|
||||
func domainList(since ts: Timestamp = 0) -> [GroupedDomain]? {
|
||||
try? run(sql: "SELECT domain, COUNT(*), SUM(logOpt&1), MAX(ts) FROM req \(ts == 0 ? "" : "WHERE ts > ?") GROUP BY domain ORDER BY 4 DESC;", bind: {
|
||||
ts == 0 || self.bindInt64($0, 1, ts)
|
||||
}) {
|
||||
allRows($0) { readGroupedDomain($0) }
|
||||
}
|
||||
}
|
||||
|
||||
func domainList(matching domain: String) -> [GroupedDomain]? {
|
||||
try? run(sql: "SELECT domain, COUNT(*), SUM(logOpt&1), MAX(ts) FROM req WHERE (domain = ? OR domain LIKE '%.' || ?) GROUP BY domain ORDER BY 4 DESC;", bind: {
|
||||
self.bindText($0, 1, domain) && self.bindText($0, 2, domain)
|
||||
}) {
|
||||
allRows($0) { readGroupedDomain($0) }
|
||||
}
|
||||
}
|
||||
|
||||
func timesForDomain(_ fullDomain: String) -> [(Timestamp, Bool)]? {
|
||||
try? run(sql: "SELECT ts, logOpt FROM req WHERE domain = ?;", bind: {
|
||||
self.bindText($0, 1, fullDomain)
|
||||
}) {
|
||||
allRows($0) { (sqlite3_column_int64($0, 0), sqlite3_column_int($0, 1) > 0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DNSFilterT
|
||||
|
||||
private struct DNSFilterT: SQLTable {
|
||||
let domain: String
|
||||
let options: FilterOptions
|
||||
static var createStatement: String {
|
||||
return """
|
||||
CREATE TABLE IF NOT EXISTS filter(
|
||||
domain TEXT UNIQUE NOT NULL,
|
||||
opt INTEGER DEFAULT 0
|
||||
);
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: read
|
||||
|
||||
func loadFilters() -> [String : FilterOptions]? {
|
||||
try? run(sql: "SELECT domain, opt FROM filter;", bind: nil) {
|
||||
allRowsKeyed($0) {
|
||||
(key: readText($0, 0) ?? "",
|
||||
value: FilterOptions(rawValue: sqlite3_column_int($0, 1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: write
|
||||
|
||||
func setFilter(_ domain: String, _ value: FilterOptions?) {
|
||||
func removeFilter() {
|
||||
try? run(sql: "DELETE FROM filter WHERE domain = ? LIMIT 1;", bind: {
|
||||
self.bindText($0, 1, domain)
|
||||
}) { stmt -> Void in
|
||||
sqlite3_step(stmt)
|
||||
}
|
||||
}
|
||||
guard let rv = value?.rawValue, rv > 0 else {
|
||||
removeFilter()
|
||||
return
|
||||
}
|
||||
func createFilter() throws {
|
||||
try run(sql: "INSERT OR FAIL INTO filter (domain, opt) VALUES (?, ?);", bind: {
|
||||
self.bindText($0, 1, domain) && self.bindInt($0, 2, rv)
|
||||
}) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
}
|
||||
}
|
||||
func updateFilter() {
|
||||
try? run(sql: "UPDATE filter SET opt = ? WHERE domain = ? LIMIT 1;", bind: {
|
||||
self.bindInt($0, 1, rv) && self.bindText($0, 2, domain)
|
||||
}) { stmt -> Void in
|
||||
sqlite3_step(stmt)
|
||||
}
|
||||
}
|
||||
do { try createFilter() } catch { updateFilter() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Recordings
|
||||
|
||||
struct Recording: SQLTable {
|
||||
let id: sqlite3_int64
|
||||
let start: Timestamp
|
||||
let stop: Timestamp?
|
||||
var appId: String? = nil
|
||||
var title: String? = nil
|
||||
var notes: String? = nil
|
||||
static var createStatement: String {
|
||||
return """
|
||||
CREATE TABLE IF NOT EXISTS rec(
|
||||
id INTEGER PRIMARY KEY,
|
||||
start INTEGER DEFAULT (strftime('%s','now')),
|
||||
stop INTEGER,
|
||||
appid TEXT,
|
||||
title TEXT,
|
||||
notes TEXT
|
||||
);
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: write
|
||||
|
||||
func startNewRecording() throws -> Recording {
|
||||
try run(sql: "INSERT INTO rec (stop) VALUES (NULL);", bind: nil) { stmt -> Recording in
|
||||
try ifStep(stmt, SQLITE_DONE)
|
||||
return try getRecording(withID: sqlite3_last_insert_rowid(dbPointer))
|
||||
}
|
||||
}
|
||||
|
||||
func stopRecording(_ r: inout Recording) {
|
||||
guard r.stop == nil else { return }
|
||||
let theID = r.id
|
||||
try? run(sql: "UPDATE rec SET stop = (strftime('%s','now')) WHERE id = ? LIMIT 1;", bind: {
|
||||
self.bindInt64($0, 1, theID)
|
||||
}) { stmt -> Void in
|
||||
try ifStep(stmt, SQLITE_DONE)
|
||||
r = try getRecording(withID: theID)
|
||||
}
|
||||
}
|
||||
|
||||
func updateRecording(_ r: Recording) {
|
||||
try? run(sql: "UPDATE rec SET title = ?, appid = ?, notes = ? WHERE id = ? LIMIT 1;", bind: {
|
||||
self.bindTextOrNil($0, 1, r.title) && self.bindTextOrNil($0, 2, r.appId)
|
||||
&& self.bindTextOrNil($0, 3, r.notes) && self.bindInt64($0, 4, r.id)
|
||||
}) { stmt -> Void in
|
||||
sqlite3_step(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteRecording(_ r: Recording) throws -> Bool {
|
||||
_ = try? deleteRecordingLogs(r.id)
|
||||
return try run(sql: "DELETE FROM rec WHERE id = ? LIMIT 1;", bind: {
|
||||
self.bindInt64($0, 1, r.id)
|
||||
}) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
return sqlite3_changes(dbPointer) > 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: read
|
||||
|
||||
func readRecording(_ stmt: OpaquePointer) -> Recording {
|
||||
let end = sqlite3_column_int64(stmt, 2)
|
||||
return Recording(id: sqlite3_column_int64(stmt, 0),
|
||||
start: sqlite3_column_int64(stmt, 1),
|
||||
stop: end == 0 ? nil : end,
|
||||
appId: readText(stmt, 3),
|
||||
title: readText(stmt, 4),
|
||||
notes: readText(stmt, 5))
|
||||
}
|
||||
|
||||
func ongoingRecording() -> Recording? {
|
||||
try? run(sql: "SELECT * FROM rec WHERE stop IS NULL LIMIT 1;", bind: nil) {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return readRecording($0)
|
||||
}
|
||||
}
|
||||
|
||||
func allRecordings() -> [Recording]? {
|
||||
try? run(sql: "SELECT * FROM rec WHERE stop IS NOT NULL;", bind: nil) {
|
||||
allRows($0) { readRecording($0) }
|
||||
}
|
||||
}
|
||||
|
||||
func getRecording(withID: sqlite3_int64) throws -> Recording {
|
||||
try run(sql: "SELECT * FROM rec WHERE id = ? LIMIT 1;", bind: {
|
||||
self.bindInt64($0, 1, withID)
|
||||
}) {
|
||||
try ifStep($0, SQLITE_ROW)
|
||||
return readRecording($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK:
|
||||
|
||||
private struct RecordingLog: SQLTable {
|
||||
let rID: Int32
|
||||
let ts: Timestamp
|
||||
let domain: String
|
||||
static var createStatement: String {
|
||||
return """
|
||||
CREATE TABLE IF NOT EXISTS recLog(
|
||||
rid INTEGER REFERENCES rec(id) ON DELETE CASCADE,
|
||||
ts INTEGER,
|
||||
domain TEXT
|
||||
);
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLiteDatabase {
|
||||
|
||||
// MARK: write
|
||||
|
||||
func persistRecordingLogs(_ r: Recording) {
|
||||
guard let end = r.stop else {
|
||||
return
|
||||
}
|
||||
try? run(sql: """
|
||||
INSERT INTO recLog (rid, ts, domain) SELECT ?, ts, domain FROM req
|
||||
WHERE req.ts >= ? AND req.ts <= ?
|
||||
""", bind: {
|
||||
self.bindInt64($0, 1, r.id) && self.bindInt64($0, 2, r.start) && self.bindInt64($0, 3, end)
|
||||
}) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteRecordingLogs(_ recId: sqlite3_int64, matchingDomain d: String? = nil) throws -> Int32 {
|
||||
try run(sql: "DELETE FROM recLog WHERE rid = ? \(d==nil ? "" : "AND domain = ?");", bind: {
|
||||
self.bindInt64($0, 1, recId) && (d==nil ? true : self.bindTextOrNil($0, 2,d))
|
||||
}) {
|
||||
try ifStep($0, SQLITE_DONE)
|
||||
return sqlite3_changes(dbPointer)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: read
|
||||
|
||||
func getRecordingsLogs(_ r: Recording) -> [RecordLog]? {
|
||||
try? run(sql: "SELECT domain, COUNT() FROM recLog WHERE rid = ? GROUP BY domain;", bind: {
|
||||
self.bindInt64($0, 1, r.id)
|
||||
}) {
|
||||
allRows($0) { (readText($0, 0), sqlite3_column_int($0, 1)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typealias RecordLog = (domain: String?, count: Int32)
|
||||
29
main/DB/TheGreatDestroyer.swift
Normal file
@@ -0,0 +1,29 @@
|
||||
import Foundation
|
||||
|
||||
struct TheGreatDestroyer {
|
||||
|
||||
/// Callback fired when user performs row edit -> delete action
|
||||
static func deleteLogs(domain: String, since ts: Timestamp, strict flag: Bool) {
|
||||
sync.pause()
|
||||
DispatchQueue.global().async {
|
||||
defer { sync.continue() }
|
||||
guard let db = AppDB, db.dnsLogsDelete(domain, strict: flag, since: ts) > 0 else {
|
||||
return // nothing has changed
|
||||
}
|
||||
db.vacuum()
|
||||
sync.needsReloadDB(domain: domain)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fired when user taps on Settings -> Delete All Logs
|
||||
static func deleteAllLogs() {
|
||||
sync.pause()
|
||||
DispatchQueue.global().async {
|
||||
defer { sync.continue() }
|
||||
do {
|
||||
try AppDB?.dnsLogsDeleteAll()
|
||||
sync.needsReloadDB()
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
49
main/Data Source/DomainFilter.swift
Normal file
@@ -0,0 +1,49 @@
|
||||
import Foundation
|
||||
|
||||
enum DomainFilter {
|
||||
static private var data = AppDB?.loadFilters() ?? [:]
|
||||
|
||||
/// Get filter with given `domain` name
|
||||
@inline(__always) static subscript(_ domain: String) -> FilterOptions? {
|
||||
data[domain]
|
||||
}
|
||||
|
||||
/// Update local memory object by loading values from persistent db.
|
||||
/// - Note: Will trigger `NotifyDNSFilterChanged` notification.
|
||||
// static func reload() {
|
||||
// data = AppDB?.loadFilters() ?? [:]
|
||||
// NotifyDNSFilterChanged.post()
|
||||
// }
|
||||
|
||||
/// Get list of domains (sorted by name) which do contain the given filter
|
||||
static func list(where matching: FilterOptions) -> [String] {
|
||||
data.compactMap { $1.contains(matching) ? $0 : nil }.sorted()
|
||||
}
|
||||
|
||||
/// Get total number of blocked and ignored domains. Shown in settings overview.
|
||||
static func counts() -> (blocked: Int, ignored: Int) {
|
||||
data.reduce(into: (0, 0)) {
|
||||
if $1.1.contains(.blocked) { $0.0 += 1 }
|
||||
if $1.1.contains(.ignored) { $0.1 += 1 } }
|
||||
}
|
||||
|
||||
/// Union `filter` with set.
|
||||
/// - Note: Will trigger `NotifyDNSFilterChanged` notification.
|
||||
static func update(_ domain: String, add filter: FilterOptions) {
|
||||
update(domain, set: (data[domain] ?? FilterOptions()).union(filter))
|
||||
}
|
||||
|
||||
/// Subtract `filter` from set.
|
||||
/// - Note: Will trigger `NotifyDNSFilterChanged` notification.
|
||||
static func update(_ domain: String, remove filter: FilterOptions) {
|
||||
update(domain, set: data[domain]?.subtracting(filter))
|
||||
}
|
||||
|
||||
/// Update persistent db, local memory object, and post notification to subscribers
|
||||
/// - Parameter set: Remove a filter with `nil` or `.none`
|
||||
static private func update(_ domain: String, set: FilterOptions?) {
|
||||
AppDB?.setFilter(domain, set)
|
||||
data[domain] = (set == FilterOptions.none) ? nil : set
|
||||
NotifyDNSFilterChanged.post(domain)
|
||||
}
|
||||
}
|
||||
307
main/Data Source/GroupedDomainDataSource.swift
Normal file
@@ -0,0 +1,307 @@
|
||||
import UIKit
|
||||
|
||||
protocol GroupedDomainDataSourceDelegate: UITableViewController {
|
||||
/// Currently only called when a row is moved and the `tableView` is frontmost.
|
||||
func groupedDomainDataSource(needsUpdate row: Int)
|
||||
}
|
||||
|
||||
// ##########################
|
||||
// #
|
||||
// # MARK: DataSource
|
||||
// #
|
||||
// ##########################
|
||||
|
||||
class GroupedDomainDataSource: FilterPipelineDelegate, SyncUpdateDelegate {
|
||||
|
||||
let parent: String?
|
||||
private let pipeline = FilterPipeline<GroupedDomain>()
|
||||
private var currentOrder: DateFilterOrderBy = .Date
|
||||
private var orderAsc = false
|
||||
|
||||
private(set) lazy var search = SearchBarManager { [unowned self] _ in
|
||||
self.pipeline.reloadFilter(withId: "search")
|
||||
}
|
||||
|
||||
/// Will init `sync.allowPullToRefresh()` on `tableView.refreshControl` as well.
|
||||
weak var delegate: GroupedDomainDataSourceDelegate? {
|
||||
willSet { if #available(iOS 10.0, *), newValue !== delegate {
|
||||
sync.allowPullToRefresh(onTVC: newValue, forObserver: self)
|
||||
}}}
|
||||
|
||||
/// - Note: Will call `tableview.reloadData()`
|
||||
init(withParent: String?) {
|
||||
parent = withParent
|
||||
let len: Int
|
||||
if let p = withParent, p.first != "#" { len = p.count } else { len = 0 }
|
||||
|
||||
pipeline.addFilter("search") { [unowned self] in
|
||||
!self.search.isActive ||
|
||||
$0.domain.prefix($0.domain.count - len).lowercased().contains(self.search.term)
|
||||
}
|
||||
pipeline.delegate = self
|
||||
resetSortingOrder(force: true)
|
||||
|
||||
NotifyDNSFilterChanged.observe(call: #selector(didChangeDomainFilter), on: self)
|
||||
NotifySortOrderChanged.observe(call: #selector(didChangeSortOrder), on: self)
|
||||
|
||||
sync.addObserver(self) // calls syncUpdate(reset:)
|
||||
}
|
||||
|
||||
/// Callback fired when user changes date filter settings. (`NotifySortOrderChanged` notification)
|
||||
@objc private func didChangeSortOrder(_ notification: Notification) {
|
||||
resetSortingOrder()
|
||||
}
|
||||
|
||||
/// Read user defaults and apply new sorting order. Either by setting a new or reversing the current.
|
||||
/// - Parameter force: If `true` set new sorting even if the type does not differ.
|
||||
private func resetSortingOrder(force: Bool = false) {
|
||||
let orderAscChanged = (orderAsc <-? Pref.DateFilter.OrderAsc)
|
||||
let orderTypChanged = (currentOrder <-? Pref.DateFilter.OrderBy)
|
||||
if orderTypChanged || force {
|
||||
switch currentOrder {
|
||||
case .Date:
|
||||
pipeline.setSorting { [unowned self] in
|
||||
self.orderAsc ? $0.lastModified < $1.lastModified : $0.lastModified > $1.lastModified
|
||||
}
|
||||
case .Name:
|
||||
pipeline.setSorting { [unowned self] in
|
||||
self.orderAsc ? $0.domain < $1.domain : $0.domain > $1.domain
|
||||
}
|
||||
case .Count:
|
||||
pipeline.setSorting { [unowned self] in
|
||||
self.orderAsc ? $0.total < $1.total : $0.total > $1.total
|
||||
}
|
||||
}
|
||||
} else if orderAscChanged {
|
||||
pipeline.reverseSorting()
|
||||
}
|
||||
}
|
||||
|
||||
/// Callback fired when user edits list of `blocked` or `ignored` domains in settings. (`NotifyDNSFilterChanged` notification)
|
||||
@objc private func didChangeDomainFilter(_ notification: Notification) {
|
||||
guard let domain = notification.object as? String else {
|
||||
preconditionFailure("Domain independent filter reset not implemented") // `syncUpdate(reset:)` async!
|
||||
}
|
||||
if let x = pipeline.dataSourceGet(where: { $0.domain == domain }) {
|
||||
var obj = x.object
|
||||
obj.options = DomainFilter[domain]
|
||||
pipeline.update(obj, at: x.index)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: Table View Data Source
|
||||
|
||||
@inline(__always) var numberOfRows: Int { get { pipeline.displayObjectCount() } }
|
||||
|
||||
@inline(__always) subscript(_ row: Int) -> GroupedDomain { pipeline.displayObject(at: row) }
|
||||
}
|
||||
|
||||
|
||||
// ################################
|
||||
// #
|
||||
// # MARK: - Partial Update
|
||||
// #
|
||||
// ################################
|
||||
|
||||
extension GroupedDomainDataSource {
|
||||
|
||||
func syncUpdate(_: SyncUpdate, reset rows: SQLiteRowRange) {
|
||||
var logs = AppDB?.dnsLogsGrouped(range: rows, parentDomain: parent) ?? []
|
||||
for (i, val) in logs.enumerated() {
|
||||
logs[i].options = DomainFilter[val.domain]
|
||||
}
|
||||
DispatchQueue.main.sync {
|
||||
pipeline.reset(dataSource: logs)
|
||||
}
|
||||
}
|
||||
|
||||
func syncUpdate(_: SyncUpdate, insert rows: SQLiteRowRange, affects: SyncUpdateEnd) {
|
||||
guard let latest = AppDB?.dnsLogsGrouped(range: rows, parentDomain: parent) else {
|
||||
assertionFailure("NotifySyncInsert fired with empty range")
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.sync {
|
||||
cellAnimationsGroup(if: latest.count > 14)
|
||||
for x in latest {
|
||||
if let (i, obj) = pipeline.dataSourceGet(where: { $0.domain == x.domain }) {
|
||||
pipeline.update(obj + x, at: i)
|
||||
} else {
|
||||
var y = x
|
||||
y.options = DomainFilter[x.domain]
|
||||
pipeline.addNew(y)
|
||||
}
|
||||
}
|
||||
cellAnimationsCommit()
|
||||
}
|
||||
}
|
||||
|
||||
func syncUpdate(_ sender: SyncUpdate, remove rows: SQLiteRowRange, affects: SyncUpdateEnd) {
|
||||
if affects == .Latest {
|
||||
// TODO: alternatively query last modified from db (last entry _before_ range)
|
||||
syncUpdate(sender, reset: sender.rows)
|
||||
return
|
||||
}
|
||||
guard let outdated = AppDB?.dnsLogsGrouped(range: rows, parentDomain: parent),
|
||||
outdated.count > 0 else {
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.sync {
|
||||
cellAnimationsGroup(if: outdated.count > 14)
|
||||
var listOfDeletes: [Int] = []
|
||||
for x in outdated {
|
||||
guard let (i, obj) = pipeline.dataSourceGet(where: { $0.domain == x.domain }) else {
|
||||
assertionFailure("Try to remove non-existent element")
|
||||
continue // should never happen
|
||||
}
|
||||
if obj.total > x.total {
|
||||
pipeline.update(obj - x, at: i)
|
||||
} else {
|
||||
listOfDeletes.append(i)
|
||||
}
|
||||
}
|
||||
pipeline.remove(indices: listOfDeletes.sorted())
|
||||
cellAnimationsCommit()
|
||||
}
|
||||
}
|
||||
|
||||
func syncUpdate(_ sender: SyncUpdate, partialRemove affectedFQDN: String) {
|
||||
let affectedParent = affectedFQDN.extractDomain()
|
||||
guard parent == nil || parent == affectedParent else {
|
||||
return // does not affect current table
|
||||
}
|
||||
let affected = (parent == nil ? affectedParent : affectedFQDN)
|
||||
let updated = AppDB?.dnsLogsGrouped(range: sender.rows, matchingDomain: affected, parentDomain: parent)?.first
|
||||
DispatchQueue.main.sync {
|
||||
guard let old = pipeline.dataSourceGet(where: { $0.domain == affected }) else {
|
||||
// can only happen if delete sheet is open while background sync removed the element
|
||||
return
|
||||
}
|
||||
if var updated = updated {
|
||||
assert(old.object.domain == updated.domain)
|
||||
updated.options = DomainFilter[updated.domain]
|
||||
pipeline.update(updated, at: old.index)
|
||||
} else {
|
||||
pipeline.remove(indices: [old.index])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// #################################
|
||||
// #
|
||||
// # MARK: - Cell Animations
|
||||
// #
|
||||
// #################################
|
||||
|
||||
extension GroupedDomainDataSource {
|
||||
/// Sets `pipeline.delegate = nil` to disable individual cell animations (update, insert, delete & move).
|
||||
private func cellAnimationsGroup(if condition: Bool = true) {
|
||||
if condition || delegate?.tableView.isFrontmost == false {
|
||||
pipeline.delegate = nil
|
||||
}
|
||||
}
|
||||
/// No-Op if cell animations are enabled already.
|
||||
/// Else, set `pipeline.delegate = self` and perform `reloadData()`.
|
||||
private func cellAnimationsCommit() {
|
||||
if pipeline.delegate == nil {
|
||||
pipeline.delegate = self
|
||||
delegate?.tableView.reloadData()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Collect animations and post them in a single animations block.
|
||||
// This will require enormous work to translate them into a final set.
|
||||
func filterPipelineDidReset() { delegate?.tableView.reloadData() }
|
||||
func filterPipeline(delete rows: [Int]) { delegate?.tableView.safeDeleteRows(rows) }
|
||||
func filterPipeline(insert row: Int) { delegate?.tableView.safeInsertRow(row, with: .left) }
|
||||
func filterPipeline(update row: Int) {
|
||||
guard let tv = delegate?.tableView else { return }
|
||||
if !tv.isEditing { tv.safeReloadRow(row) }
|
||||
else if tv.isFrontmost == true {
|
||||
delegate?.groupedDomainDataSource(needsUpdate: row)
|
||||
}
|
||||
}
|
||||
func filterPipeline(move oldRow: Int, to newRow: Int) {
|
||||
delegate?.tableView.safeMoveRow(oldRow, to: newRow)
|
||||
if delegate?.tableView.isFrontmost == true {
|
||||
delegate?.groupedDomainDataSource(needsUpdate: newRow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ##########################
|
||||
// #
|
||||
// # MARK: - Edit Row
|
||||
// #
|
||||
// ##########################
|
||||
|
||||
protocol GroupedDomainEditRow : UIViewController, EditableRows {
|
||||
var source: GroupedDomainDataSource { get }
|
||||
}
|
||||
|
||||
extension GroupedDomainEditRow {
|
||||
|
||||
func editableRowActions(_ index: IndexPath) -> [(RowAction, String)] {
|
||||
let x = source[index.row]
|
||||
if x.domain.starts(with: "#") {
|
||||
return [(.delete, "Delete")]
|
||||
}
|
||||
let b = x.options?.contains(.blocked) ?? false
|
||||
let i = x.options?.contains(.ignored) ?? false
|
||||
return [(.delete, "Delete"), (.block, b ? "Unblock" : "Block"), (.ignore, i ? "Unignore" : "Ignore")]
|
||||
}
|
||||
|
||||
func editableRowActionColor(_: IndexPath, _ action: RowAction) -> UIColor? {
|
||||
action == .block ? .systemOrange : nil
|
||||
}
|
||||
|
||||
func editableRowUserInfo(_ index: IndexPath) -> Any? { source[index.row] }
|
||||
|
||||
func editableRowCallback(_ index: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool {
|
||||
let entry = userInfo as! GroupedDomain
|
||||
switch action {
|
||||
case .ignore: showFilterSheet(entry, .ignored)
|
||||
case .block: showFilterSheet(entry, .blocked)
|
||||
case .delete:
|
||||
let name = entry.domain
|
||||
let flag = (source.parent != nil)
|
||||
AlertDeleteLogs(name, latest: entry.lastModified) {
|
||||
TheGreatDestroyer.deleteLogs(domain: name, since: $0, strict: flag)
|
||||
}.presentIn(self)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func showFilterSheet(_ entry: GroupedDomain, _ filter: FilterOptions) {
|
||||
if entry.options?.contains(filter) ?? false {
|
||||
DomainFilter.update(entry.domain, remove: filter)
|
||||
} else {
|
||||
// TODO: alert sheet
|
||||
DomainFilter.update(entry.domain, add: filter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Extensions
|
||||
extension TVCDomains : GroupedDomainEditRow {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath, tableView)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
|
||||
extension TVCHosts : GroupedDomainEditRow {
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath, tableView)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
}
|
||||
47
main/Data Source/RecordingsDB.swift
Normal file
@@ -0,0 +1,47 @@
|
||||
import Foundation
|
||||
|
||||
enum RecordingsDB {
|
||||
/// Get last started recording (where `start` is set, but `stop` is not)
|
||||
static func getCurrent() -> Recording? { AppDB?.recordingGetOngoing() }
|
||||
|
||||
/// Create new recording and set `start` timestamp to `now()`
|
||||
static func startNew() -> Recording? { try? AppDB?.recordingStartNew() }
|
||||
|
||||
/// Finalize recording by setting the `stop` timestamp to `now()`
|
||||
static func stop(_ r: inout Recording) { AppDB?.recordingStop(&r) }
|
||||
|
||||
/// Get list of all recordings
|
||||
static func list() -> [Recording] { AppDB?.recordingGetAll() ?? [] }
|
||||
|
||||
/// Copy log entries from generic `heap` table to recording specific `recLog` table
|
||||
static func persist(_ r: Recording) {
|
||||
sync.syncNow { // persist changes in cache before copying recording details
|
||||
AppDB?.recordingLogsPersist(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get list of domains that occured during the recording
|
||||
static func details(_ r: Recording) -> [RecordLog] {
|
||||
AppDB?.recordingLogsGetGrouped(r) ?? []
|
||||
}
|
||||
|
||||
/// Update `title`, `appid`, and `notes` and post `NotifyRecordingChanged` notification.
|
||||
static func update(_ r: Recording) {
|
||||
AppDB?.recordingUpdate(r)
|
||||
NotifyRecordingChanged.post((r, false))
|
||||
}
|
||||
|
||||
/// Delete whole recording including all entries and post `NotifyRecordingChanged` notification.
|
||||
static func delete(_ r: Recording) {
|
||||
if (try? AppDB?.recordingDelete(r)) == true {
|
||||
NotifyRecordingChanged.post((r, true))
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete individual entries from recording while keeping the recording alive.
|
||||
/// - Returns: `true` if at least one row is deleted.
|
||||
static func deleteDetails(_ r: Recording, domain: String) -> Bool {
|
||||
((try? AppDB?.recordingLogsDelete(r.id, matchingDomain: domain)) ?? 0) > 0
|
||||
}
|
||||
}
|
||||
|
||||
279
main/Data Source/SyncUpdate.swift
Normal file
@@ -0,0 +1,279 @@
|
||||
import UIKit
|
||||
|
||||
class SyncUpdate {
|
||||
private var lastSync: TimeInterval = 0
|
||||
private var timer: Timer!
|
||||
private var paused: Int = 1 // first start() will decrement
|
||||
|
||||
private var filterType: DateFilterKind
|
||||
private var range: SQLiteRowRange? // written in reloadRangeFromDB()
|
||||
/// `tsEarliest ?? 0`
|
||||
private var tsMin: Timestamp { tsEarliest ?? 0 }
|
||||
/// `(tsLatest + 1) ?? 0`
|
||||
private var tsMax: Timestamp { (tsLatest ?? -1) + 1 }
|
||||
|
||||
/// Returns invalid range `(-1,-1)` if collection contains no rows
|
||||
var rows: SQLiteRowRange { get { range ?? (-1,-1) } }
|
||||
private(set) var tsEarliest: Timestamp? // as set per user, not actual earliest
|
||||
private(set) var tsLatest: Timestamp? // as set per user, not actual latest
|
||||
|
||||
|
||||
init(periodic interval: TimeInterval) {
|
||||
(filterType, tsEarliest, tsLatest) = Pref.DateFilter.restrictions()
|
||||
reloadRangeFromDB()
|
||||
|
||||
NotifyDateFilterChanged.observe(call: #selector(didChangeDateFilter), on: self)
|
||||
timer = Timer.repeating(interval, call: #selector(periodicUpdate), on: self)
|
||||
syncNow() // because timer will only fire after interval
|
||||
}
|
||||
|
||||
/// Callback fired every `7` seconds.
|
||||
@objc private func periodicUpdate() { if paused == 0 { syncNow() } }
|
||||
|
||||
/// Callback fired when user changes `DateFilter` on root tableView controller
|
||||
@objc private func didChangeDateFilter() {
|
||||
self.pause()
|
||||
let filter = Pref.DateFilter.restrictions()
|
||||
filterType = filter.type
|
||||
DispatchQueue.global().async {
|
||||
// Not necessary, but improve execution order (delete then insert).
|
||||
if self.tsMin <= (filter.earliest ?? 0) {
|
||||
self.set(newEarliest: filter.earliest)
|
||||
self.set(newLatest: filter.latest)
|
||||
} else {
|
||||
self.set(newLatest: filter.latest)
|
||||
self.set(newEarliest: filter.earliest)
|
||||
}
|
||||
self.continue()
|
||||
}
|
||||
}
|
||||
|
||||
/// - Warning: Always call from a background thread!
|
||||
func needsReloadDB(domain: String? = nil) {
|
||||
assert(!Thread.isMainThread)
|
||||
reloadRangeFromDB()
|
||||
if let dom = domain {
|
||||
notifyObservers { $0.syncUpdate(self, partialRemove: dom) }
|
||||
} else {
|
||||
notifyObservers { $0.syncUpdate(self, reset: rows) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Sync Now
|
||||
|
||||
/// This will immediately resume timer updates, ignoring previous `pause()` requests.
|
||||
func start() { paused = 0 }
|
||||
|
||||
/// All calls must be balanced with `continue()` calls.
|
||||
/// Can be nested within other `pause-continue` pairs.
|
||||
/// - Warning: An execution branch that results in unbalanced pairs will completely disable updates!
|
||||
func pause() { paused += 1 }
|
||||
|
||||
/// Must be balanced with a `pause()` call. A `continue()` without a `pause()` is a `nop`.
|
||||
/// - Note: Internally the sync timer keeps running. The `pause` will simply ignore execution during that time.
|
||||
func `continue`() { if paused > 0 { paused -= 1 } }
|
||||
|
||||
/// Persist logs from cache and notify all observers. (`NotifySyncInsert`)
|
||||
/// Determine rows of outdated entries that should be removed and notify observers as well. (`NotifySyncRemove`)
|
||||
/// - Note: This method is rate limited. Sync will be performed at most once per second.
|
||||
/// - Note: This method returns immediatelly. Syncing is done in a background thread.
|
||||
/// - Parameter block: **Always** called on a background thread!
|
||||
func syncNow(whenDone block: (() -> Void)? = nil) {
|
||||
let now = Date().timeIntervalSince1970
|
||||
guard (now - lastSync) > 1 else { // rate limiting
|
||||
if let b = block { DispatchQueue.global().async { b() } }
|
||||
return
|
||||
}
|
||||
lastSync = now
|
||||
self.pause() // reduce concurrent load
|
||||
DispatchQueue.global().async {
|
||||
self.internalSync()
|
||||
block?()
|
||||
self.continue()
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by `syncNow()`. Split to a separate func to reduce `self.` cluttering
|
||||
private func internalSync() {
|
||||
assert(!Thread.isMainThread)
|
||||
// Always persist logs ...
|
||||
if let newest = AppDB?.dnsLogsPersist() { // move cache -> heap
|
||||
if filterType == .ABRange {
|
||||
// ... even if we filter a few later
|
||||
if let r = rows(tsMin, tsMax, scope: newest) {
|
||||
notify(insert: r, .Latest)
|
||||
}
|
||||
} else {
|
||||
notify(insert: newest, .Latest)
|
||||
}
|
||||
}
|
||||
if filterType == .LastXMin {
|
||||
set(newEarliest: Timestamp.past(minutes: Pref.DateFilter.LastXMin))
|
||||
}
|
||||
// TODO: periodic hard delete old logs (will reset rowids!)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
private func rows(_ ts1: Timestamp, _ ts2: Timestamp, scope: SQLiteRowRange = (0,0)) -> SQLiteRowRange? {
|
||||
AppDB?.dnsLogsRowRange(between: ts1, and: ts2, within: scope)
|
||||
}
|
||||
|
||||
private func reloadRangeFromDB() {
|
||||
// `nil` is not SQLiteRowRange(0,0) aka. full collection.
|
||||
// `nil` means invalid range. e.g. ts restriction too high or empty db.
|
||||
range = rows(tsMin, tsMax)
|
||||
}
|
||||
|
||||
/// Update internal `tsEarliest`, then post `NotifySyncInsert` or `NotifySyncRemove` notification with row ids.
|
||||
/// - Warning: Always call from a background thread!
|
||||
private func set(newEarliest: Timestamp?) {
|
||||
func from(_ t: Timestamp?) -> Timestamp { t ?? 0 }
|
||||
func to(_ t: Timestamp) -> Timestamp { tsLatest == nil ? t : min(t, tsMax) }
|
||||
|
||||
if let (old, new) = tsEarliest <-/ newEarliest {
|
||||
if old != nil, (new == nil || new! < old!) {
|
||||
if let r = rows(from(new), to(old!), scope: (0, range?.start ?? 0)) {
|
||||
notify(insert: r, .Earliest)
|
||||
}
|
||||
} else if range != nil {
|
||||
if let r = rows(from(old), to(new!), scope: range!) {
|
||||
notify(remove: r, .Earliest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Update internal `tsLatest`, then post `NotifySyncInsert` or `NotifySyncRemove` notification with row ids.
|
||||
/// - Warning: Always call from a background thread!
|
||||
private func set(newLatest: Timestamp?) {
|
||||
func from(_ t: Timestamp) -> Timestamp { max(t + 1, tsMin) }
|
||||
func to(_ t: Timestamp?) -> Timestamp { t == nil ? 0 : t! + 1 }
|
||||
// +1: include upper end because `dnsLogsRowRange` selects `ts < X`
|
||||
|
||||
if let (old, new) = tsLatest <-/ newLatest {
|
||||
if old != nil, (new == nil || old! < new!) {
|
||||
if let r = rows(from(old!), to(new), scope: (range?.end ?? 0, 0)) {
|
||||
notify(insert: r, .Latest)
|
||||
}
|
||||
} else if range != nil {
|
||||
if let r = rows(from(new!), to(old), scope: range!) {
|
||||
notify(remove: r, .Latest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// - Warning: Always call from a background thread!
|
||||
private func notify(insert r: SQLiteRowRange, _ end: SyncUpdateEnd) {
|
||||
if range == nil { range = r }
|
||||
else {
|
||||
switch end {
|
||||
case .Earliest: range!.start = r.start
|
||||
case .Latest: range!.end = r.end
|
||||
}
|
||||
}
|
||||
notifyObservers { $0.syncUpdate(self, insert: r, affects: end) }
|
||||
}
|
||||
|
||||
/// - Warning: `range` must not be `nil`!
|
||||
/// - Warning: Always call from a background thread!
|
||||
private func notify(remove r: SQLiteRowRange, _ end: SyncUpdateEnd) {
|
||||
switch end {
|
||||
case .Earliest: range!.start = r.end + 1
|
||||
case .Latest: range!.end = r.start - 1
|
||||
}
|
||||
if range!.start > range!.end { range = nil }
|
||||
notifyObservers { $0.syncUpdate(self, remove: r, affects: end) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Observer List
|
||||
|
||||
private var observers: [WeakObserver] = []
|
||||
|
||||
/// Add `delegate` to observer list and immediatelly call `syncUpdate(reset:)` (on background thread).
|
||||
func addObserver(_ delegate: SyncUpdateDelegate) {
|
||||
observers.removeAll { $0.target == nil }
|
||||
observers.append(.init(target: delegate))
|
||||
DispatchQueue.global().async {
|
||||
delegate.syncUpdate(self, reset: self.rows)
|
||||
}
|
||||
}
|
||||
|
||||
/// - Warning: Always call from a background thread!
|
||||
private func notifyObservers(_ block: (SyncUpdateDelegate) -> Void) {
|
||||
assert(!Thread.isMainThread)
|
||||
self.pause()
|
||||
for o in observers where o.target != nil { block(o.target!) }
|
||||
self.continue()
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper class for `SyncUpdateDelegate` that supports weak references
|
||||
private struct WeakObserver {
|
||||
weak var target: SyncUpdateDelegate?
|
||||
weak var pullToRefresh: UIRefreshControl?
|
||||
}
|
||||
|
||||
enum SyncUpdateEnd { case Earliest, Latest }
|
||||
|
||||
protocol SyncUpdateDelegate : AnyObject {
|
||||
/// `SyncUpdate` has unpredictable changes. Reload your `dataSource`.
|
||||
/// - Warning: This function will **always** be called from a background thread.
|
||||
func syncUpdate(_ sender: SyncUpdate, reset rows: SQLiteRowRange)
|
||||
|
||||
/// `SyncUpdate` added new `rows` to database. Sync changes to your `dataSource`.
|
||||
/// - Warning: This function will **always** be called from a background thread.
|
||||
func syncUpdate(_ sender: SyncUpdate, insert rows: SQLiteRowRange, affects: SyncUpdateEnd)
|
||||
|
||||
/// `SyncUpdate` outdated some `rows` in database. Sync changes to your `dataSource`.
|
||||
/// - Warning: This function will **always** be called from a background thread.
|
||||
func syncUpdate(_ sender: SyncUpdate, remove rows: SQLiteRowRange, affects: SyncUpdateEnd)
|
||||
|
||||
/// Background process did delete some entries in database that match `affectedDomain`.
|
||||
/// Update or remove entries from your `dataSource`.
|
||||
/// - Warning: This function will **always** be called from a background thread.
|
||||
func syncUpdate(_ sender: SyncUpdate, partialRemove affectedDomain: String)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Pull-To-Refresh
|
||||
|
||||
@available(iOS 10.0, *)
|
||||
extension SyncUpdate {
|
||||
|
||||
/// Add Pull-To-Refresh control to `tableViewController`. On action notify `observer.syncUpdate(reset:)`
|
||||
/// - Warning: Must be called after `addObserver()` such that `observer` exists in list of observers.
|
||||
func allowPullToRefresh(onTVC tableViewController: UITableViewController?, forObserver: SyncUpdateDelegate) {
|
||||
guard let i = observers.firstIndex(where: { $0.target === forObserver }) else {
|
||||
assertionFailure("You must add the observer before enabling Pull-To-Refresh!")
|
||||
return
|
||||
}
|
||||
// remove previous
|
||||
observers[i].pullToRefresh?.removeTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
|
||||
observers[i].pullToRefresh = nil
|
||||
if let tvc = tableViewController {
|
||||
let rc = UIRefreshControl()
|
||||
rc.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
|
||||
tvc.tableView.refreshControl = rc
|
||||
observers[i].pullToRefresh = rc
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull-To-Refresh callback method. Find observer with corresponding `RefreshControl` and notify `syncUpdate(reset:)`
|
||||
@objc private func pullToRefresh(sender: UIRefreshControl) {
|
||||
guard let x = observers.first(where: { $0.pullToRefresh === sender }) else {
|
||||
assertionFailure("Should never happen. RefreshControl removed from table view while keeping it active somewhere else.")
|
||||
return
|
||||
}
|
||||
syncNow {
|
||||
x.target?.syncUpdate(self, reset: self.rows)
|
||||
DispatchQueue.main.sync {
|
||||
sender.endRefreshing()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
main/Data Source/TestDataSource.swift
Normal file
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
|
||||
#if IOS_SIMULATOR
|
||||
|
||||
class TestDataSource {
|
||||
|
||||
static func load() {
|
||||
QLog.Debug("SQLite path: \(URL.internalDB())")
|
||||
|
||||
let db = AppDB!
|
||||
let deleted = db.dnsLogsDelete("test.com", strict: false)
|
||||
try? db.run(sql: "DELETE FROM cache;")
|
||||
QLog.Debug("Deleting \(deleted) rows matching 'test.com' (+ \(db.numberOfChanges) in cache)")
|
||||
|
||||
QLog.Debug("Writing 33 test logs")
|
||||
try? db.logWrite("keeptest.com", blocked: false)
|
||||
for _ in 1...4 { try? db.logWrite("test.com", blocked: false) }
|
||||
for _ in 1...7 { try? db.logWrite("i.test.com", blocked: false) }
|
||||
for i in 1...8 { try? db.logWrite("b.test.com", blocked: i>5) }
|
||||
for i in 1...13 { try? db.logWrite("bi.test.com", blocked: i%2==0) }
|
||||
|
||||
db.dnsLogsPersist()
|
||||
|
||||
QLog.Debug("Creating 4 filters")
|
||||
db.setFilter("b.test.com", .blocked)
|
||||
db.setFilter("i.test.com", .ignored)
|
||||
db.setFilter("bi.test.com", [.blocked, .ignored])
|
||||
|
||||
QLog.Debug("Done")
|
||||
|
||||
Timer.repeating(2, call: #selector(insertRandom), on: self)
|
||||
}
|
||||
|
||||
@objc static func insertRandom() {
|
||||
//QLog.Debug("Inserting 1 periodic log entry")
|
||||
try? AppDB?.logWrite("\(arc4random() % 5).count.test.com", blocked: true)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,8 +1,8 @@
|
||||
import UIKit
|
||||
|
||||
extension UIAlertController {
|
||||
func presentIn(_ viewController: UIViewController?) {
|
||||
viewController?.present(self, animated: true, completion: nil)
|
||||
func presentIn(_ viewController: UIViewController) {
|
||||
viewController.present(self, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func AskAlert(title: String?, text: String?, buttonText: String = "Continue", bu
|
||||
/// - buttons: Default: `[]`
|
||||
/// - lastIsDestructive: Default: `false`
|
||||
/// - cancelButtonText: Default: `"Dismiss"`
|
||||
func BottomAlert(title: String?, text: String?, buttons: [String] = [], lastIsDestructive: Bool = false, cancelButtonText: String = "Dismiss", callback: @escaping (_ index: Int?) -> Void) -> UIAlertController {
|
||||
func BottomAlert(title: String?, text: String?, buttons: [String] = [], lastIsDestructive: Bool = false, cancelButtonText: String = "Cancel", callback: @escaping (_ index: Int?) -> Void) -> UIAlertController {
|
||||
let alert = UIAlertController(title: title, message: text, preferredStyle: .actionSheet)
|
||||
for (i, btn) in buttons.enumerated() {
|
||||
let dangerous = (lastIsDestructive && i + 1 == buttons.count)
|
||||
@@ -54,21 +54,13 @@ func BottomAlert(title: String?, text: String?, buttons: [String] = [], lastIsDe
|
||||
}
|
||||
|
||||
func AlertDeleteLogs(_ domain: String, latest: Timestamp, success: @escaping (_ tsMin: Timestamp) -> Void) -> UIAlertController {
|
||||
let sinceNow = Timestamp.now() - latest
|
||||
var buttons = ["Last 5 minutes", "Last 15 minutes", "Last hour", "Last 24 hours", "Delete everything"]
|
||||
var times: [Timestamp] = [300, 900, 3600, 86400]
|
||||
while times.count > 0, times[0] < sinceNow {
|
||||
buttons.removeFirst()
|
||||
times.removeFirst()
|
||||
}
|
||||
return BottomAlert(title: "Delete logs", text: "Delete logs for domain '\(domain)'", buttons: buttons, lastIsDestructive: true, cancelButtonText: "Cancel") {
|
||||
guard let idx = $0 else {
|
||||
return
|
||||
}
|
||||
if idx >= times.count {
|
||||
success(0)
|
||||
} else {
|
||||
success(Timestamp(Date().timeIntervalSince1970) - times[idx])
|
||||
let minutesPassed = (Timestamp.now() - latest) / 60
|
||||
let times: [Int] = [5, 15, 60, 1440].compactMap { minutesPassed < $0 ? $0 : nil }
|
||||
let fmt = TimeFormat(.full, allowed: [.hour, .minute])
|
||||
let labels = times.map { "Last " + (fmt.from(minutes: $0) ?? "?") }
|
||||
return BottomAlert(title: "Delete logs", text: "Delete logs for domain '\(domain)'", buttons: labels + ["Delete everything"], lastIsDestructive: true) {
|
||||
if let i = $0 {
|
||||
success(i < times.count ? Timestamp.past(minutes: times[i]) : 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
88
main/Extensions/Array.swift
Normal file
@@ -0,0 +1,88 @@
|
||||
import Foundation
|
||||
|
||||
//extension Collection {
|
||||
// subscript(ifExist i: Index?) -> Iterator.Element? {
|
||||
// guard let i = i else { return nil }
|
||||
// return indices.contains(i) ? self[i] : nil
|
||||
// }
|
||||
//}
|
||||
|
||||
extension Range where Bound == Int {
|
||||
@inline(__always) func arr() -> [Bound] { self.map { $0 } }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Sorted Array
|
||||
|
||||
extension Array {
|
||||
typealias CompareFn = (Element, Element) -> Bool
|
||||
|
||||
/// Binary tree search operation.
|
||||
/// - Warning: Array must be sorted already.
|
||||
/// - Parameters:
|
||||
/// - mustExist: Determine whether to return low index or `nil` if element is missing.
|
||||
/// - first: If `true`, keep searching for first matching element.
|
||||
/// - Returns: Index or `nil` (only if `mustExist = true` and element does not exist).
|
||||
/// - Complexity: O(log *n*), where *n* is the length of the array.
|
||||
func binTreeIndex(of element: Element, compare fn: CompareFn, mustExist: Bool = false, findFirst: Bool = false) -> Int? {
|
||||
var found = false
|
||||
var lo = 0, hi = self.count - 1
|
||||
while lo <= hi {
|
||||
let mid = (lo + hi)/2
|
||||
if fn(self[mid], element) {
|
||||
lo = mid + 1
|
||||
} else if fn(element, self[mid]) {
|
||||
hi = mid - 1
|
||||
} else {
|
||||
if !findFirst { return mid } // exit early if we dont care about first index
|
||||
hi = mid - 1
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return (mustExist && !found) ? nil : lo // not found, would be inserted at position lo
|
||||
}
|
||||
|
||||
/// Binary tree lookup whether element exists. Performs `binTreeIndex(of:compare:mustExist:)` internally.
|
||||
func binTreeExists(_ element: Element, compare fn: CompareFn) -> Bool {
|
||||
binTreeIndex(of: element, compare: fn, mustExist: true) != nil
|
||||
}
|
||||
|
||||
/// Binary tree insert operation
|
||||
/// - Warning: Array must be sorted already.
|
||||
/// - Returns: Index at which `elem` was inserted
|
||||
/// - Complexity: O(log *n*), where *n* is the length of the array.
|
||||
@discardableResult mutating func binTreeInsert(_ elem: Element, compare fn: CompareFn) -> Int {
|
||||
let newIndex = binTreeIndex(of: elem, compare: fn)!
|
||||
insert(elem, at: newIndex)
|
||||
return newIndex
|
||||
}
|
||||
|
||||
/// Binary tree remove operation
|
||||
/// - Warning: Array must be sorted already.
|
||||
/// - Returns: Index of removed `elem` or `nil` if it does not exist
|
||||
/// - Complexity: O(log *n*), where *n* is the length of the array.
|
||||
@discardableResult mutating func binTreeRemove(_ elem: Element, compare fn: CompareFn) -> Int? {
|
||||
if let i = binTreeIndex(of: elem, compare: fn, mustExist: true) {
|
||||
remove(at: i)
|
||||
return i
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Sorted synchronous comparison between elements
|
||||
/// - Parameter sortedSubset: Must be a strict subset of the sorted array.
|
||||
/// - Returns: List of elements that are **not** present in `sortedSubset`.
|
||||
/// - Complexity: O(*m*+*n*), where *n* is the length of the array and *m* the length of the `sortedSubset`.
|
||||
/// If indices are found earlier, *n* may be significantly less (on average: `n/2`)
|
||||
func difference(toSubset sortedSubset: [Element], compare fn: CompareFn) -> [Element] {
|
||||
var result: [Element] = []
|
||||
var iter = makeIterator()
|
||||
for rhs in sortedSubset {
|
||||
while let lhs = iter.next(), fn(lhs, rhs) {
|
||||
result.append(lhs)
|
||||
}
|
||||
}
|
||||
result.append(contentsOf: iter)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ extension UIView {
|
||||
private static let inverseItem: [NSLayoutConstraint.Attribute] = [.right, .bottom, .trailing, .lastBaseline, .rightMargin, .bottomMargin, .trailingMargin]
|
||||
|
||||
/// Create and active constraints for provided edges. Constraints will anchor the same edge on both `self` and `other`.
|
||||
/// - Note: Will set `translatesAutoresizingMaskIntoConstraints = false`
|
||||
/// - Parameters:
|
||||
/// - edges: List of constraint attributes, e.g. `[.top, .bottom, .left, .right]`
|
||||
/// - other: Instance to bind to, e.g. `UIView` or `UILayoutGuide`
|
||||
@@ -66,7 +67,8 @@ extension UIView {
|
||||
/// - rel: Constraint relation. (Default: `.equal`)
|
||||
/// - Returns: List of created and active constraints
|
||||
@discardableResult func anchor(_ edges: [NSLayoutConstraint.Attribute], to other: Any, margin: CGFloat = 0, if rel: NSLayoutConstraint.Relation = .equal) -> [NSLayoutConstraint] {
|
||||
edges.map {
|
||||
translatesAutoresizingMaskIntoConstraints = false
|
||||
return edges.map {
|
||||
let (A, B) = UIView.inverseItem.contains($0) ? (other, self) : (self, other)
|
||||
return NSLayoutConstraint(item: A, attribute: $0, relatedBy: rel, toItem: B, attribute: $0, multiplier: 1, constant: margin).on()
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
extension GroupedDomain {
|
||||
static func +(a: GroupedDomain, b: GroupedDomain) -> Self {
|
||||
GroupedDomain(domain: a.domain, total: a.total + b.total, blocked: a.blocked + b.blocked,
|
||||
lastModified: max(a.lastModified, b.lastModified), options: a.options ?? b.options )
|
||||
}
|
||||
}
|
||||
|
||||
extension Array where Element == GroupedDomain {
|
||||
func merge(_ domain: String, options opt: FilterOptions? = nil) -> GroupedDomain {
|
||||
var b: Int32 = 0, t: Int32 = 0, m: Timestamp = 0
|
||||
for x in self {
|
||||
b += x.blocked
|
||||
t += x.total
|
||||
m = Swift.max(m, x.lastModified)
|
||||
}
|
||||
return GroupedDomain(domain: domain, total: t, blocked: b, lastModified: m, options: opt)
|
||||
}
|
||||
}
|
||||
|
||||
extension Recording {
|
||||
var fallbackTitle: String { get { "Unnamed Recording #\(id)" } }
|
||||
var duration: Timestamp? { get { stop == nil ? nil : stop! - start } }
|
||||
var durationString: String? { get { stop == nil ? nil : TimeFormat.from(duration!) } }
|
||||
}
|
||||
|
||||
extension Timestamp {
|
||||
func asDateTime() -> String { dateTimeFormat.string(from: self) }
|
||||
func toDate() -> Date { Date(timeIntervalSince1970: Double(self)) }
|
||||
static func now() -> Timestamp { Timestamp(Date().timeIntervalSince1970) }
|
||||
}
|
||||
51
main/Extensions/Font.swift
Normal file
@@ -0,0 +1,51 @@
|
||||
import UIKit
|
||||
|
||||
extension UIFont {
|
||||
func withTraits(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
|
||||
UIFont(descriptor: fontDescriptor.withSymbolicTraits(traits)!, size: 0) // keep size as is
|
||||
}
|
||||
func bold() -> UIFont { withTraits(traits: .traitBold) }
|
||||
func italic() -> UIFont { withTraits(traits: .traitItalic) }
|
||||
func monoSpace() -> UIFont {
|
||||
let traits = fontDescriptor.object(forKey: .traits) as? [UIFontDescriptor.TraitKey: Any] ?? [:]
|
||||
let weight = (traits[.weight] as? CGFloat) ?? UIFont.Weight.regular.rawValue
|
||||
return .monospacedDigitSystemFont(ofSize: pointSize, weight: .init(rawValue: weight))
|
||||
}
|
||||
}
|
||||
|
||||
extension NSAttributedString {
|
||||
static func image(_ img: UIImage) -> Self {
|
||||
let att = NSTextAttachment()
|
||||
att.image = img
|
||||
return self.init(attachment: att)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSMutableAttributedString {
|
||||
static private var def: UIFont = .preferredFont(forTextStyle: .body)
|
||||
|
||||
func normal(_ str: String, _ style: UIFont.TextStyle = .body) -> Self { append(str, withFont: .preferredFont(forTextStyle: style)) }
|
||||
func bold(_ str: String, _ style: UIFont.TextStyle = .body) -> Self { append(str, withFont: UIFont.preferredFont(forTextStyle: style).bold()) }
|
||||
func italic(_ str: String, _ style: UIFont.TextStyle = .body) -> Self { append(str, withFont: UIFont.preferredFont(forTextStyle: style).italic()) }
|
||||
|
||||
func h1(_ str: String) -> Self { normal(str, .title1) }
|
||||
func h2(_ str: String) -> Self { normal(str, .title2) }
|
||||
func h3(_ str: String) -> Self { normal(str, .title3) }
|
||||
|
||||
private func append(_ str: String, withFont: UIFont) -> Self {
|
||||
append(NSAttributedString(string: str, attributes: [
|
||||
.font : withFont,
|
||||
.foregroundColor : UIColor.sysFg
|
||||
]))
|
||||
return self
|
||||
}
|
||||
|
||||
func centered(_ content: NSAttributedString) -> Self {
|
||||
let before = length
|
||||
append(content)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.alignment = .center
|
||||
addAttribute(.paragraphStyle, value: ps, range: .init(location: before, length: content.length))
|
||||
return self
|
||||
}
|
||||
}
|
||||
@@ -16,91 +16,6 @@ struct QLog {
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
subscript(ifExist i: Index?) -> Iterator.Element? {
|
||||
guard let i = i else { return nil }
|
||||
return indices.contains(i) ? self[i] : nil
|
||||
}
|
||||
}
|
||||
|
||||
var listOfSLDs: [String : [String : Bool]] = {
|
||||
let path = Bundle.main.url(forResource: "third-level", withExtension: "txt")
|
||||
let content = try! String(contentsOf: path!)
|
||||
var res: [String : [String : Bool]] = [:]
|
||||
content.enumerateLines { line, _ in
|
||||
let dom = line.split(separator: ".")
|
||||
let tld = String(dom.first!)
|
||||
let sld = String(dom.last!)
|
||||
if res[tld] == nil { res[tld] = [:] }
|
||||
res[tld]![sld] = true
|
||||
}
|
||||
return res
|
||||
}()
|
||||
|
||||
extension String {
|
||||
/// Check if string is equal to `domain` or ends with `.domain`
|
||||
func isSubdomain(of domain: String) -> Bool { self == domain || self.hasSuffix("." + domain) }
|
||||
/// Split string into top level domain part and host part
|
||||
func splitDomainAndHost() -> (domain: String, host: String?) {
|
||||
let lastChr = last?.asciiValue ?? 0
|
||||
guard lastChr > UInt8(ascii: "9") || lastChr < UInt8(ascii: "0") else { // IP address
|
||||
return (domain: "# IP connection", host: self)
|
||||
}
|
||||
var parts = components(separatedBy: ".")
|
||||
guard let tld = parts.popLast(), let sld = parts.popLast() else {
|
||||
return (domain: self, host: nil) // no subdomains, just plain SLD
|
||||
}
|
||||
var ending = sld + "." + tld
|
||||
if listOfSLDs[tld]?[sld] ?? false, let rld = parts.popLast() {
|
||||
ending = rld + "." + ending
|
||||
}
|
||||
return (domain: ending, host: parts.joined(separator: "."))
|
||||
}
|
||||
/// Returns `true` if String matches list of known second level domains (e.g., `co.uk`).
|
||||
func isKnownSLD() -> Bool {
|
||||
let parts = components(separatedBy: ".")
|
||||
return parts.count == 2 && listOfSLDs[parts.last!]?[parts.first!] ?? false
|
||||
}
|
||||
}
|
||||
|
||||
extension Timer {
|
||||
@discardableResult static func repeating(_ interval: TimeInterval, call selector: Selector, on target: Any, userInfo: Any? = nil) -> Timer {
|
||||
Timer.scheduledTimer(timeInterval: interval, target: target, selector: selector,
|
||||
userInfo: userInfo, repeats: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension DateFormatter {
|
||||
convenience init(withFormat: String) {
|
||||
self.init()
|
||||
dateFormat = withFormat
|
||||
}
|
||||
func with(format: String) -> Self {
|
||||
dateFormat = format
|
||||
return self
|
||||
}
|
||||
func string(from ts: Timestamp) -> String {
|
||||
string(from: Date.init(timeIntervalSince1970: Double(ts)))
|
||||
}
|
||||
}
|
||||
|
||||
struct TimeFormat {
|
||||
static func from(_ duration: Timestamp) -> String {
|
||||
String(format: "%02d:%02d", duration / 60, duration % 60)
|
||||
}
|
||||
static func from(_ duration: TimeInterval, millis: Bool = false) -> String {
|
||||
let t = Int(duration)
|
||||
if millis {
|
||||
let mil = Int(duration * 1000) % 1000
|
||||
return String(format: "%02d:%02d.%03d", t / 60, t % 60, mil)
|
||||
}
|
||||
return String(format: "%02d:%02d", t / 60, t % 60)
|
||||
}
|
||||
static func since(_ date: Date, millis: Bool = false) -> String {
|
||||
from(Date().timeIntervalSince(date), millis: millis)
|
||||
}
|
||||
}
|
||||
|
||||
extension UIColor {
|
||||
static var sysBg: UIColor { get { if #available(iOS 13.0, *) { return .systemBackground } else { return .white } }}
|
||||
static var sysFg: UIColor { get { if #available(iOS 13.0, *) { return .label } else { return .black } }}
|
||||
@@ -111,3 +26,35 @@ extension UIEdgeInsets {
|
||||
self.init(top: top ?? all, left: left ?? all, bottom: bottom ?? all, right: right ?? all)
|
||||
}
|
||||
}
|
||||
|
||||
precedencegroup CompareAssignPrecedence {
|
||||
assignment: true
|
||||
associativity: left
|
||||
higherThan: ComparisonPrecedence
|
||||
}
|
||||
|
||||
infix operator <-? : CompareAssignPrecedence
|
||||
infix operator <-/ : CompareAssignPrecedence
|
||||
extension Equatable {
|
||||
/// Assign a new value to `lhs` if `newValue` differs from the previous value. Return `false` if they are equal.
|
||||
/// - Returns: `true` if `lhs` was overwritten with another value
|
||||
static func <-?(lhs: inout Self, newValue: Self) -> Bool {
|
||||
if lhs != newValue {
|
||||
lhs = newValue
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Assign a new value to `lhs` if `newValue` differs from the previous value.
|
||||
/// Return tuple with both values. Or `nil` if they are equal.
|
||||
/// - Returns: `nil` if `previousValue == newValue`
|
||||
static func <-/(lhs: inout Self, newValue: Self) -> (previousValue: Self, newValue: Self)? {
|
||||
let previousValue = lhs
|
||||
if previousValue != newValue {
|
||||
lhs = newValue
|
||||
return (previousValue, newValue)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
let NotifyVPNStateChanged = NSNotification.Name("GlassVPNStateChanged") // VPNState!
|
||||
let NotifyFilterChanged = NSNotification.Name("PSIFilterSettingsChanged") // nil!
|
||||
let NotifyLogHistoryReset = NSNotification.Name("PSILogHistoryReset") // nil!
|
||||
let NotifyDNSFilterChanged = NSNotification.Name("PSIDNSFilterSettingsChanged") // domain: String!
|
||||
let NotifyDateFilterChanged = NSNotification.Name("PSIDateFilterSettingsChanged") // nil!
|
||||
let NotifySortOrderChanged = NSNotification.Name("PSIDateFilterSortOrderChanged") // nil!
|
||||
let NotifyRecordingChanged = NSNotification.Name("PSIRecordingChanged") // (Recording, deleted: Bool)!
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,84 @@
|
||||
import Foundation
|
||||
|
||||
let dateTimeFormat = DateFormatter(withFormat: "yyyy-MM-dd HH:mm:ss")
|
||||
var currentVPNState: VPNState = .off
|
||||
let sync = SyncUpdate(periodic: 7)
|
||||
|
||||
public enum VPNState : Int {
|
||||
case on = 1, inbetween, off
|
||||
}
|
||||
|
||||
enum Pref {
|
||||
static func Int(_ key: String) -> Int { UserDefaults.standard.integer(forKey: key) }
|
||||
static func Int(_ val: Int, _ key: String) { UserDefaults.standard.set(val, forKey: key) }
|
||||
static func Bool(_ key: String) -> Bool { UserDefaults.standard.bool(forKey: key) }
|
||||
static func Bool(_ val: Bool, _ key: String) { UserDefaults.standard.set(val, forKey: key) }
|
||||
static func `Any`(_ key: String) -> Any? { UserDefaults.standard.object(forKey: key) }
|
||||
static func `Any`(_ val: Any?, _ key: String) { UserDefaults.standard.set(val, forKey: key) }
|
||||
|
||||
enum DidShowTutorial {
|
||||
static var Welcome: Bool {
|
||||
get { Pref.Bool("didShowTutorialAppWelcome") }
|
||||
set { Pref.Bool(newValue, "didShowTutorialAppWelcome") }
|
||||
}
|
||||
static var Recordings: Bool {
|
||||
get { Pref.Bool("didShowTutorialRecordings") }
|
||||
set { Pref.Bool(newValue, "didShowTutorialRecordings") }
|
||||
}
|
||||
}
|
||||
enum ContextAnalyis {
|
||||
static var CoOccurrenceTime: Int? {
|
||||
get { Pref.Any("contextAnalyisCoOccurrenceTime") as? Int }
|
||||
set { Pref.Any(newValue, "contextAnalyisCoOccurrenceTime") }
|
||||
}
|
||||
}
|
||||
enum DateFilter {
|
||||
static var Kind: DateFilterKind {
|
||||
get { DateFilterKind(rawValue: Pref.Int("dateFilterType"))! }
|
||||
set { Pref.Int(newValue.rawValue, "dateFilterType") }
|
||||
}
|
||||
/// Default: `0` (disabled)
|
||||
static var LastXMin: Int {
|
||||
get { Pref.Int("dateFilterLastXMin") }
|
||||
set { Pref.Int(newValue, "dateFilterLastXMin") }
|
||||
}
|
||||
/// Default: `nil` (disabled)
|
||||
static var RangeA: Timestamp? {
|
||||
get { Pref.Any("dateFilterRangeA") as? Timestamp }
|
||||
set { Pref.Any(newValue, "dateFilterRangeA") }
|
||||
}
|
||||
/// Default: `nil` (disabled)
|
||||
static var RangeB: Timestamp? {
|
||||
get { Pref.Any("dateFilterRangeB") as? Timestamp }
|
||||
set { Pref.Any(newValue, "dateFilterRangeB") }
|
||||
}
|
||||
/// default: `.Date`
|
||||
static var OrderBy: DateFilterOrderBy {
|
||||
get { DateFilterOrderBy(rawValue: Pref.Int("dateFilterOderType"))! }
|
||||
set { Pref.Int(newValue.rawValue, "dateFilterOderType") }
|
||||
}
|
||||
/// default: `false` (Desc)
|
||||
static var OrderAsc: Bool {
|
||||
get { Pref.Bool("dateFilterOderAsc") }
|
||||
set { Pref.Bool(newValue, "dateFilterOderAsc") }
|
||||
}
|
||||
|
||||
/// - Returns: Timestamp restriction depending on current selected date filter.
|
||||
/// - `Off` : `(nil, nil)`
|
||||
/// - `LastXMin` : `(now-LastXMin, nil)`
|
||||
/// - `ABRange` : `(RangeA, RangeB)`
|
||||
static func restrictions() -> (type: DateFilterKind, earliest: Timestamp?, latest: Timestamp?) {
|
||||
let type = Kind
|
||||
switch type {
|
||||
case .Off: return (type, nil, nil)
|
||||
case .LastXMin: return (type, Timestamp.past(minutes: Pref.DateFilter.LastXMin), nil)
|
||||
case .ABRange: return (type, Pref.DateFilter.RangeA, Pref.DateFilter.RangeB)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
enum DateFilterKind: Int {
|
||||
case Off = 0, LastXMin = 1, ABRange = 2;
|
||||
}
|
||||
enum DateFilterOrderBy: Int {
|
||||
case Date = 0, Name = 1, Count = 2;
|
||||
}
|
||||
|
||||
51
main/Extensions/String.swift
Normal file
@@ -0,0 +1,51 @@
|
||||
import UIKit
|
||||
|
||||
extension NSMutableAttributedString {
|
||||
func withColor(_ color: UIColor, fromBack: Int) -> Self {
|
||||
let l = length - fromBack
|
||||
let r = (l < 0) ? NSMakeRange(0, length) : NSMakeRange(l, fromBack)
|
||||
self.addAttribute(.foregroundColor, value: color, range: r)
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
/// Check if string is equal to `domain` or ends with `.domain`
|
||||
func isSubdomain(of domain: String) -> Bool { self == domain || self.hasSuffix("." + domain) }
|
||||
|
||||
/// Extract second or third level domain name
|
||||
func extractDomain() -> String {
|
||||
let lastChr = last?.asciiValue ?? 0
|
||||
guard lastChr > UInt8(ascii: "9") || lastChr < UInt8(ascii: "0") else { // IP address
|
||||
return "# IP"
|
||||
}
|
||||
var parts = components(separatedBy: ".")
|
||||
guard let tld = parts.popLast(), let sld = parts.popLast() else {
|
||||
return self // no subdomains, just plain SLD
|
||||
}
|
||||
if listOfSLDs[tld]?[sld] ?? false, let rld = parts.popLast() {
|
||||
return rld + "." + sld + "." + tld
|
||||
}
|
||||
return sld + "." + tld
|
||||
}
|
||||
|
||||
/// Returns `true` if String matches list of known second level domains (e.g., `co.uk`).
|
||||
func isKnownSLD() -> Bool {
|
||||
let parts = components(separatedBy: ".")
|
||||
return parts.count == 2 && listOfSLDs[parts.last!]?[parts.first!] ?? false
|
||||
}
|
||||
}
|
||||
|
||||
private var listOfSLDs: [String : [String : Bool]] = {
|
||||
let path = Bundle.main.url(forResource: "third-level", withExtension: "txt")
|
||||
let content = try! String(contentsOf: path!)
|
||||
var res: [String : [String : Bool]] = [:]
|
||||
content.enumerateLines { line, _ in
|
||||
let dom = line.split(separator: ".")
|
||||
let tld = String(dom.first!)
|
||||
let sld = String(dom.last!)
|
||||
if res[tld] == nil { res[tld] = [:] }
|
||||
res[tld]![sld] = true
|
||||
}
|
||||
return res
|
||||
}()
|
||||
@@ -1,98 +1,100 @@
|
||||
import UIKit
|
||||
|
||||
extension GroupedDomain {
|
||||
var detailCellText: String { get {
|
||||
return blocked > 0
|
||||
? "\(lastModified.asDateTime()) — \(blocked)/\(total) blocked"
|
||||
: "\(lastModified.asDateTime()) — \(total)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FilterOptions {
|
||||
func tableRowImage() -> UIImage? {
|
||||
let blocked = contains(.blocked)
|
||||
let ignored = contains(.ignored)
|
||||
if blocked { return UIImage(named: ignored ? "block_ignore" : "shield-x") }
|
||||
if ignored { return UIImage(named: "quicklook-not") }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension NSMutableAttributedString {
|
||||
func withColor(_ color: UIColor, fromBack: Int) -> Self {
|
||||
let l = length - fromBack
|
||||
let r = (l < 0) ? NSMakeRange(0, length) : NSMakeRange(l, fromBack)
|
||||
self.addAttribute(.foregroundColor, value: color, range: r)
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Pull-to-Refresh
|
||||
|
||||
extension UIRefreshControl {
|
||||
convenience init(call: Selector, on: UITableViewController) {
|
||||
self.init()
|
||||
addTarget(on, action: call, for: .valueChanged)
|
||||
addTarget(self, action: #selector(endRefreshing), for: .valueChanged)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Incremental Update Delegate
|
||||
|
||||
protocol IncrementalDataSourceUpdate : UITableViewController {
|
||||
var dataSource: [GroupedDomain] { get set }
|
||||
}
|
||||
|
||||
extension IncrementalDataSourceUpdate {
|
||||
func ifDisplayed(_ block: () -> Void) {
|
||||
DispatchQueue.main.sync {
|
||||
if self.tableView.window?.isKeyWindow ?? false {
|
||||
block()
|
||||
// TODO: custom handling if cell is being edited
|
||||
} else {
|
||||
self.tableView.reloadData()
|
||||
}
|
||||
}
|
||||
}
|
||||
func insertRow(_ obj: GroupedDomain, at index: Int) {
|
||||
dataSource.insert(obj, at: index)
|
||||
ifDisplayed {
|
||||
self.tableView.insertRows(at: [IndexPath(row: index)], with: .left)
|
||||
}
|
||||
}
|
||||
func moveRow(_ obj: GroupedDomain, from: Int, to: Int) {
|
||||
dataSource.remove(at: from)
|
||||
dataSource.insert(obj, at: to)
|
||||
ifDisplayed {
|
||||
let source = IndexPath(row: from)
|
||||
let cell = self.tableView.cellForRow(at: source)
|
||||
cell?.detailTextLabel?.text = obj.detailCellText
|
||||
self.tableView.moveRow(at: source, to: IndexPath(row: to))
|
||||
}
|
||||
}
|
||||
func replaceRow(_ obj: GroupedDomain, at index: Int) {
|
||||
dataSource[index] = obj
|
||||
ifDisplayed {
|
||||
self.tableView.reloadRows(at: [IndexPath(row: index)], with: .automatic)
|
||||
}
|
||||
}
|
||||
func deleteRow(at index: Int) {
|
||||
dataSource.remove(at: index)
|
||||
ifDisplayed {
|
||||
self.tableView.deleteRows(at: [IndexPath(row: index)], with: .automatic)
|
||||
}
|
||||
}
|
||||
func replaceData(with newData: [GroupedDomain]) {
|
||||
dataSource = newData
|
||||
ifDisplayed {
|
||||
self.tableView.reloadData()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension IndexPath {
|
||||
/// Convenience init with `section: 0`
|
||||
public init(row: Int) { self.init(row: row, section: 0) }
|
||||
}
|
||||
|
||||
extension UIRefreshControl {
|
||||
convenience init(call: Selector, on target: Any) {
|
||||
self.init()
|
||||
addTarget(target, action: call, for: .valueChanged)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableView
|
||||
|
||||
extension UITableView {
|
||||
/// Returns `true` if this `tableView` is the currently frontmost visible
|
||||
var isFrontmost: Bool { window?.isKeyWindow ?? false }
|
||||
|
||||
/// If frontmost window, perform `insertRows()`; If not, perform `reloadData()`
|
||||
func safeInsertRow(_ index: Int, with animation: UITableView.RowAnimation = .automatic) {
|
||||
isFrontmost ? insertRows(at: [IndexPath(row: index)], with: animation) : reloadData()
|
||||
}
|
||||
/// If frontmost window, perform `insertRows()`; If not, perform `reloadData()`
|
||||
func safeInsertRows(_ range: Range<Int>, with animation: UITableView.RowAnimation = .automatic) {
|
||||
isFrontmost ? insertRows(at: range.map {IndexPath(row: $0)}, with: animation) : reloadData()
|
||||
}
|
||||
/// If frontmost window, perform `deleteRows()`; If not, perform `reloadData()`
|
||||
func safeDeleteRows(_ indices: [Int], with animation: UITableView.RowAnimation = .automatic) {
|
||||
isFrontmost ? deleteRows(at: indices.map {IndexPath(row: $0)}, with: animation) : reloadData()
|
||||
}
|
||||
/// If frontmost window, perform `deleteRows()`; If not, perform `reloadData()`
|
||||
func safeDeleteRows(_ range: Range<Int>, with animation: UITableView.RowAnimation = .automatic) {
|
||||
isFrontmost ? deleteRows(at: range.map {IndexPath(row: $0)}, with: animation) : reloadData()
|
||||
}
|
||||
/// If frontmost window, perform `reloadRows()`; If not, perform `reloadData()`
|
||||
func safeReloadRow(_ index: Int, with animation: UITableView.RowAnimation = .automatic) {
|
||||
isFrontmost ? reloadRows(at: [IndexPath(row: index)], with: animation) : reloadData()
|
||||
}
|
||||
/// If frontmost window, perform `moveRow()`; If not, perform `reloadData()`
|
||||
func safeMoveRow(_ from: Int, to: Int) {
|
||||
isFrontmost ? moveRow(at: IndexPath(row: from), to: IndexPath(row: to)) : reloadData()
|
||||
}
|
||||
|
||||
/// Recalculate and apply new `tableHeaderView` height.
|
||||
func sizeHeaderToFit() {
|
||||
if let head = tableHeaderView {
|
||||
head.frame.size.height = head.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
|
||||
tableHeaderView = head
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - EditableRows
|
||||
|
||||
public enum RowAction {
|
||||
case ignore, block, delete
|
||||
}
|
||||
|
||||
protocol EditableRows {
|
||||
func editableRowUserInfo(_ index: IndexPath) -> Any?
|
||||
func editableRowActions(_ index: IndexPath) -> [(RowAction, String)]
|
||||
func editableRowActionColor(_ index: IndexPath, _ action: RowAction) -> UIColor?
|
||||
@discardableResult func editableRowCallback(_ atIndexPath: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool
|
||||
}
|
||||
|
||||
extension EditableRows where Self: UITableViewDelegate {
|
||||
func getRowActionsIOS9(_ index: IndexPath, _ table: UITableView) -> [UITableViewRowAction]? {
|
||||
let userInfo = editableRowUserInfo(index)
|
||||
return editableRowActions(index).compactMap { a,t in
|
||||
let x = UITableViewRowAction(style: a == .delete ? .destructive : .normal, title: t) {
|
||||
self.editableRowCallback($1, a, userInfo)
|
||||
table.isEditing = false
|
||||
}
|
||||
if let color = editableRowActionColor(index, a) {
|
||||
x.backgroundColor = color
|
||||
}
|
||||
return x
|
||||
}
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
func getRowActionsIOS11(_ index: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
let userInfo = editableRowUserInfo(index)
|
||||
return UISwipeActionsConfiguration(actions: editableRowActions(index).compactMap { a,t in
|
||||
let x = UIContextualAction(style: a == .delete ? .destructive : .normal, title: t) { $2(self.editableRowCallback(index, a, userInfo)) }
|
||||
x.backgroundColor = editableRowActionColor(index, a)
|
||||
return x
|
||||
})
|
||||
}
|
||||
func editableRowUserInfo(_ index: IndexPath) -> Any? { nil }
|
||||
}
|
||||
|
||||
protocol EditActionsRemove : EditableRows {}
|
||||
extension EditActionsRemove where Self: UITableViewController {
|
||||
func editableRowActions(_: IndexPath) -> [(RowAction, String)] { [(.delete, "Remove")] }
|
||||
func editableRowActionColor(_: IndexPath, _: RowAction) -> UIColor? { nil }
|
||||
}
|
||||
|
||||
90
main/Extensions/Time.swift
Normal file
@@ -0,0 +1,90 @@
|
||||
import Foundation
|
||||
|
||||
extension DateFormatter {
|
||||
convenience init(withFormat: String) {
|
||||
self.init()
|
||||
dateFormat = withFormat
|
||||
}
|
||||
}
|
||||
|
||||
extension Date {
|
||||
/// Convert `Timestamp` to `Date`
|
||||
init(_ ts: Timestamp) { self.init(timeIntervalSince1970: Double(ts)) }
|
||||
/// Convert `Date` to `Timestamp`
|
||||
var timestamp: Timestamp { get { Timestamp(self.timeIntervalSince1970) } }
|
||||
}
|
||||
|
||||
extension Timestamp {
|
||||
/// Current time as `Timestamp` (second accuracy)
|
||||
static func now() -> Timestamp { Date().timestamp }
|
||||
/// Create `Timestamp` with `now() - minutes * 60`
|
||||
static func past(minutes: Int) -> Timestamp { now() - Timestamp(minutes * 60) }
|
||||
}
|
||||
|
||||
extension Timer {
|
||||
/// Recurring timer maintains a strong reference to `target`.
|
||||
@discardableResult static func repeating(_ interval: TimeInterval, call selector: Selector, on target: Any, userInfo: Any? = nil) -> Timer {
|
||||
Timer.scheduledTimer(timeInterval: interval, target: target, selector: selector,
|
||||
userInfo: userInfo, repeats: true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DateFormat
|
||||
|
||||
enum DateFormat {
|
||||
private static let _hms = DateFormatter(withFormat: "yyyy-MM-dd HH:mm:ss")
|
||||
private static let _hm = DateFormatter(withFormat: "yyyy-MM-dd HH:mm")
|
||||
|
||||
/// Format: `yyyy-MM-dd HH:mm:ss`
|
||||
static func seconds(_ date: Date) -> String { _hms.string(from: date) }
|
||||
/// Format: `yyyy-MM-dd HH:mm:ss`
|
||||
static func seconds(_ ts: Timestamp) -> String { _hms.string(from: Date(ts)) }
|
||||
/// Format: `yyyy-MM-dd HH:mm`
|
||||
static func minutes(_ date: Date) -> String { _hm.string(from: date) }
|
||||
/// Format: `yyyy-MM-dd HH:mm`
|
||||
static func minutes(_ ts: Timestamp) -> String { _hm.string(from: Date(ts)) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - TimeFormat
|
||||
|
||||
struct TimeFormat {
|
||||
private var formatter: DateComponentsFormatter
|
||||
|
||||
/// Init new formatter with exactly 1 unit count. E.g., `61 min -> 1 hr`
|
||||
/// - Parameter allowed: Default: `[.day, .hour, .minute, .second]`
|
||||
init(_ style: DateComponentsFormatter.UnitsStyle, allowed: NSCalendar.Unit = [.day, .hour, .minute, .second]) {
|
||||
formatter = DateComponentsFormatter()
|
||||
formatter.maximumUnitCount = 1
|
||||
formatter.allowedUnits = allowed
|
||||
formatter.unitsStyle = style
|
||||
}
|
||||
|
||||
/// Formatted duration string, e.g., `20 min` or `7 days`
|
||||
func from(days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> String? {
|
||||
formatter.string(from: DateComponents(day: days, hour: hours, minute: minutes, second: seconds))
|
||||
}
|
||||
|
||||
// MARK: static
|
||||
|
||||
/// Time string with format `HH:mm`
|
||||
static func from(_ duration: Timestamp) -> String {
|
||||
String(format: "%02d:%02d", duration / 60, duration % 60)
|
||||
}
|
||||
|
||||
/// Duration string with format `HH:mm` or `HH:mm.sss`
|
||||
static func from(_ duration: TimeInterval, millis: Bool = false) -> String {
|
||||
let t = Int(duration)
|
||||
if millis {
|
||||
let mil = Int(duration * 1000) % 1000
|
||||
return String(format: "%02d:%02d.%03d", t / 60, t % 60, mil)
|
||||
}
|
||||
return String(format: "%02d:%02d", t / 60, t % 60)
|
||||
}
|
||||
|
||||
/// Duration string with format `HH:mm` or `HH:mm.sss` since reference date
|
||||
static func since(_ date: Date, millis: Bool = false) -> String {
|
||||
from(Date().timeIntervalSince(date), millis: millis)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
fileprivate extension FileManager {
|
||||
func exportDir() -> URL {
|
||||
try! url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
}
|
||||
// func exportDir() -> URL {
|
||||
// try! url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
// }
|
||||
func appGroupDir() -> URL {
|
||||
containerURL(forSecurityApplicationGroupIdentifier: "group.de.uni-bamberg.psi.AppCheck")!
|
||||
}
|
||||
@@ -13,7 +13,7 @@ fileprivate extension FileManager {
|
||||
}
|
||||
|
||||
extension URL {
|
||||
static func exportDir() -> URL { FileManager.default.exportDir() }
|
||||
// static func exportDir() -> URL { FileManager.default.exportDir() }
|
||||
static func appGroupDir() -> URL { FileManager.default.appGroupDir() }
|
||||
static func internalDB() -> URL { FileManager.default.internalDB() }
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ class TVCPreviousRecords: UITableViewController, EditActionsRemove {
|
||||
private var dataSource: [Recording] = []
|
||||
|
||||
override func viewDidLoad() {
|
||||
dataSource = DBWrp.listOfRecordings().reversed() // newest on top
|
||||
dataSource = RecordingsDB.list().reversed() // newest on top
|
||||
NotifyRecordingChanged.observe(call: #selector(recordingDidChange(_:)), on: self)
|
||||
}
|
||||
|
||||
@@ -69,15 +69,23 @@ class TVCPreviousRecords: UITableViewController, EditActionsRemove {
|
||||
let x = dataSource[indexPath.row]
|
||||
cell.textLabel?.text = x.title ?? x.fallbackTitle
|
||||
cell.textLabel?.textColor = (x.title == nil) ? .systemGray : nil
|
||||
cell.detailTextLabel?.text = "at \(x.start.asDateTime()), duration: \(x.durationString ?? "?")"
|
||||
cell.detailTextLabel?.text = "at \(DateFormat.seconds(x.start)), duration: \(x.durationString ?? "?")"
|
||||
return cell
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Editing
|
||||
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath, tableView)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
|
||||
func editableRowCallback(_ index: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool {
|
||||
DBWrp.recordingDelete(self.dataSource[index.row])
|
||||
RecordingsDB.delete(self.dataSource[index.row])
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,15 +6,13 @@ class TVCRecordingDetails: UITableViewController, EditActionsRemove {
|
||||
|
||||
override func viewDidLoad() {
|
||||
title = record.title ?? record.fallbackTitle
|
||||
dataSource = DBWrp.recordingDetails(record)
|
||||
dataSource = RecordingsDB.details(record)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View Data Source
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
dataSource.count
|
||||
}
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { dataSource.count }
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "PreviousRecordDetailCell")!
|
||||
@@ -27,10 +25,18 @@ class TVCRecordingDetails: UITableViewController, EditActionsRemove {
|
||||
|
||||
// MARK: - Editing
|
||||
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath, tableView)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
|
||||
func editableRowCallback(_ index: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool {
|
||||
if DBWrp.recordingDeleteDetails(record, domain: self.dataSource[index.row].domain) {
|
||||
self.dataSource.remove(at: index.row)
|
||||
self.tableView.deleteRows(at: [index], with: .automatic)
|
||||
if RecordingsDB.deleteDetails(record, domain: dataSource[index.row].domain) {
|
||||
dataSource.remove(at: index.row)
|
||||
tableView.deleteRows(at: [index], with: .automatic)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ class VCEditRecording: UIViewController, UITextFieldDelegate, UITextViewDelegate
|
||||
inputTitle.text = record.title
|
||||
inputNotes.text = record.notes
|
||||
inputDetails.text = """
|
||||
Start: \(record.start.asDateTime())
|
||||
End: \(record.stop?.asDateTime() ?? "?")
|
||||
Start: \(DateFormat.seconds(record.start))
|
||||
End: \(record.stop == nil ? "?" : DateFormat.seconds(record.stop!))
|
||||
Duration: \(record.durationString ?? "?")
|
||||
"""
|
||||
validateSaveButton()
|
||||
@@ -35,7 +35,8 @@ class VCEditRecording: UIViewController, UITextFieldDelegate, UITextViewDelegate
|
||||
// MARK: Save & Cancel Buttons
|
||||
|
||||
@IBAction func didTapSave(_ sender: UIBarButtonItem) {
|
||||
if deleteOnCancel { // aka newly created
|
||||
let newlyCreated = deleteOnCancel
|
||||
if newlyCreated {
|
||||
// if remains true, `viewDidDisappear` will delete the record
|
||||
deleteOnCancel = false
|
||||
}
|
||||
@@ -43,8 +44,10 @@ class VCEditRecording: UIViewController, UITextFieldDelegate, UITextViewDelegate
|
||||
record.title = (inputTitle.text == "") ? nil : inputTitle.text
|
||||
record.notes = (inputNotes.text == "") ? nil : inputNotes.text
|
||||
dismiss(animated: true) {
|
||||
DBWrp.recordingUpdate(self.record)
|
||||
DBWrp.recordingPersist(self.record)
|
||||
RecordingsDB.update(self.record)
|
||||
if newlyCreated {
|
||||
RecordingsDB.persist(self.record)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +59,7 @@ class VCEditRecording: UIViewController, UITextFieldDelegate, UITextViewDelegate
|
||||
override func viewDidDisappear(_ animated: Bool) {
|
||||
if deleteOnCancel {
|
||||
QLog.Debug("deleting record #\(record.id)")
|
||||
DBWrp.recordingDelete(record)
|
||||
RecordingsDB.delete(record)
|
||||
deleteOnCancel = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,15 +12,12 @@ class VCRecordings: UIViewController, UINavigationControllerDelegate {
|
||||
override func viewDidLoad() {
|
||||
prevRecController = (children.first as! UINavigationController)
|
||||
prevRecController.delegate = self
|
||||
// Duplicate font attributes but set monospace
|
||||
let traits = timeLabel.font.fontDescriptor.object(forKey: .traits) as? [UIFontDescriptor.TraitKey: Any] ?? [:]
|
||||
let weight = traits[.weight] as? CGFloat ?? UIFont.Weight.regular.rawValue
|
||||
timeLabel.font = UIFont.monospacedDigitSystemFont(ofSize: timeLabel.font.pointSize, weight: UIFont.Weight(rawValue: weight))
|
||||
timeLabel.font = timeLabel.font.monoSpace()
|
||||
// hide timer if not running
|
||||
updateUI(setRecording: false, animated: false)
|
||||
currentRecording = DBWrp.recordingGetCurrent()
|
||||
currentRecording = RecordingsDB.getCurrent()
|
||||
|
||||
if !UserDefaults.standard.bool(forKey: "didShowTutorialRecordings") {
|
||||
if !Pref.DidShowTutorial.Recordings {
|
||||
self.perform(#selector(showTutorial), with: nil, afterDelay: 0.5)
|
||||
}
|
||||
}
|
||||
@@ -33,10 +30,20 @@ class VCRecordings: UIViewController, UINavigationControllerDelegate {
|
||||
stopTimer(animate: false)
|
||||
}
|
||||
|
||||
func navigationController(_ navigationController: UINavigationController, willShow vc: UIViewController, animated: Bool) {
|
||||
let isRoot = (vc == navigationController.viewControllers.first)
|
||||
UIView.animate(withDuration: 0.3) {
|
||||
self.startNewRecView.isHidden = !isRoot // hide "new recording" if details open
|
||||
func navigationController(_ nav: UINavigationController, willShow vc: UIViewController, animated: Bool) {
|
||||
hideNewRecording(isRootVC: (vc == nav.viewControllers.first), didShow: false)
|
||||
}
|
||||
|
||||
func navigationController(_ nav: UINavigationController, didShow vc: UIViewController, animated: Bool) {
|
||||
// TODO: use interactive animation handler to dynamically animate "new recording" view
|
||||
hideNewRecording(isRootVC: (vc == nav.viewControllers.first), didShow: true)
|
||||
}
|
||||
|
||||
private func hideNewRecording(isRootVC: Bool, didShow: Bool) {
|
||||
if isRootVC == didShow {
|
||||
UIView.animate(withDuration: 0.3) {
|
||||
self.startNewRecView.isHidden = !isRootVC // hide "new recording" if details open
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,11 +52,11 @@ class VCRecordings: UIViewController, UINavigationControllerDelegate {
|
||||
|
||||
@IBAction private func startRecordingButtonTapped(_ sender: UIButton) {
|
||||
if recordingTimer == nil {
|
||||
currentRecording = DBWrp.recordingStartNew()
|
||||
currentRecording = RecordingsDB.startNew()
|
||||
startTimer(animate: true)
|
||||
} else {
|
||||
stopTimer(animate: true)
|
||||
DBWrp.recordingStop(¤tRecording!)
|
||||
RecordingsDB.stop(¤tRecording!)
|
||||
prevRecController.popToRootViewController(animated: true)
|
||||
let editVC = (prevRecController.topViewController as! TVCPreviousRecords)
|
||||
editVC.insertAndEditRecording(currentRecording!)
|
||||
@@ -61,7 +68,7 @@ class VCRecordings: UIViewController, UINavigationControllerDelegate {
|
||||
guard let r = currentRecording, r.stop == nil else {
|
||||
return
|
||||
}
|
||||
recordingTimer = Timer.repeating(0.086, call: #selector(timerCallback(_:)), on: self, userInfo: r.start.toDate())
|
||||
recordingTimer = Timer.repeating(0.086, call: #selector(timerCallback(_:)), on: self, userInfo: Date(r.start))
|
||||
updateUI(setRecording: true, animated: animate)
|
||||
}
|
||||
|
||||
@@ -127,7 +134,7 @@ class VCRecordings: UIViewController, UINavigationControllerDelegate {
|
||||
))
|
||||
x.buttonTitleDone = "Got it"
|
||||
x.present {
|
||||
UserDefaults.standard.set(true, forKey: "didShowTutorialRecordings")
|
||||
Pref.DidShowTutorial.Recordings = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
169
main/Requests/Analytics/VCCoOccurrence.swift
Normal file
@@ -0,0 +1,169 @@
|
||||
import UIKit
|
||||
|
||||
class VCCoOccurrence: UIViewController, UITableViewDataSource {
|
||||
var fqdn: String!
|
||||
private var dataSource: [ContextAnalysisResult] = []
|
||||
|
||||
@IBOutlet private var tableView: UITableView!
|
||||
@IBOutlet private var timeSegment: UISegmentedControl!
|
||||
private let availableTimes = [0, 5, 15, 30]
|
||||
private var selectedTime = -1 {
|
||||
didSet { logTimeDelta = log(CGFloat(max(2, selectedTime+1))) }
|
||||
}
|
||||
private var logTimeDelta: CGFloat = 1
|
||||
private var logMaxCount: CGFloat = 1
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
selectedTime = Pref.ContextAnalyis.CoOccurrenceTime ?? 5 // calls `didSet` and `logTimeDelta`
|
||||
timeSegment.removeAllSegments() // clear IB values
|
||||
for (i, time) in availableTimes.enumerated() {
|
||||
timeSegment.insertSegment(withTitle: TimeFormat(.abbreviated).from(seconds: time), at: i, animated: false)
|
||||
if time == selectedTime {
|
||||
timeSegment.selectedSegmentIndex = i
|
||||
}
|
||||
}
|
||||
reloadDataSource()
|
||||
}
|
||||
|
||||
func reloadDataSource() {
|
||||
dataSource = [("Loading …", 0, 0, 0)]
|
||||
logMaxCount = 1
|
||||
tableView.reloadData()
|
||||
let domain = fqdn!
|
||||
let time = Timestamp(selectedTime)
|
||||
DispatchQueue.global().async { [weak self] in
|
||||
let temp: [ContextAnalysisResult]
|
||||
let total: Int32
|
||||
if let db = AppDB,
|
||||
let times = db.dnsLogsUniqTs(domain), times.count > 0,
|
||||
let result = db.contextAnalysis(coOccurrence: times, plusMinus: time, exclude: domain),
|
||||
result.count > 0
|
||||
{
|
||||
temp = result
|
||||
var sum: Int32 = 0
|
||||
for x in result { sum += x.count }
|
||||
total = sum // if statement guarantees >= 1
|
||||
} else {
|
||||
temp = []
|
||||
total = 1
|
||||
}
|
||||
DispatchQueue.main.sync { [weak self] in
|
||||
self?.dataSource = temp
|
||||
self?.logMaxCount = log(CGFloat(total + 1))
|
||||
self?.tableView.reloadData()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func didChangeTime(_ sender: UISegmentedControl) {
|
||||
selectedTime = availableTimes[sender.selectedSegmentIndex]
|
||||
Pref.ContextAnalyis.CoOccurrenceTime = selectedTime
|
||||
reloadDataSource()
|
||||
}
|
||||
|
||||
@IBAction func didClose(_ sender: UIBarButtonItem) {
|
||||
dismiss(animated: true)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View Data Source
|
||||
|
||||
func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int {
|
||||
dataSource.count
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "CoOccurrenceCell") as! CoOccurrenceCell
|
||||
let src = dataSource[indexPath.row]
|
||||
cell.title.text = src.domain
|
||||
cell.rank.text = "\(indexPath.row + 1)."
|
||||
cell.count.text = "\(src.count)"
|
||||
cell.avgdiff.text = String(format: "%.2fs", src.avg)
|
||||
|
||||
// log percentage of total co-occurrence count + 1 (min: log(2))
|
||||
cell.countMeter.percent = (log(CGFloat(src.count + 1)) / logMaxCount)
|
||||
// log percentage of selected time window (0s/5s/15s/30s) + 1 (min: log(2))
|
||||
cell.avgdiffMeter.percent = 1 - (log(CGFloat(src.avg + 1)) / logTimeDelta)
|
||||
return cell
|
||||
}
|
||||
}
|
||||
|
||||
class CoOccurrenceCell: UITableViewCell {
|
||||
@IBOutlet var title: UILabel!
|
||||
@IBOutlet var rank: TagLabel!
|
||||
@IBOutlet var count: TagLabel!
|
||||
@IBOutlet var avgdiff: TagLabel!
|
||||
@IBOutlet var countMeter: MeterBar!
|
||||
@IBOutlet var avgdiffMeter: MeterBar!
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Tutorial Screen
|
||||
|
||||
extension VCCoOccurrence {
|
||||
|
||||
@IBAction func showInfoScreen() {
|
||||
let sampleCell: UIImage = {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "CoOccurrenceCell") as! CoOccurrenceCell
|
||||
cell.title.text = "example.org"
|
||||
cell.rank.text = "9."
|
||||
cell.count.text = "14"
|
||||
cell.avgdiff.text = String(format: "%.2fs", 0.71)
|
||||
cell.countMeter.percent = 0.35
|
||||
cell.avgdiffMeter.percent = 0.95
|
||||
|
||||
// Bug: Sometimes dequeue will return a "broken" hidden cell.
|
||||
// It can't be set visible and thus can't render an image.
|
||||
// Funnily `cell.contentView` can rendered.
|
||||
let theView = cell.isHidden ? cell.contentView : cell
|
||||
|
||||
// resize view to fit into tutorial sheet
|
||||
let minWidth = TutorialSheet.verticalWidth - 10 //-> 2 * textContainer.lineFragmentPadding
|
||||
theView.frame.size = theView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
|
||||
theView.frame.size.width = min(theView.frame.size.width, minWidth)
|
||||
// set width in two steps because first call may change layoutMargins
|
||||
theView.frame.size.width += theView.layoutMargins.left + theView.layoutMargins.right
|
||||
// FIXME: In case `hidden == false`, backgroundColor will be black in Dark mode.
|
||||
theView.backgroundColor = tableView.backgroundColor
|
||||
return theView.asImage(insets: theView.layoutMargins)
|
||||
}()
|
||||
|
||||
let x = TutorialSheet()
|
||||
x.addSheet().addArrangedSubview(QuickUI.text(attributed: NSMutableAttributedString()
|
||||
.h3("Co-Occurrence")
|
||||
.normal(" allows you to find requests that happen often at the same time as the selected domain. " +
|
||||
"Hence it will give you a hint what Apps might be involved in the activity." +
|
||||
"\n\nHow do you interpret these results? Lets look at an example:\n\n")
|
||||
.centered(.image(sampleCell))
|
||||
.normal("\n\nThe domain ").bold("example.org").normal(" had ").bold("14").normal(" requests with an ").italic("average time divergence").normal(" of ").bold("0.71 seconds").normal(". " +
|
||||
"That is, these 14 domain calls happend, on average, less then a second before or after the original request of the selected domain." +
|
||||
"\n\nClose temporal proximity and high occurrence counts are both indicators for domain correlation. " +
|
||||
"Results are sorted by a ranking index (").bold("9.").normal(") which strikes a balance between the two. " +
|
||||
"Preferring entries with higher counts as well as low time divergence.")
|
||||
.italic("\n\nTip: ").normal("As a visual guide you can look for the colored bar beside each value. " +
|
||||
"The larger the bar, the greater the correlation.")
|
||||
))
|
||||
|
||||
x.present(in: self)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate extension UIView {
|
||||
func asImage(insets: UIEdgeInsets = .zero) -> UIImage {
|
||||
if #available(iOS 10.0, *) {
|
||||
let renderer = UIGraphicsImageRenderer(bounds: bounds.inset(by: insets))
|
||||
return renderer.image { rendererContext in
|
||||
layer.render(in: rendererContext.cgContext)
|
||||
}
|
||||
} else {
|
||||
UIGraphicsBeginImageContext(bounds.inset(by: insets).size)
|
||||
let ctx = UIGraphicsGetCurrentContext()!
|
||||
ctx.translateBy(x: -insets.left, y: -insets.top)
|
||||
layer.render(in:ctx)
|
||||
let image = UIGraphicsGetImageFromCurrentImageContext()
|
||||
UIGraphicsEndImageContext()
|
||||
return UIImage(cgImage: image!.cgImage!)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,76 @@
|
||||
import UIKit
|
||||
|
||||
class TVCDomains: UITableViewController, IncrementalDataSourceUpdate {
|
||||
class TVCDomains: UITableViewController, UISearchBarDelegate, GroupedDomainDataSourceDelegate {
|
||||
|
||||
internal var dataSource: [GroupedDomain] = []
|
||||
lazy var source = GroupedDomainDataSource(withParent: nil)
|
||||
|
||||
@IBOutlet private var filterButton: UIBarButtonItem!
|
||||
@IBOutlet private var filterButtonDetail: UIBarButtonItem!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
if #available(iOS 10.0, *) {
|
||||
tableView.refreshControl = UIRefreshControl(call: #selector(reloadDataSource), on: self)
|
||||
}
|
||||
NotifyLogHistoryReset.observe(call: #selector(reloadDataSource), on: self)
|
||||
reloadDataSource()
|
||||
DBWrp.dataA_delegate = self
|
||||
NotifyDateFilterChanged.observe(call: #selector(didChangeDateFilter), on: self)
|
||||
didChangeDateFilter()
|
||||
source.delegate = self // init lazy var, ready for tableView data source
|
||||
}
|
||||
|
||||
@objc func reloadDataSource() {
|
||||
dataSource = DBWrp.listOfDomains()
|
||||
tableView.reloadData()
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
// iOS 11+ fix: fuse after `didAppear` to hide on app launch
|
||||
source.search.fuseWith(tableViewController: self)
|
||||
}
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if let index = tableView.indexPathForSelectedRow?.row {
|
||||
(segue.destination as? TVCHosts)?.parentDomain = dataSource[index].domain
|
||||
(segue.destination as? TVCHosts)?.parentDomain = source[index].domain
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View Delegate
|
||||
// MARK: - Filter
|
||||
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { dataSource.count }
|
||||
@IBAction private func filterButtonTapped(_ sender: UIBarButtonItem) {
|
||||
let vc = self.storyboard!.instantiateViewController(withIdentifier: "domainFilter")
|
||||
vc.modalPresentationStyle = .custom
|
||||
if #available(iOS 13.0, *) {
|
||||
vc.isModalInPresentation = true
|
||||
}
|
||||
present(vc, animated: true)
|
||||
}
|
||||
|
||||
@objc private func didChangeDateFilter() {
|
||||
switch Pref.DateFilter.Kind {
|
||||
case .ABRange: // read start/end time
|
||||
self.filterButtonDetail.title = "A – B"
|
||||
self.filterButton.image = UIImage(named: "filter-filled")
|
||||
case .LastXMin: // most recent
|
||||
let lastXMin = Pref.DateFilter.LastXMin
|
||||
if lastXMin == 0 { fallthrough }
|
||||
self.filterButtonDetail.title = TimeFormat(.abbreviated).from(minutes: lastXMin)
|
||||
self.filterButton.image = UIImage(named: "filter-filled")
|
||||
default:
|
||||
self.filterButtonDetail.title = ""
|
||||
self.filterButton.image = UIImage(named: "filter-clear")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View Data Source
|
||||
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { source.numberOfRows }
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "DomainCell")!
|
||||
let entry = dataSource[indexPath.row]
|
||||
let entry = source[indexPath.row]
|
||||
cell.textLabel?.text = entry.domain
|
||||
cell.detailTextLabel?.text = entry.detailCellText
|
||||
cell.imageView?.image = entry.options?.tableRowImage()
|
||||
return cell
|
||||
}
|
||||
|
||||
func groupedDomainDataSource(needsUpdate row: Int) {
|
||||
let entry = source[row]
|
||||
let cell = tableView.cellForRow(at: IndexPath(row: row))
|
||||
cell?.detailTextLabel?.text = entry.detailCellText
|
||||
cell?.imageView?.image = entry.options?.tableRowImage()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,115 @@
|
||||
import UIKit
|
||||
|
||||
class TVCHostDetails: UITableViewController {
|
||||
class TVCHostDetails: UITableViewController, SyncUpdateDelegate, UITabBarDelegate {
|
||||
|
||||
@IBOutlet private var actionsBar: UITabBar!
|
||||
|
||||
public var fullDomain: String!
|
||||
private var dataSource: [(ts: Timestamp, blocked: Bool)] = []
|
||||
private var dataSource: [GroupedTsOccurrence] = []
|
||||
// TODO: respect date reverse sort order
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
navigationItem.prompt = fullDomain
|
||||
super.viewDidLoad()
|
||||
sync.addObserver(self) // calls `syncUpdate(reset:)`
|
||||
if #available(iOS 10.0, *) {
|
||||
tableView.refreshControl = UIRefreshControl(call: #selector(reloadDataSource), on: self)
|
||||
sync.allowPullToRefresh(onTVC: self, forObserver: self)
|
||||
actionsBar.unselectedItemTintColor = .systemBlue
|
||||
}
|
||||
NotifyLogHistoryReset.observe(call: #selector(reloadDataSource), on: self)
|
||||
reloadDataSource()
|
||||
UIDevice.orientationDidChangeNotification.observe(call: #selector(didChangeOrientation), on: self)
|
||||
}
|
||||
|
||||
@objc func reloadDataSource() {
|
||||
dataSource = DBWrp.listOfTimes(fullDomain)
|
||||
tableView.reloadData()
|
||||
}
|
||||
// MARK: - Table View Data Source
|
||||
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { dataSource.count }
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "HostDetailCell")!
|
||||
let src = dataSource[indexPath.row]
|
||||
cell.textLabel?.text = src.ts.asDateTime()
|
||||
cell.imageView?.image = (src.blocked ? UIImage(named: "shield-x") : nil)
|
||||
cell.textLabel?.text = DateFormat.seconds(src.ts)
|
||||
cell.detailTextLabel?.text = (src.total > 1) ? "\(src.total)x" : nil
|
||||
cell.imageView?.image = (src.blocked > 0 ? UIImage(named: "shield-x") : nil)
|
||||
return cell
|
||||
}
|
||||
}
|
||||
|
||||
// #########################
|
||||
// #
|
||||
// # MARK: - Tab Bar
|
||||
// #
|
||||
// #########################
|
||||
|
||||
extension TVCHostDetails {
|
||||
|
||||
@objc private func didChangeOrientation(_ sender: Notification) {
|
||||
tableView.sizeHeaderToFit() // otherwise TabBar won't compress
|
||||
}
|
||||
|
||||
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
|
||||
tabBar.selectedItem = nil
|
||||
performSegue(withIdentifier: "segueAnalysisCoOccurrence", sender: nil)
|
||||
}
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "segueAnalysisCoOccurrence" {
|
||||
(segue.destination as? VCCoOccurrence)?.fqdn = fullDomain
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ################################
|
||||
// #
|
||||
// # MARK: - Partial Update
|
||||
// #
|
||||
// ################################
|
||||
|
||||
extension TVCHostDetails {
|
||||
|
||||
func syncUpdate(_ _: SyncUpdate, reset rows: SQLiteRowRange) {
|
||||
dataSource = AppDB?.timesForDomain(fullDomain, range: rows) ?? []
|
||||
DispatchQueue.main.sync { tableView.reloadData() }
|
||||
}
|
||||
|
||||
func syncUpdate(_ _: SyncUpdate, insert rows: SQLiteRowRange, affects: SyncUpdateEnd) {
|
||||
guard let latest = AppDB?.timesForDomain(fullDomain, range: rows), latest.count > 0 else {
|
||||
return
|
||||
}
|
||||
// Assuming they are ordered by ts and in descending order
|
||||
let range: Range<Int>
|
||||
switch affects {
|
||||
case .Earliest:
|
||||
range = dataSource.endIndex..<(dataSource.endIndex + latest.count)
|
||||
dataSource.append(contentsOf: latest)
|
||||
case .Latest:
|
||||
range = dataSource.startIndex..<(dataSource.startIndex + latest.count)
|
||||
dataSource.insert(contentsOf: latest, at: 0)
|
||||
}
|
||||
DispatchQueue.main.sync { tableView.safeInsertRows(range, with: .left) }
|
||||
}
|
||||
|
||||
func syncUpdate(_ sender: SyncUpdate, remove _: SQLiteRowRange, affects: SyncUpdateEnd) {
|
||||
// Assuming they are ordered by ts and in descending order
|
||||
let range: Range<Int>
|
||||
switch affects {
|
||||
case .Earliest:
|
||||
guard let t = sender.tsEarliest,
|
||||
let i = dataSource.lastIndex(where: { $0.ts >= t }),
|
||||
(i+1) < dataSource.count else { return }
|
||||
range = (i+1)..<dataSource.endIndex
|
||||
dataSource.removeLast(dataSource.count - (i+1))
|
||||
case .Latest:
|
||||
guard let t = sender.tsLatest,
|
||||
let i = dataSource.firstIndex(where: { $0.ts <= t }),
|
||||
i > 0 else { return }
|
||||
range = dataSource.startIndex..<i
|
||||
dataSource.removeFirst(i)
|
||||
}
|
||||
DispatchQueue.main.sync { tableView.safeDeleteRows(range) }
|
||||
}
|
||||
|
||||
func syncUpdate(_ sender: SyncUpdate, partialRemove affectedDomain: String) {
|
||||
if fullDomain.isSubdomain(of: affectedDomain) {
|
||||
syncUpdate(sender, reset: sender.rows)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +1,34 @@
|
||||
import UIKit
|
||||
|
||||
class TVCHosts: UITableViewController, IncrementalDataSourceUpdate {
|
||||
class TVCHosts: UITableViewController, GroupedDomainDataSourceDelegate {
|
||||
|
||||
lazy var source = GroupedDomainDataSource(withParent: parentDomain)
|
||||
|
||||
public var parentDomain: String!
|
||||
internal var dataSource: [GroupedDomain] = []
|
||||
private var isSpecial: Bool = false
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
navigationItem.prompt = parentDomain
|
||||
super.viewDidLoad()
|
||||
isSpecial = (parentDomain.first == "#") // aka: "# IP address"
|
||||
if #available(iOS 10.0, *) {
|
||||
tableView.refreshControl = UIRefreshControl(call: #selector(reloadDataSource), on: self)
|
||||
}
|
||||
NotifyLogHistoryReset.observe(call: #selector(reloadDataSource), on: self)
|
||||
reloadDataSource()
|
||||
DBWrp.currentlyOpenParent = parentDomain
|
||||
DBWrp.dataB_delegate = self
|
||||
}
|
||||
deinit {
|
||||
DBWrp.currentlyOpenParent = nil
|
||||
}
|
||||
|
||||
@objc func reloadDataSource() {
|
||||
dataSource = DBWrp.listOfHosts(parentDomain)
|
||||
tableView.reloadData()
|
||||
source.delegate = self // init lazy var, ready for tableView data source
|
||||
source.search.fuseWith(tableViewController: self)
|
||||
}
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if let index = tableView.indexPathForSelectedRow?.row {
|
||||
(segue.destination as? TVCHostDetails)?.fullDomain = dataSource[index].domain
|
||||
(segue.destination as? TVCHostDetails)?.fullDomain = source[index].domain
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Data Source
|
||||
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { dataSource.count }
|
||||
// MARK: - Table View Data Source
|
||||
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { source.numberOfRows }
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "HostCell")!
|
||||
let entry = dataSource[indexPath.row]
|
||||
let entry = source[indexPath.row]
|
||||
if isSpecial {
|
||||
// currently only used for IP addresses
|
||||
cell.textLabel?.text = entry.domain
|
||||
@@ -51,4 +40,11 @@ class TVCHosts: UITableViewController, IncrementalDataSourceUpdate {
|
||||
cell.imageView?.image = entry.options?.tableRowImage()
|
||||
return cell
|
||||
}
|
||||
|
||||
func groupedDomainDataSource(needsUpdate row: Int) {
|
||||
let entry = source[row]
|
||||
let cell = tableView.cellForRow(at: IndexPath(row: row))
|
||||
cell?.detailTextLabel?.text = entry.detailCellText
|
||||
cell?.imageView?.image = entry.options?.tableRowImage()
|
||||
}
|
||||
}
|
||||
|
||||
120
main/Requests/VCDateFilter.swift
Normal file
@@ -0,0 +1,120 @@
|
||||
import UIKit
|
||||
|
||||
// TODO: (count > x) filter
|
||||
|
||||
class VCDateFilter: UIViewController, UIGestureRecognizerDelegate {
|
||||
|
||||
@IBOutlet private var filterBy: UISegmentedControl!
|
||||
|
||||
// entries no older than
|
||||
@IBOutlet private var durationTitle: UILabel!
|
||||
@IBOutlet private var durationView: UIView!
|
||||
@IBOutlet private var durationSlider: UISlider!
|
||||
@IBOutlet private var durationLabel: UILabel!
|
||||
private let durationTimes = [0, 1, 20, 60, 360, 720, 1440, 2880, 4320, 10080]
|
||||
|
||||
// entries within range
|
||||
@IBOutlet private var rangeTitle: UILabel!
|
||||
@IBOutlet private var rangeView: UIView!
|
||||
@IBOutlet private var buttonRangeStart: UIButton!
|
||||
@IBOutlet private var buttonRangeEnd: UIButton!
|
||||
private lazy var tsRangeA: Timestamp = Pref.DateFilter.RangeA ?? AppDB?.dnsLogsMinDate() ?? .now()
|
||||
private lazy var tsRangeB: Timestamp = Pref.DateFilter.RangeB ?? .now()
|
||||
|
||||
// order by
|
||||
@IBOutlet private var orderbyType: UISegmentedControl!
|
||||
@IBOutlet private var orderbyAsc: UISegmentedControl!
|
||||
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
filterBy.selectedSegmentIndex = (Pref.DateFilter.Kind == .ABRange ? 1 : 0)
|
||||
didChangeFilterBy(filterBy)
|
||||
|
||||
durationSlider.tag = -1 // otherwise wont update because `tag == 0`
|
||||
durationSlider.value = Float(durationTimes.firstIndex(of: Pref.DateFilter.LastXMin) ?? 0) / 9
|
||||
durationSliderChanged(durationSlider)
|
||||
|
||||
buttonRangeStart.setTitle(DateFormat.minutes(tsRangeA), for: .normal)
|
||||
buttonRangeEnd.setTitle(DateFormat.minutes(tsRangeB), for: .normal)
|
||||
|
||||
orderbyType.selectedSegmentIndex = Pref.DateFilter.OrderBy.rawValue
|
||||
orderbyAsc.selectedSegmentIndex = (Pref.DateFilter.OrderAsc ? 0 : 1)
|
||||
}
|
||||
|
||||
@IBAction private func didChangeFilterBy(_ sender: UISegmentedControl) {
|
||||
let firstSelected = (sender.selectedSegmentIndex == 0)
|
||||
durationTitle.isHidden = !firstSelected
|
||||
durationView.isHidden = !firstSelected
|
||||
rangeTitle.isHidden = firstSelected
|
||||
rangeView.isHidden = firstSelected
|
||||
}
|
||||
|
||||
@IBAction private func durationSliderChanged(_ sender: UISlider) {
|
||||
let i = Int((sender.value + (0.499/9)) * 9) // mid-value-switch
|
||||
guard i >= 0, i <= 9 else { return }
|
||||
sender.value = Float(i) / 9
|
||||
if sender.tag != durationTimes[i] {
|
||||
sender.tag = durationTimes[i]
|
||||
durationLabel.text = (sender.tag == 0 ? "Off" : TimeFormat(.short).from(minutes: sender.tag))
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction private func didTapRangeButton(_ sender: UIButton) {
|
||||
let flag = (sender == buttonRangeStart)
|
||||
DatePickerAlert(presentIn: self, configure: {
|
||||
$0.setDate(Date(flag ? self.tsRangeA : self.tsRangeB), animated: false)
|
||||
}, onSuccess: {
|
||||
var ts = $0.timestamp
|
||||
ts -= ts % 60 // remove seconds
|
||||
// if one of these is greater than the other, adjust the latter too.
|
||||
if flag || self.tsRangeA > ts {
|
||||
self.tsRangeA = ts // lower end of minute
|
||||
self.buttonRangeStart.setTitle(DateFormat.minutes(ts), for: .normal)
|
||||
}
|
||||
if !flag || ts > self.tsRangeB {
|
||||
self.tsRangeB = ts + 59 // upper end of minute
|
||||
self.buttonRangeEnd.setTitle(DateFormat.minutes(ts + 59), for: .normal)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
|
||||
if gestureRecognizer.view === touch.view {
|
||||
saveSettings()
|
||||
dismiss(animated: true)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private func saveSettings() {
|
||||
let newXMin = durationSlider.tag
|
||||
let filterType: DateFilterKind
|
||||
let orderType: DateFilterOrderBy
|
||||
|
||||
switch filterBy.selectedSegmentIndex {
|
||||
case 0: filterType = (newXMin > 0) ? .LastXMin : .Off
|
||||
case 1: filterType = .ABRange
|
||||
default: preconditionFailure()
|
||||
}
|
||||
switch orderbyType.selectedSegmentIndex {
|
||||
case 0: orderType = .Date
|
||||
case 1: orderType = .Name
|
||||
case 2: orderType = .Count
|
||||
default: preconditionFailure()
|
||||
}
|
||||
let a = Pref.DateFilter.OrderBy <-? orderType
|
||||
let b = Pref.DateFilter.OrderAsc <-? (orderbyAsc.selectedSegmentIndex == 0)
|
||||
if a || b {
|
||||
NotifySortOrderChanged.post()
|
||||
}
|
||||
let c = Pref.DateFilter.Kind <-? filterType
|
||||
let d = Pref.DateFilter.LastXMin <-? newXMin
|
||||
let e = Pref.DateFilter.RangeA <-? (filterType == .ABRange ? tsRangeA : nil)
|
||||
let f = Pref.DateFilter.RangeB <-? (filterType == .ABRange ? tsRangeB : nil)
|
||||
if c || d || e || f {
|
||||
NotifyDateFilterChanged.post()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,27 @@
|
||||
import UIKit
|
||||
|
||||
class TVCFilter: UITableViewController, EditActionsRemove {
|
||||
var currentFilter: FilterOptions = .none
|
||||
private var dataSource: [String] = []
|
||||
var currentFilter: FilterOptions = .none // set by segue
|
||||
private lazy var dataSource = DomainFilter.list(where: currentFilter)
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
// if #available(iOS 10.0, *) {
|
||||
// tableView.refreshControl = UIRefreshControl(call: #selector(reloadDataSource), on: self)
|
||||
// }
|
||||
NotifyFilterChanged.observe(call: #selector(reloadDataSource), on: self)
|
||||
reloadDataSource()
|
||||
NotifyDNSFilterChanged.observe(call: #selector(didChangeDomainFilter), on: self)
|
||||
}
|
||||
|
||||
@objc func reloadDataSource() {
|
||||
dataSource = DBWrp.dataF_list(currentFilter)
|
||||
tableView.reloadData()
|
||||
|
||||
@objc func didChangeDomainFilter(_ notification: Notification) {
|
||||
guard let domain = notification.object as? String else {
|
||||
preconditionFailure("Domain independent filter reset not implemented")
|
||||
}
|
||||
if DomainFilter[domain]?.contains(currentFilter) ?? false {
|
||||
let i = dataSource.binTreeIndex(of: domain, compare: (<))!
|
||||
if i >= dataSource.count || dataSource[i] != domain {
|
||||
dataSource.insert(domain, at: i)
|
||||
tableView.safeInsertRow(i)
|
||||
}
|
||||
} else if let i = dataSource.binTreeRemove(domain, compare: (<)) {
|
||||
tableView.safeDeleteRows([i])
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction private func addNewFilter() {
|
||||
@@ -33,13 +39,16 @@ class TVCFilter: UITableViewController, EditActionsRemove {
|
||||
ErrorAlert("Entered domain is not valid. Filter can't match country TLD only.").presentIn(self)
|
||||
return
|
||||
}
|
||||
DBWrp.updateFilter(dom, add: self.currentFilter)
|
||||
DomainFilter.update(dom, add: self.currentFilter)
|
||||
}
|
||||
alert.addTextField {
|
||||
$0.placeholder = "cdn.domain.tld"
|
||||
$0.keyboardType = .URL
|
||||
}
|
||||
alert.addTextField { $0.placeholder = "cdn.domain.tld" }
|
||||
alert.presentIn(self)
|
||||
}
|
||||
|
||||
// MARK: - Table View Delegate
|
||||
// MARK: - Table View Data Source
|
||||
|
||||
override func tableView(_ _: UITableView, numberOfRowsInSection _: Int) -> Int { dataSource.count }
|
||||
|
||||
@@ -54,11 +63,17 @@ class TVCFilter: UITableViewController, EditActionsRemove {
|
||||
|
||||
// MARK: - Editing
|
||||
|
||||
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
|
||||
getRowActionsIOS9(indexPath, tableView)
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
||||
getRowActionsIOS11(indexPath)
|
||||
}
|
||||
|
||||
func editableRowCallback(_ index: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool {
|
||||
let domain = dataSource[index.row]
|
||||
DBWrp.updateFilter(domain, remove: currentFilter)
|
||||
dataSource.remove(at: index.row)
|
||||
tableView.deleteRows(at: [index], with: .automatic)
|
||||
DomainFilter.update(domain, remove: currentFilter)
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -11,16 +11,14 @@ class TVCSettings: UITableViewController {
|
||||
super.viewDidLoad()
|
||||
NotifyVPNStateChanged.observe(call: #selector(vpnStateChanged(_:)), on: self)
|
||||
changedState(currentVPNState)
|
||||
NotifyFilterChanged.observe(call: #selector(reloadDataSource), on: self)
|
||||
NotifyDNSFilterChanged.observe(call: #selector(reloadDataSource), on: self)
|
||||
reloadDataSource()
|
||||
}
|
||||
|
||||
@objc func reloadDataSource() {
|
||||
let (blocked, ignored) = DBWrp.dataF_counts()
|
||||
DispatchQueue.main.async {
|
||||
self.cellDomainsIgnored.detailTextLabel?.text = "\(ignored) Domains"
|
||||
self.cellDomainsBlocked.detailTextLabel?.text = "\(blocked) Domains"
|
||||
}
|
||||
let (blocked, ignored) = DomainFilter.counts()
|
||||
cellDomainsIgnored.detailTextLabel?.text = "\(ignored) Domains"
|
||||
cellDomainsBlocked.detailTextLabel?.text = "\(blocked) Domains"
|
||||
}
|
||||
|
||||
@IBAction func toggleVPNProxy(_ sender: UISwitch) {
|
||||
@@ -28,33 +26,13 @@ class TVCSettings: UITableViewController {
|
||||
}
|
||||
|
||||
@IBAction func exportDB(_ sender: Any) {
|
||||
// TODO: export partly?
|
||||
// TODO: show header-banner of success
|
||||
// Share Sheet
|
||||
let sheet = UIActivityViewController(activityItems: [URL.internalDB()], applicationActivities: nil)
|
||||
self.present(sheet, animated: true)
|
||||
// Save to Files app
|
||||
// self.present(UIDocumentPickerViewController(url: FileManager.default.internalDB(), in: .exportToService), animated: true)
|
||||
// Shows Alert and exports to Documents directory
|
||||
// AskAlert(title: "Export results?", text: """
|
||||
// This action will copy the internal database to the app's local Documents directory. You can use the Files app to access the database file.
|
||||
//
|
||||
// Note: This will make your DNS requests available to other apps!
|
||||
// """, buttonText: "Export") {
|
||||
// do {
|
||||
// let dest = try SQLiteDatabase.export()
|
||||
// let folder = dest.deletingLastPathComponent()
|
||||
// let out = folder.lastPathComponent + "/" + dest.lastPathComponent
|
||||
// Alert(title: "Successful", text: "File exported to '\(out)'", buttonText: "OK").presentIn(self)
|
||||
// } catch {
|
||||
// ErrorAlert(error).presentIn(self)
|
||||
// }
|
||||
// }.presentIn(self)
|
||||
}
|
||||
|
||||
@IBAction func resetTutorialAlerts(_ sender: UIButton) {
|
||||
UserDefaults.standard.removeObject(forKey: "didShowTutorialAppWelcome")
|
||||
UserDefaults.standard.removeObject(forKey: "didShowTutorialRecordings")
|
||||
Pref.DidShowTutorial.Welcome = false
|
||||
Pref.DidShowTutorial.Recordings = false
|
||||
Alert(title: sender.titleLabel?.text,
|
||||
text: "\nDone.\n\nYou may need to restart the application.").presentIn(self)
|
||||
}
|
||||
@@ -64,7 +42,7 @@ class TVCSettings: UITableViewController {
|
||||
"You are about to delete all results that have been logged in the past. " +
|
||||
"Your preferences for blocked and ignored domains are preserved.\n" +
|
||||
"Continue?", buttonText: "Delete", buttonStyle: .destructive) { _ in
|
||||
DBWrp.deleteHistory()
|
||||
TheGreatDestroyer.deleteAllLogs()
|
||||
}.presentIn(self)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ class TBCMain: UITabBarController {
|
||||
NotifyVPNStateChanged.observe(call: #selector(vpnStateChanged(_:)), on: self)
|
||||
changedState(currentVPNState)
|
||||
|
||||
if !UserDefaults.standard.bool(forKey: "didShowTutorialAppWelcome") {
|
||||
if !Pref.DidShowTutorial.Welcome {
|
||||
self.perform(#selector(showWelcomeMessage), with: nil, afterDelay: 0.5)
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ class TBCMain: UITabBarController {
|
||||
)
|
||||
))
|
||||
x.present {
|
||||
UserDefaults.standard.set(true, forKey: "didShowTutorialAppWelcome")
|
||||
Pref.DidShowTutorial.Welcome = true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||