OSDN Git Service

HMAPIResponseをSwiftに変換した
authormasakih <masakih@users.sourceforge.jp>
Sat, 21 Jan 2017 12:30:51 +0000 (21:30 +0900)
committermasakih <masakih@users.sourceforge.jp>
Sat, 21 Jan 2017 12:30:51 +0000 (21:30 +0900)
KCD.xcodeproj/project.pbxproj
KCD/HMAPIResponse.h [deleted file]
KCD/HMAPIResponse.m [deleted file]
KCD/HMAPIResponse.swift [new file with mode: 0644]
KCD/HMJSONReciever.m
KCD/KCD-Bridging-Header.h

index ef3e90f..10dc92a 100644 (file)
                F4BDEB71187252F30069D0CE /* KCDTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4BDEB70187252F30069D0CE /* KCDTests.m */; };
                F4BDEB7B187253130069D0CE /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F4BDEB7A187253130069D0CE /* WebKit.framework */; };
                F4BEEE9F18D211280006F70C /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = F4BEEE9D18D211280006F70C /* Localizable.strings */; };
-               F4BEEFE91B0CE312004702B8 /* HMAPIResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = F4BEEFE81B0CE312004702B8 /* HMAPIResponse.m */; };
                F4BEEFFC1B11A5A7004702B8 /* HMExternalBrowserWindowController.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4BEEFFE1B11A5A7004702B8 /* HMExternalBrowserWindowController.xib */; };
                F4BEEFFF1B11A5C2004702B8 /* HMMediumShipViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4BEF0011B11A5C2004702B8 /* HMMediumShipViewController.xib */; };
                F4BEF0021B11A5CC004702B8 /* HMFleetMinimumViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4BEF0041B11A5CC004702B8 /* HMFleetMinimumViewController.xib */; };
                F4C6686C1C5451ED00601AFB /* HMStrengthenListViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4C6686E1C5451ED00601AFB /* HMStrengthenListViewController.xib */; };
                F4C6686F1C54524900601AFB /* HMVerticalFleetViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4C668711C54524900601AFB /* HMVerticalFleetViewController.xib */; };
                F4C668721C54525300601AFB /* HMCombileViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4C668741C54525300601AFB /* HMCombileViewController.xib */; };
+               F4CF25A81E325ABA00C02A66 /* HMAPIResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4CF25A71E325ABA00C02A66 /* HMAPIResponse.swift */; };
                F4D05BC61E0ABD6800688D66 /* HMSlotItemWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4D05BC51E0ABD6800688D66 /* HMSlotItemWindowController.swift */; };
                F4D05BC81E0C0DA100688D66 /* HMAirBaseWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4D05BC71E0C0DA100688D66 /* HMAirBaseWindowController.swift */; };
                F4D05BCA1E0CADA100688D66 /* HMExternalBrowserWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4D05BC91E0CADA100688D66 /* HMExternalBrowserWindowController.swift */; };
                F4BEEEA118D211360006F70C /* ja */ = {isa = PBXFileReference; lastKnownFileType = text; name = ja; path = ja.lproj/Localizable.strings.sed; sourceTree = "<group>"; };
                F4BEEEA418D211500006F70C /* ja */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.make; name = ja; path = ja.lproj/Makefile; sourceTree = "<group>"; };
                F4BEEEA718D323520006F70C /* Makefile */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = SOURCE_ROOT; };
-               F4BEEFE71B0CE312004702B8 /* HMAPIResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HMAPIResponse.h; sourceTree = "<group>"; };
-               F4BEEFE81B0CE312004702B8 /* HMAPIResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HMAPIResponse.m; sourceTree = "<group>"; };
                F4C041B91875CAF5009273EB /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
                F4C1190318A71AEA005D5B25 /* HMJSONReciever.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HMJSONReciever.h; sourceTree = "<group>"; };
                F4C1190418A71AEA005D5B25 /* HMJSONReciever.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HMJSONReciever.m; sourceTree = "<group>"; };
                F4C5A2331C37F87500533FB6 /* EquipmentEnhancementListBuilder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = EquipmentEnhancementListBuilder; sourceTree = BUILT_PRODUCTS_DIR; };
                F4C5A2351C37F87600533FB6 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
                F4C5A23D1C380E0400533FB6 /* HMEnhancementListItem.plist */ = {isa = PBXFileReference; lastKnownFileType = file.bplist; path = HMEnhancementListItem.plist; sourceTree = "<group>"; };
+               F4CF25A71E325ABA00C02A66 /* HMAPIResponse.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMAPIResponse.swift; sourceTree = "<group>"; };
                F4D05BC51E0ABD6800688D66 /* HMSlotItemWindowController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMSlotItemWindowController.swift; sourceTree = "<group>"; };
                F4D05BC71E0C0DA100688D66 /* HMAirBaseWindowController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMAirBaseWindowController.swift; sourceTree = "<group>"; };
                F4D05BC91E0CADA100688D66 /* HMExternalBrowserWindowController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMExternalBrowserWindowController.swift; sourceTree = "<group>"; };
                                F4C1190418A71AEA005D5B25 /* HMJSONReciever.m */,
                                F4C1190618A746EB005D5B25 /* HMJSONTracker.h */,
                                F4C1190718A746EB005D5B25 /* HMJSONTracker.m */,
-                               F4BEEFE71B0CE312004702B8 /* HMAPIResponse.h */,
-                               F4BEEFE81B0CE312004702B8 /* HMAPIResponse.m */,
+                               F4CF25A71E325ABA00C02A66 /* HMAPIResponse.swift */,
                                F494DC5D18C30AE100AE97E4 /* HMMissionStatus.h */,
                                F494DC5E18C30AE100AE97E4 /* HMMissionStatus.m */,
                                F494DC6B18CC054800AE97E4 /* HMNyukyoDockStatus.h */,
                                F4E5FF0C1E1645280026868C /* HMScreenshotListViewController.swift in Sources */,
                                F44BC71B1E29DCB4004644E3 /* HMMemberKDockCommand.swift in Sources */,
                                F4AC136F1E0963DB00851147 /* HMProgressPanel.swift in Sources */,
-                               F4BEEFE91B0CE312004702B8 /* HMAPIResponse.m in Sources */,
                                F4AA592A1E1D1387001667AF /* HMIgnoreZeroTransformer.swift in Sources */,
                                F4AC136D1E0802C000851147 /* HMPreferencePanelController.swift in Sources */,
                                F44BC6E91E232B15004644E3 /* HMKaisouLockCommand.swift in Sources */,
                                F44BC6C91E22314B004644E3 /* HMUnknownComand.swift in Sources */,
                                F44BC6DD1E228345004644E3 /* HMUpdateQuestListCommand.swift in Sources */,
                                F495462B1B14CBA600E0D8D0 /* HMBookmarkManager.m in Sources */,
+                               F4CF25A81E325ABA00C02A66 /* HMAPIResponse.swift in Sources */,
                                F43F3D521A39CC7500D6DAF7 /* HMKCMasterSlotItemObject.m in Sources */,
                                F44BC6F71E23DA4A004644E3 /* HMDestroyShipCommand.swift in Sources */,
                                F4AA59141E1C951F001667AF /* HMTimerCountFormatter.swift in Sources */,
diff --git a/KCD/HMAPIResponse.h b/KCD/HMAPIResponse.h
deleted file mode 100644 (file)
index 9f59fa2..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-//
-//  HMAPIResponse.h
-//  KCD
-//
-//  Created by Hori,Masaki on 2015/05/21.
-//  Copyright (c) 2015年 Hori,Masaki. All rights reserved.
-//
-
-#import <Foundation/Foundation.h>
-
-@interface HMAPIResponse : NSObject
-
-@property (readonly) NSString *api;
-@property (nonatomic, readonly) NSDictionary<NSString *, NSString *> *parameter;
-@property (nonatomic, readonly) id json;
-@property (readonly) NSDate *date;
-@property (nonatomic, readonly) BOOL success;
-@property (readonly) NSString *errorString;
-
-#if ENABLE_JSON_LOG
-@property (nonatomic, copy) NSArray *argumentArray;
-#endif
-
-+ (instancetype)apiResponseWithRequest:(NSURLRequest *)request data:(NSData *)data;
-- (instancetype)initWithRequest:(NSURLRequest *)request data:(NSData *)data;
-
-@end
diff --git a/KCD/HMAPIResponse.m b/KCD/HMAPIResponse.m
deleted file mode 100644 (file)
index 7bc8c4f..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-//
-//  HMAPIResponse.m
-//  KCD
-//
-//  Created by Hori,Masaki on 2015/05/21.
-//  Copyright (c) 2015年 Hori,Masaki. All rights reserved.
-//
-
-#import "HMAPIResponse.h"
-
-#import "HMAppDelegate.h"
-
-
-@interface HMAPIResponse ()
-@property (copy, readwrite) NSString *api;
-@property (nonatomic, copy, readwrite) NSDictionary *parameter;
-@property (nonatomic, strong, readwrite) id json;
-@property (strong, readwrite) NSDate *date;
-@property (nonatomic, readwrite) BOOL success;
-@property (copy, readwrite) NSString *errorString;
-
-@property (nonatomic, copy) NSData *jsonData;
-@property (nonatomic, copy) NSString *paramString;
-
-@end
-
-@implementation HMAPIResponse
-
-+ (instancetype)apiResponseWithRequest:(NSURLRequest *)request data:(NSData *)data
-{
-       return [[self alloc] initWithRequest:request data:data];
-}
-- (instancetype)initWithRequest:(NSURLRequest *)request data:(NSData *)data
-{
-       self = [super init];
-       if(self) {
-               NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
-               if(![string hasPrefix:@"svdata="]) {
-                       HMAppDelegate *appDelegate = [[NSApplication sharedApplication] delegate];
-                       [appDelegate logLineReturn:@"recive data has not prefix svdata=. api -> %@.", request.URL.path];
-                       [appDelegate logLineReturn:@"Original strings -> %@", string];
-                       return nil;
-               }
-               string = [string substringFromIndex:strlen("svdata=")];
-               _jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
-               
-               NSData *requestBodyData = [request HTTPBody];
-               _paramString = [[NSString alloc] initWithData:requestBodyData encoding:NSUTF8StringEncoding];
-               
-               _api = request.URL.path;
-               _date = [NSDate dateWithTimeIntervalSinceNow:0];
-       }
-       
-       return self;
-}
-
-- (void)parseJSON
-{
-       NSError *error = nil;
-       id json = [NSJSONSerialization JSONObjectWithData:self.jsonData
-                                                                                         options:NSJSONReadingAllowFragments
-                                                                                               error:&error];
-       if(error) {
-               HMAppDelegate *appDelegate = [[NSApplication sharedApplication] delegate];
-               [appDelegate logLineReturn:@"Fail decode JSON data %@", error];
-               return;
-       }
-       if(![json isKindOfClass:[NSDictionary class]]) {
-               self.errorString = @"JSON is NOT NSDictionary.";
-               return;
-       }
-       self.json = json;
-    self.success = YES;
-    if(![[json objectForKey:@"api_result"] isEqual:@1]) {
-        self.success = NO;
-    }
-}
-
-- (id)json
-{
-       if(_json) return _json;
-       
-       [self parseJSON];
-       return _json;
-}
-
-- (void)parseParameter
-{
-    NSString *unescape = self.paramString.stringByRemovingPercentEncoding;
-       NSArray *pair = [unescape componentsSeparatedByString:@"&"];
-       NSMutableDictionary *dict = [NSMutableDictionary new];
-       for(NSString *p in pair) {
-               NSArray *pp = [p componentsSeparatedByString:@"="];
-               if([pp count] != 2) {
-                       NSLog(@"API (%@): Bad Argument: pair is odd.", self.api);
-                       continue;
-               }
-               [dict setObject:pp[1] forKey:pp[0]];
-       }
-       _parameter = dict;
-       
-#if ENABLE_JSON_LOG
-       NSMutableArray *array = [NSMutableArray new];
-       for(NSString *p in pair) {
-               NSArray *pp = [p componentsSeparatedByString:@"="];
-               if([pp count] != 2) {
-                       NSLog(@"API (%@): Bad Argument: pair is odd.", self.api);
-                       continue;
-               }
-               [array addObject:@{@"key": pp[0], @"value": pp[1]}];
-       }
-       self.argumentArray = array;
-#endif
-       
-}
-- (NSDictionary *)parameter
-{
-       if(_parameter) return _parameter;
-       
-       [self parseParameter];
-       return _parameter;
-}
-#if ENABLE_JSON_LOG
-- (NSArray *)argumentArray
-{
-       if(_argumentArray) return _argumentArray;
-       
-       [self parseParameter];
-       return _argumentArray;
-}
-#endif
-
-- (BOOL)success
-{
-       if(_json) return _success;
-       
-       [self parseJSON];
-       return _success;
-}
-@end
diff --git a/KCD/HMAPIResponse.swift b/KCD/HMAPIResponse.swift
new file mode 100644 (file)
index 0000000..c1dac63
--- /dev/null
@@ -0,0 +1,87 @@
+//
+//  HMAPIResponse.swift
+//  KCD
+//
+//  Created by Hori,Masaki on 2017/01/20.
+//  Copyright © 2017年 Hori,Masaki. All rights reserved.
+//
+
+import Cocoa
+
+fileprivate func parseJSON(_ data: Data) -> [String:Any]? {
+    guard let j = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]),
+        let json = j as? [String:Any]
+        else { return nil }
+    return json
+}
+fileprivate func parseParameter(_ string: String) -> [String:String] {
+    let piar = string.components(separatedBy: "&")
+    return piar.reduce(Dictionary<String,String>()) {
+        var dict = $0
+        let p = $1.components(separatedBy: "=")
+        if p.count == 2 {
+            dict[p[0]] = p[1]
+        }
+        return dict
+    }
+}
+
+class HMAPIResponse: NSObject {
+    let api: String
+    let parameter: [String:String]
+    let json: [String:Any]
+    let date: Date
+    var success: Bool {
+        if let r = json["api_result"] as? Int { return r == 1 }
+        return false
+    }
+    
+    #if ENABLE_JSON_LOG
+    let argumentArray: [[String:String]]
+    #endif
+    
+    init?(request: NSURLRequest, data: Data) {
+        date = Date()
+        
+        let prefix = "svdata="
+        guard let string = String(data: data, encoding: .utf8),
+            string.hasPrefix(prefix)
+            else {
+                print("data is wrong")
+                return nil
+        }
+        let start = string.index(string.startIndex, offsetBy: prefix.characters.count)
+        let jsonString = string[start..<string.endIndex]
+        guard let jsonData = jsonString.data(using: .utf8),
+            let j = parseJSON(jsonData)
+            else {
+                print("Can not parse JSON")
+                return nil
+        }
+        json = j
+        
+        guard let requestBodyData = request.httpBody,
+            let paramStr = String(data: requestBodyData, encoding: .utf8),
+            let unescaped = paramStr.removingPercentEncoding
+            else {
+                print("Can not parse Parameter")
+                return nil
+        }
+        parameter = parseParameter(unescaped)
+        
+        guard let a = request.url?.path
+            else {
+                print("URLRequest is wrong")
+                return nil
+        }
+        api = a
+        
+        #if ENABLE_JSON_LOG
+            argumentArray = parameter.map { (key, value) in
+                ["key": key, "value": value]
+            }
+        #endif
+        
+        super.init()
+    }
+}
index d3b9167..305f71e 100644 (file)
@@ -12,7 +12,6 @@
 
 #import "CustomHTTPProtocol.h"
 #import "HMAppDelegate.h"
-#import "HMAPIResponse.h"
 
 
 @interface HMJSONReciever ()
@@ -78,7 +77,7 @@
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [[NSApp delegate] logLineReturn:@"body -> \n%@", string];
 #else
-       HMAPIResponse *apiResult = [HMAPIResponse apiResponseWithRequest:protocol.request data:data];
+    HMAPIResponse *apiResult = [[HMAPIResponse alloc] initWithRequest:protocol.request data:data];
        if(apiResult) {
                [self.queueu enqueue:apiResult];
        }
index 8e34db7..3c1b51e 100644 (file)
@@ -23,8 +23,6 @@
 
 #import "HMScreenshotModel.h"
 
-#import "HMAPIResponse.h"
-
 
 // Core Data
 #import "HMCoreDataManager.h"