Browse Source

Convert NetworkMonitor to obj-c

Grant Limberg 9 years ago
parent
commit
a91187e60e

+ 10 - 8
ZeroTier One.xcodeproj/project.pbxproj

@@ -7,7 +7,6 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
-		932D472D1D138B0C004BCFE2 /* NetworkMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 932D472C1D138B0C004BCFE2 /* NetworkMonitor.swift */; };
 		932D472F1D1CD499004BCFE2 /* ZeroTierIcon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 932D472E1D1CD499004BCFE2 /* ZeroTierIcon.icns */; };
 		932D47331D1CD861004BCFE2 /* PreferencesViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */; };
 		932D47371D1CDC9B004BCFE2 /* AboutViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */; };
@@ -24,12 +23,12 @@
 		93D167661D54308200330C99 /* Network.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167651D54308200330C99 /* Network.m */; };
 		93D167691D57E7EA00330C99 /* AboutViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167681D57E7EA00330C99 /* AboutViewController.m */; };
 		93D1676D1D57EB8400330C99 /* PreferencesViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1676C1D57EB8400330C99 /* PreferencesViewController.m */; };
+		93D167701D57FD3800330C99 /* NetworkMonitor.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1676F1D57FD3800330C99 /* NetworkMonitor.m */; };
 		93DAFB271D3F0BEE004D5417 /* about.html in Resources */ = {isa = PBXBuildFile; fileRef = 93DAFB261D3F0BEE004D5417 /* about.html */; };
 		93DAFE4B1CFE53CA00547CC4 /* AuthtokenCopy.m in Sources */ = {isa = PBXBuildFile; fileRef = 93DAFE4A1CFE53CA00547CC4 /* AuthtokenCopy.m */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXFileReference section */
-		932D472C1D138B0C004BCFE2 /* NetworkMonitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkMonitor.swift; sourceTree = "<group>"; };
 		932D472E1D1CD499004BCFE2 /* ZeroTierIcon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = ZeroTierIcon.icns; sourceTree = "<group>"; };
 		932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = PreferencesViewController.xib; sourceTree = "<group>"; };
 		932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = AboutViewController.xib; sourceTree = "<group>"; };
@@ -53,6 +52,8 @@
 		93D167681D57E7EA00330C99 /* AboutViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AboutViewController.m; sourceTree = "<group>"; };
 		93D1676B1D57EB8400330C99 /* PreferencesViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PreferencesViewController.h; sourceTree = "<group>"; };
 		93D1676C1D57EB8400330C99 /* PreferencesViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PreferencesViewController.m; sourceTree = "<group>"; };
+		93D1676E1D57FD3800330C99 /* NetworkMonitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NetworkMonitor.h; sourceTree = "<group>"; };
+		93D1676F1D57FD3800330C99 /* NetworkMonitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NetworkMonitor.m; sourceTree = "<group>"; };
 		93DAFB261D3F0BEE004D5417 /* about.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = about.html; sourceTree = "<group>"; };
 		93DAFE491CFE53C900547CC4 /* ZeroTier One-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ZeroTier One-Bridging-Header.h"; sourceTree = "<group>"; };
 		93DAFE4A1CFE53CA00547CC4 /* AuthtokenCopy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AuthtokenCopy.m; sourceTree = "<group>"; };
@@ -92,19 +93,18 @@
 				932D472E1D1CD499004BCFE2 /* ZeroTierIcon.icns */,
 				93326BDB1CE7C816005CA2AC /* AppDelegate.swift */,
 				93326BE81CE7D9B9005CA2AC /* JoinNetworkViewController.swift */,
+				93326BE91CE7D9B9005CA2AC /* JoinNetworkViewController.xib */,
 				9330F13A1CF534E500687EC8 /* NetworkInfoCell.swift */,
 				93326BEC1CE7DA30005CA2AC /* ShowNetworksViewController.swift */,
+				93326BED1CE7DA30005CA2AC /* ShowNetworksViewController.xib */,
 				93326BDD1CE7C816005CA2AC /* Assets.xcassets */,
 				93326BDF1CE7C816005CA2AC /* MainMenu.xib */,
 				93326BE21CE7C816005CA2AC /* Info.plist */,
-				93326BE91CE7D9B9005CA2AC /* JoinNetworkViewController.xib */,
-				93326BED1CE7DA30005CA2AC /* ShowNetworksViewController.xib */,
 				93DAFE4A1CFE53CA00547CC4 /* AuthtokenCopy.m */,
 				93DAFE4C1CFE53DA00547CC4 /* AuthtokenCopy.h */,
 				93DAFE491CFE53C900547CC4 /* ZeroTier One-Bridging-Header.h */,
-				932D472C1D138B0C004BCFE2 /* NetworkMonitor.swift */,
-				932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */,
-				932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */,
+				93D1676E1D57FD3800330C99 /* NetworkMonitor.h */,
+				93D1676F1D57FD3800330C99 /* NetworkMonitor.m */,
 				93DAFB261D3F0BEE004D5417 /* about.html */,
 				93D1675D1D54191C00330C99 /* NodeStatus.h */,
 				93D1675E1D54191C00330C99 /* NodeStatus.m */,
@@ -114,8 +114,10 @@
 				93D167651D54308200330C99 /* Network.m */,
 				93D167671D57E7EA00330C99 /* AboutViewController.h */,
 				93D167681D57E7EA00330C99 /* AboutViewController.m */,
+				932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */,
 				93D1676B1D57EB8400330C99 /* PreferencesViewController.h */,
 				93D1676C1D57EB8400330C99 /* PreferencesViewController.m */,
+				932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */,
 			);
 			path = "ZeroTier One";
 			sourceTree = "<group>";
@@ -197,10 +199,10 @@
 			buildActionMask = 2147483647;
 			files = (
 				93D167621D541BC200330C99 /* ServiceCom.m in Sources */,
-				932D472D1D138B0C004BCFE2 /* NetworkMonitor.swift in Sources */,
 				93326BDC1CE7C816005CA2AC /* AppDelegate.swift in Sources */,
 				93DAFE4B1CFE53CA00547CC4 /* AuthtokenCopy.m in Sources */,
 				9330F13B1CF534E500687EC8 /* NetworkInfoCell.swift in Sources */,
+				93D167701D57FD3800330C99 /* NetworkMonitor.m in Sources */,
 				93326BEA1CE7D9B9005CA2AC /* JoinNetworkViewController.swift in Sources */,
 				93326BEE1CE7DA30005CA2AC /* ShowNetworksViewController.swift in Sources */,
 				93D1675F1D54191C00330C99 /* NodeStatus.m in Sources */,

+ 5 - 5
ZeroTier One/Network.m

@@ -155,7 +155,7 @@ NSString *NetworkAllowDefaultKey = @"allowDefault";
         }
 
         if([aDecoder containsValueForKey:NetworkMtuKey]) {
-            _mtu = [aDecoder decodeIntegerForKey:NetworkMtuKey];
+            _mtu = (int)[aDecoder decodeIntegerForKey:NetworkMtuKey];
         }
 
         if([aDecoder containsValueForKey:NetworkNameKey]) {
@@ -163,7 +163,7 @@ NSString *NetworkAllowDefaultKey = @"allowDefault";
         }
 
         if([aDecoder containsValueForKey:NetworkNetconfKey]) {
-            _netconfRevision = [aDecoder decodeIntegerForKey:NetworkNetconfKey];
+            _netconfRevision = (int)[aDecoder decodeIntegerForKey:NetworkNetconfKey];
         }
 
         if([aDecoder containsValueForKey:NetworkNwidKey]) {
@@ -175,15 +175,15 @@ NSString *NetworkAllowDefaultKey = @"allowDefault";
         }
 
         if([aDecoder containsValueForKey:NetworkPortErrorKey]) {
-            _portError = [aDecoder decodeIntegerForKey:NetworkPortErrorKey];
+            _portError = (int)[aDecoder decodeIntegerForKey:NetworkPortErrorKey];
         }
 
         if([aDecoder containsValueForKey:NetworkStatusKey]) {
-            _status = [aDecoder decodeIntegerForKey:NetworkStatusKey];
+            _status = (enum NetworkStatus)[aDecoder decodeIntegerForKey:NetworkStatusKey];
         }
 
         if([aDecoder containsValueForKey:NetworkTypeKey]) {
-            _type = [aDecoder decodeIntegerForKey:NetworkTypeKey];
+            _type = (enum NetworkType)[aDecoder decodeIntegerForKey:NetworkTypeKey];
         }
 
         if([aDecoder containsValueForKey:NetworkAllowManagedKey]) {

+ 35 - 0
ZeroTier One/NetworkMonitor.h

@@ -0,0 +1,35 @@
+//
+//  NetworkMonitor.h
+//  ZeroTier One
+//
+//  Created by Grant Limberg on 8/7/16.
+//  Copyright © 2016 ZeroTier, Inc. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+extern NSString * const NetworkUpdateKey;
+extern NSString * const StatusUpdateKey;
+
+@class Network;
+
+@interface NetworkMonitor : NSObject
+{
+    NSMutableArray<Network*> *_savedNetworks;
+    NSArray<Network*> *_receivedNetworks;
+    NSMutableArray<Network*> *_allNetworks;
+
+    NSTimer *_timer;
+}
+
+- (id)init;
+- (void)dealloc;
+
+- (void)start;
+- (void)stop;
+
+- (void)updateNetworkInfo;
+
+- (void)deleteSavedNetwork:(NSString*)networkId;
+
+@end

+ 200 - 0
ZeroTier One/NetworkMonitor.m

@@ -0,0 +1,200 @@
+//
+//  NetworkMonitor.m
+//  ZeroTier One
+//
+//  Created by Grant Limberg on 8/7/16.
+//  Copyright © 2016 ZeroTier, Inc. All rights reserved.
+//
+
+#import "NetworkMonitor.h"
+#import "Network.h"
+#import "ServiceCom.h"
+#import "NodeStatus.h"
+
+NSString * const NetworkUpdateKey = @"com.zerotier.one.network-list";
+NSString * const StatusUpdateKey = @"com.zerotier.one.status";
+
+@interface NetworkMonitor (private)
+
+- (NSString*)dataFile;
+- (void)internal_updateNetworkInfo;
+- (NSInteger)findNetworkWithID:(UInt64)networkId;
+- (NSInteger)findSavedNetworkWithID:(UInt64)networkId;
+- (void)saveNetworks;
+
+@end
+
+@implementation NetworkMonitor
+
+- (id)init
+{
+    self = [super init];
+    if(self)
+    {
+        _savedNetworks = [NSMutableArray<Network*> array];
+        _receivedNetworks = [NSArray<Network*> array];
+        _allNetworks = [NSMutableArray<Network*> array];
+        _timer = nil;
+    }
+
+    return self;
+}
+
+- (void)dealloc
+{
+    [_timer invalidate];
+}
+
+- (void)start
+{
+    NSLog(@"ZeroTier monitor started");
+    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
+                                              target:self
+                                            selector:@selector(updateNetworkInfo)
+                                            userInfo:nil
+                                             repeats:YES];
+}
+
+- (void)stop
+{
+    NSLog(@"ZeroTier monitor stopped");
+    [_timer invalidate];
+    _timer = nil;
+}
+
+- (void)updateNetworkInfo
+{
+    NSString *filePath = [self dataFile];
+
+    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
+        NSArray<Network*> *networks = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
+
+        if(networks != nil) {
+            _savedNetworks = [networks mutableCopy];
+        }
+    }
+
+    [[ServiceCom sharedInstance] getNetworklist:^(NSArray<Network *> *networkList) {
+        _receivedNetworks = networkList;
+
+        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
+            [self internal_updateNetworkInfo];
+        }];
+    }];
+
+    [[ServiceCom sharedInstance] getNodeStatus:^(NodeStatus *status) {
+        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:status forKey:@"status"];
+
+        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
+            [[NSNotificationCenter defaultCenter] postNotificationName:StatusUpdateKey
+                                                                object:nil
+                                                              userInfo:userInfo];
+        }];
+    }];
+}
+
+- (void)deleteSavedNetwork:(NSString*)networkId
+{
+    UInt64 nwid = 0;
+    NSScanner *scanner = [NSScanner scannerWithString:networkId];
+    [scanner scanHexLongLong:&nwid];
+
+    NSInteger index = [self findNetworkWithID:nwid];
+
+    if(index != NSNotFound) {
+        [_allNetworks removeObjectAtIndex:index];
+    }
+
+    index = [self findSavedNetworkWithID:nwid];
+
+    if(index != NSNotFound) {
+        [_savedNetworks removeObjectAtIndex:index];
+    }
+
+    [self saveNetworks];
+}
+
+@end
+
+@implementation NetworkMonitor (private)
+- (NSString*)dataFile
+{
+    NSURL *appSupport = [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory
+                                                               inDomains:NSUserDomainMask] objectAtIndex:0];
+
+    appSupport = [[[appSupport URLByAppendingPathComponent:@"ZeroTier"] URLByAppendingPathComponent:@"One"] URLByAppendingPathComponent:@"networkinfo.dat"];
+    return appSupport.path;
+}
+
+- (void)internal_updateNetworkInfo
+{
+    NSMutableArray<Network*> *networks = [_savedNetworks mutableCopy];
+
+    for(Network *nw in _receivedNetworks) {
+        NSInteger index = [self findSavedNetworkWithID:nw.nwid];
+
+        if(index != NSNotFound) {
+            [networks setObject:nw atIndexedSubscript:index];
+        }
+        else {
+            [networks addObject:nw];
+        }
+    }
+
+    [networks sortUsingComparator:^NSComparisonResult(Network *obj1, Network *obj2) {
+        if(obj1.nwid > obj2.nwid) {
+            return true;
+        }
+        return false;
+    }];
+
+    @synchronized(_allNetworks) {
+        _allNetworks = networks;
+    }
+
+    [self saveNetworks];
+
+    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:networks forKey:@"networks"];
+
+    [[NSNotificationCenter defaultCenter] postNotificationName:NetworkUpdateKey
+                                                        object:nil
+                                                      userInfo:userInfo];
+}
+
+- (NSInteger)findNetworkWithID:(UInt64)networkId
+{
+    for(int i = 0; i < [_allNetworks count]; ++i) {
+        Network *nw = [_allNetworks objectAtIndex:i];
+
+        if(nw.nwid == networkId) {
+            return i;
+        }
+    }
+
+    return NSNotFound;
+}
+
+
+- (NSInteger)findSavedNetworkWithID:(UInt64)networkId
+{
+    for(int i = 0; i < [_savedNetworks count]; ++i) {
+        Network *nw = [_savedNetworks objectAtIndex:i];
+
+        if(nw.nwid == networkId) {
+            return i;
+        }
+    }
+
+    return NSNotFound;
+}
+
+- (void)saveNetworks
+{
+    NSString *filePath = [self dataFile];
+
+    @synchronized(_allNetworks) {
+        [NSKeyedArchiver archiveRootObject:_allNetworks toFile:filePath];
+    }
+}
+
+@end

+ 0 - 164
ZeroTier One/NetworkMonitor.swift

@@ -1,164 +0,0 @@
-//
-//  NetworkMonitor.swift
-//  ZeroTier One
-//
-//  Created by Grant Limberg on 6/16/16.
-//  Copyright © 2016 ZeroTier, Inc. All rights reserved.
-//
-
-import Cocoa
-
-let networkUpdateKey = "com.zerotier.one.network-list"
-let statusUpdateKey = "com.zerotier.one.status"
-
-class NetworkMonitor: NSObject {
-
-    var timer: NSTimer? = nil
-
-    var savedNetworks: [Network] = [Network]()
-    var receivedNetworks: [Network] = [Network]()
-    var allNetworks: [Network] = [Network]()
-
-    override init() {
-        super.init()
-    }
-
-    deinit {
-        timer?.invalidate()
-    }
-
-    func start() {
-        NSLog("ZeroTier monitor started")
-        timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
-                                                       target: self,
-                                                       selector: #selector(updateNetworkInfo),
-                                                       userInfo: nil,
-                                                       repeats: true)
-    }
-
-
-    func stop() {
-        NSLog("ZeroTier monitor stopped")
-        timer?.invalidate()
-        timer = nil
-    }
-
-    private func  dataFile() -> String {
-        var appSupport = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0]
-        appSupport = appSupport.URLByAppendingPathComponent("ZeroTier").URLByAppendingPathComponent("One").URLByAppendingPathComponent("networks.dat")
-        return appSupport.path!
-    }
-
-    func updateNetworkInfo() {
-        //NSLog("updateNetworkInfo")
-        let filePath = dataFile()
-
-        if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
-            let networks = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as! [Network]
-
-            self.savedNetworks.removeAll()
-
-            for n in networks {
-                self.savedNetworks.append(n)
-            }
-        }
-
-        ServiceCom.sharedInstance().getNetworklist() { (networkList) -> Void in
-            self.receivedNetworks = networkList
-
-            NSOperationQueue.mainQueue().addOperationWithBlock() { () -> Void in
-                self.internal_updateNetworkInfo()
-            }
-        }
-
-        ServiceCom.sharedInstance().getNodeStatus() { nodeStatus -> Void in
-            NSOperationQueue.mainQueue().addOperationWithBlock() { () -> Void in
-                let nc = NSNotificationCenter.defaultCenter()
-
-                nc.postNotificationName(statusUpdateKey, object: nil, userInfo: ["status": nodeStatus])
-            }
-        }
-    }
-
-    func deleteSavedNetwork(nwid: String) {
-        if let nwid = UInt64(nwid, radix: 16) {
-            let index = findNetworkWithID(nwid)
-
-            if index != NSNotFound {
-                allNetworks.removeAtIndex(index)
-            }
-
-            let index2 = findSavedNetworkWithID(nwid)
-
-            if index2 != NSNotFound {
-                savedNetworks.removeAtIndex(index2)
-            }
-        }
-
-        saveNetworks()
-    }
-
-    // Only to be called by updateNetworkInfo()
-    private func internal_updateNetworkInfo() {
-        var networks = self.savedNetworks
-
-        for nw in receivedNetworks {
-            let index = findSavedNetworkWithID(nw.nwid)
-
-            if index != NSNotFound {
-                networks[index] = nw
-            }
-            else {
-                networks.append(nw)
-            }
-        }
-
-        networks.sortInPlace({ (left, right) -> Bool in
-            if left.nwid < right.nwid {
-                return true
-            }
-
-            return false
-        })
-
-        objc_sync_enter(allNetworks)
-        allNetworks = networks
-        objc_sync_exit(allNetworks)
-
-        saveNetworks()
-
-        let nc = NSNotificationCenter.defaultCenter()
-
-        nc.postNotificationName(networkUpdateKey, object: nil, userInfo: ["networks": networks])
-    }
-
-    private func findNetworkWithID(nwid: UInt64) -> Int {
-        for (index, element) in allNetworks.enumerate() {
-
-            if element.nwid == nwid {
-                return index
-            }
-        }
-
-        return NSNotFound
-    }
-
-    private func findSavedNetworkWithID(nwid: UInt64) -> Int {
-        for (index, element) in savedNetworks.enumerate() {
-
-            if element.nwid == nwid {
-                return index
-            }
-        }
-
-        return NSNotFound
-    }
-
-    private func saveNetworks() {
-        let file = dataFile()
-
-        objc_sync_enter(allNetworks)
-        NSKeyedArchiver.archiveRootObject(self.allNetworks, toFile: file)
-        objc_sync_exit(allNetworks)
-    }
-}

+ 1 - 0
ZeroTier One/ZeroTier One-Bridging-Header.h

@@ -8,3 +8,4 @@
 #import "ServiceCom.h"
 #import "AboutViewController.h"
 #import "PreferencesViewController.h"
+#import "NetworkMonitor.h"