VerificationManager.m 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. //
  2. // VerificationManager.m
  3. // Filmage Screen
  4. //
  5. // Created by 朱东勇 on 2018/2/8.
  6. // Copyright © 2018年 kdan mobile. All rights reserved.
  7. //
  8. #import "VerificationManager.h"
  9. #import "NSNULL+Filtration.h"
  10. #import "NSObject+DeviceInfo.h"
  11. #import "JSONKit.h"
  12. #import "ASIFormDataRequest.h"
  13. const NSString *kDeviceVerifyFinishNotification = @"kDeviceVerifyFinishNotification";
  14. const NSString *kDeviceActivateStatusChangeNotification = @"kDeviceActivateNotification";
  15. static VerificationManager *__verificationManager = nil;
  16. @interface VerificationManager ()
  17. @property (nonatomic, strong) NSTimer *timer;
  18. @property (nonatomic) BOOL isVerifing;
  19. @end
  20. @implementation VerificationManager
  21. + (VerificationManager*)manager {
  22. #if VERSION_DMG
  23. if (!__verificationManager)
  24. __verificationManager = [[VerificationManager alloc] init];
  25. #else
  26. return nil;
  27. #endif
  28. return __verificationManager;
  29. }
  30. + (VerificationManager*)defaultManager {
  31. #if VERSION_DMG
  32. if (!__verificationManager)
  33. __verificationManager = [[VerificationManager alloc] init];
  34. #else
  35. return nil;
  36. #endif
  37. return __verificationManager;
  38. }
  39. - (instancetype)init {
  40. self = [super init];
  41. self.autoVerification = YES;
  42. #if !DEBUG // 非测试环境时
  43. #if kTestMode // 测试模式时 报错
  44. //#error 服务器未切换到正式服务器!
  45. #endif
  46. #endif
  47. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  48. [self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  49. }];
  50. });
  51. return self;
  52. }
  53. #pragma mark - Setter & Getter
  54. - (ActivityStatus)status {
  55. return self.detailInfo.status;
  56. }
  57. - (BOOL)needUpgradeLicense {
  58. if ([self.detailInfo[@"device"][@"product_code"] isEqualToString:@"com.brother.pdfreaderpro.mac.product_1"] ||
  59. [self.detailInfo[@"device"][@"product_code"] isEqualToString:@"com.brother.pdfreaderpro.cross.platform.product_1"]) {
  60. return YES;
  61. }
  62. // if ([self.detailInfo[@"subscription"][@"product"][@"code"] isEqualToString:@"com.brother.pdfreaderpro.mac.product_1"]) {
  63. // return YES;
  64. // }
  65. return NO;
  66. }
  67. - (BOOL)secondTrialEnabled {
  68. return self.detailInfo.repeatTrial;
  69. }
  70. - (NSInteger)trialTimes {
  71. return self.detailInfo.trialTimes;
  72. }
  73. - (NSString *)licenseCode {
  74. return self.detailInfo.licenseCode;
  75. }
  76. - (NSString *)email {
  77. return self.detailInfo.email?:@"";
  78. }
  79. - (NSString *)accountName {
  80. return self.detailInfo.accountName;
  81. }
  82. - (NSString*)udid {
  83. //#if DEBUG
  84. // NSString *cachePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"uuid.plist"];
  85. // NSMutableDictionary *info = [[NSDictionary dictionaryWithContentsOfFile:cachePath] mutableCopy];
  86. //
  87. // if (!info) {
  88. // info = [NSMutableDictionary dictionary];
  89. //
  90. // [info setValue:[NSString stringWithFormat:@"TestInvate%.0f", [NSDate date].timeIntervalSince1970]
  91. // forKey:@"uuid"];
  92. //
  93. //
  94. // [[NSFileManager defaultManager] createDirectoryAtPath:NSTemporaryDirectory()
  95. // withIntermediateDirectories:YES
  96. // attributes:nil
  97. // error:nil];
  98. // [info writeToFile:cachePath atomically:YES];
  99. // }
  100. //
  101. // return info[@"uuid"]?:(GetHardwareUUID()?:@"");
  102. //#endif
  103. return GetHardwareUUID()?:@"";
  104. }
  105. - (NSString*)bundleIdentify {
  106. return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"]?:@"";
  107. }
  108. - (void)setDetailInfo:(NSDictionary *)detailInfo {
  109. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  110. [defaults setValue:[detailInfo JSONData]
  111. forKey:@"detailInfo"];
  112. [defaults synchronize];
  113. }
  114. - (NSDictionary*)detailInfo {
  115. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  116. return [[[defaults valueForKey:@"detailInfo"] objectFromJSONData] filterNullObject];
  117. }
  118. //
  119. //- (void)setIsTest:(BOOL)isTest {
  120. // _isTest = isTest;
  121. //
  122. // [self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  123. //
  124. // }];
  125. //}
  126. - (void)setAutoVerification:(BOOL)autoVerification {
  127. _autoVerification = autoVerification;
  128. [self restartTimer];
  129. }
  130. #pragma mark - Timer
  131. - (void)restartTimer {
  132. if (self.timer)
  133. [self.timer invalidate];
  134. self.timer = nil;
  135. if (self.autoVerification &&
  136. self.status != ActivityStatusNone) {
  137. self.timer = [NSTimer scheduledTimerWithTimeInterval:60 * 60//一个小时更新一次
  138. target:self
  139. selector:@selector(verificationFire)
  140. userInfo:nil
  141. repeats:NO];
  142. }
  143. }
  144. - (void)verificationFire {
  145. [self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  146. }];
  147. }
  148. #pragma mark - Interface
  149. - (void)activateDeviceWithInfo:(NSDictionary*)info
  150. complention:(ActivityComplention)complention {
  151. if (![info[@"cdkey"] length]) {
  152. //激活码为空
  153. NSError *error = [NSError errorWithDomain:@""
  154. code:ActivityErrorTypeCDKeyEmpty
  155. userInfo:nil];
  156. if (complention)
  157. complention(NO, nil, error);
  158. return;
  159. }
  160. if (![self isValidLicenseCode:info[@"cdkey"]]) {
  161. //激活码格式不正确
  162. NSError *error = [NSError errorWithDomain:@"激活失败"
  163. code:ActivityErrorTypeFormatError
  164. userInfo:nil];
  165. if (complention)
  166. complention(NO, @{@"errors":@"FormatError"}, error);
  167. return;
  168. }
  169. __block ActivityComplention tComplention = complention;
  170. __block VerificationManager *weak_self = self;
  171. //Process Params
  172. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  173. if (!app_version.length)
  174. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  175. NSDictionary *params =
  176. @{
  177. @"data":@{
  178. //激活信息
  179. @"subscription":@{
  180. @"app_code":[self bundleIdentify]?:@"",
  181. @"email":info[@"email"]?:@"",
  182. @"cdkey":info[@"cdkey"]?:@"",
  183. },
  184. //设备信息
  185. @"device":@{
  186. @"unique_sn":[self udid]?:@"",
  187. @"model":GetProductName()?:@"",
  188. @"os":GetSystemVersion()?:@"",
  189. @"time_zone":[[NSTimeZone localTimeZone] localizedName:NSTimeZoneNameStyleShortDaylightSaving locale:[NSLocale currentLocale]]?:@"",
  190. @"language":[[NSLocale currentLocale] localeIdentifier]?:@"",
  191. @"app_version":app_version?:@"",
  192. @"platform":@"DMG"
  193. }
  194. }
  195. };
  196. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  197. //Send Request
  198. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/auth_devices/activate"];
  199. NSURL *url = [NSURL URLWithString:urlString];
  200. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  201. request.requestMethod = @"POST";
  202. [request setPostBody:postData];
  203. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  204. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  205. postLength, @"Content-Length", nil];
  206. request.defaultResponseEncoding = NSUTF8StringEncoding;
  207. // [request setAuthenticationScheme:@"https"];//设置验证方式
  208. // [request setValidatesSecureCertificate:NO];//设置验证证书
  209. [request setRequestHeaders:requestHeaders];
  210. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  211. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  212. __block void(^processRequest)(void) = ^{
  213. dispatch_async(dispatch_get_main_queue(), ^{
  214. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  215. NSError *error = request.error;
  216. if (info && [info isKindOfClass:[NSDictionary class]]) {
  217. if ([info valueForKey:@"errors"]) {
  218. NSString *detailKey = [[info[@"errors"] firstObject] valueForKey:@"detail_key"];
  219. if ([detailKey isEqualToString:@"exceed_max_device_num"]) {
  220. error = [NSError errorWithDomain:@"激活失败"
  221. code:ActivityErrorTypeOutNumber
  222. userInfo:info];
  223. }else if ([detailKey isEqualToString:@"invalid_activate_info"]) {
  224. error = [NSError errorWithDomain:@"激活失败"
  225. code:ActivityErrorTypeInvalidInfo
  226. userInfo:info];
  227. }else if ([detailKey isEqualToString:@"invalid_license_key"]) {
  228. error = [NSError errorWithDomain:@"激活失败"
  229. code:ActivityErrorTypeCDKeyNotExist
  230. userInfo:info];
  231. }else if ([detailKey isEqualToString:@"license_not_match_product"]) {
  232. error = [NSError errorWithDomain:@"激活失败"
  233. code:ActivityErrorTypeNotMatchProduct
  234. userInfo:info];
  235. }else if ([detailKey isEqualToString:@"license_expired"]) {
  236. error = [NSError errorWithDomain:@"激活失败"
  237. code:ActivityErrorTypeCDKeyExpire
  238. userInfo:info];
  239. }else {
  240. error = [NSError errorWithDomain:@"激活失败"
  241. code:ActivityErrorTypeUnknow
  242. userInfo:info];
  243. }
  244. }else if ([info valueForKey:@"error"]) {
  245. error = [NSError errorWithDomain:@"激活失败"
  246. code:ActivityErrorTypeUnknow
  247. userInfo:info];
  248. }
  249. }else {
  250. if(error) {
  251. error = [NSError errorWithDomain:error.domain code:ActivityErrorTypeNetworkDisable userInfo:error.userInfo];
  252. } else {
  253. error = [NSError errorWithDomain:@"激活失败"
  254. code:ActivityErrorTypeUnknow
  255. userInfo:@{}];
  256. }
  257. }
  258. if (!error) {
  259. NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
  260. for (NSString *key in info[@"data"]) {
  261. [dic setValue:info[@"data"][key] forKey:key];
  262. }
  263. weak_self.detailInfo = dic;
  264. NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
  265. [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
  266. object:self
  267. userInfo:info];
  268. }
  269. [weak_self restartTimer];
  270. if (tComplention)
  271. tComplention(weak_self.status, info, error);
  272. });
  273. };
  274. [request setFailedBlock:^{
  275. processRequest();
  276. }];
  277. [request setCompletionBlock:^{
  278. processRequest();
  279. }];
  280. [request startAsynchronous];
  281. }
  282. - (void)verificationWithComplention:(ActivityComplention)complention {
  283. __block ActivityComplention tComplention = complention;
  284. __block VerificationManager *weak_self = self;
  285. if (!self.isVerifing) {
  286. self.isVerifing = YES;
  287. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  288. //Process Params
  289. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  290. if (!app_version.length)
  291. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  292. NSString *platform = @"DMG";
  293. #if VERSION_FREE
  294. #if VERSION_DMG
  295. #else
  296. platform = @"AppleStore";
  297. #endif
  298. #else
  299. platform = @"AppleStorePro";
  300. #endif
  301. NSDictionary *params =
  302. @{
  303. @"data":@{
  304. //验证信息
  305. @"subscription":@{
  306. @"app_code":[self bundleIdentify]?:@"",
  307. // @"email":info[@"email"]?:@"",
  308. // @"cdkey":info[@"cdkey"]?:@"",
  309. },
  310. //设备信息
  311. @"device":@{
  312. @"unique_sn":[self udid]?:@"",
  313. @"model":GetProductName()?:@"",
  314. @"os":GetSystemVersion()?:@"",
  315. @"time_zone":[[NSTimeZone localTimeZone] localizedName:NSTimeZoneNameStyleShortDaylightSaving locale:[NSLocale currentLocale]]?:@"",
  316. @"language":[[NSLocale currentLocale] localeIdentifier]?:@"",
  317. @"app_version":app_version?:@"",
  318. @"platform":platform?:@"AppleStore"
  319. }
  320. }
  321. };
  322. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  323. //Send Request
  324. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/auth_devices/verify"];
  325. NSURL *url = [NSURL URLWithString:urlString];
  326. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  327. request.requestMethod = @"POST";
  328. [request setPostBody:postData];
  329. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  330. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  331. postLength, @"Content-Length", nil];
  332. // [request setAuthenticationScheme:@"https"];//设置验证方式
  333. // [request setValidatesSecureCertificate:NO];//设置验证证书
  334. [request setRequestHeaders:requestHeaders];
  335. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  336. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  337. __block void(^processRequest)(void) = ^{
  338. dispatch_async(dispatch_get_main_queue(), ^{
  339. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  340. ActivityStatus status = weak_self.status;
  341. if ([info valueForKey:@"data"] &&
  342. [[info valueForKey:@"data"] valueForKey:@"device"]) {
  343. ActivityStatus tStatus = [(NSDictionary*)info[@"data"] status];
  344. //存储信息,并发送更新通知
  345. weak_self.detailInfo = info[@"data"];
  346. // if (status != tStatus ||
  347. // [[info valueForKey:@"data"] valueForKey:@"invite"]) {
  348. //发送通知
  349. NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
  350. [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
  351. object:weak_self
  352. userInfo:info];
  353. // }
  354. }
  355. [[NSNotificationCenter defaultCenter] postNotificationName:(NSString *)kDeviceVerifyFinishNotification
  356. object:nil
  357. userInfo:nil];
  358. weak_self.isVerifing = NO;
  359. //重置计时器
  360. [weak_self restartTimer];
  361. if (tComplention)
  362. tComplention(weak_self.status, info, request.error);
  363. });
  364. };
  365. [request setFailedBlock:^{
  366. processRequest();
  367. }];
  368. [request setCompletionBlock:^{
  369. processRequest();
  370. }];
  371. [request startAsynchronous];
  372. });
  373. }else {
  374. __block void(^waitBlock)(void) = ^{
  375. if (weak_self.isVerifing) {
  376. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  377. waitBlock();
  378. });
  379. }else {
  380. if (tComplention)
  381. tComplention(weak_self.status, @{@"data":weak_self.detailInfo?:@{}}, nil);
  382. waitBlock = NULL;
  383. }
  384. };
  385. waitBlock();
  386. }
  387. }
  388. - (void)trialForDays:(float)days
  389. complention:(ActivityComplention)complention {
  390. [self trialForDays:days email:nil name:nil complention:complention];
  391. }
  392. - (void)trialForDays:(float)days
  393. email:(NSString*)email
  394. name:(NSString*)name
  395. complention:(ActivityComplention)complention {
  396. __block ActivityComplention tComplention = complention;
  397. __block VerificationManager *weak_self = self;
  398. //Process Params
  399. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  400. if (!app_version.length)
  401. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  402. NSDictionary *params =
  403. @{
  404. @"data":@{
  405. //激活信息
  406. @"subscription":@{
  407. @"app_code":[self bundleIdentify]?:@"",
  408. @"trail_days":@(MAX(days, 1)),
  409. @"email":email?:@"",
  410. @"contact_name":name?:@""
  411. },
  412. //设备信息
  413. @"device":@{
  414. @"unique_sn":[self udid]?:@"",
  415. @"model":GetProductName()?:@"",
  416. @"os":GetSystemVersion()?:@"",
  417. @"time_zone":[[NSTimeZone localTimeZone] localizedName:NSTimeZoneNameStyleShortDaylightSaving locale:[NSLocale currentLocale]]?:@"",
  418. @"language":[[NSLocale currentLocale] localeIdentifier]?:@"",
  419. @"app_version":app_version?:@""
  420. }
  421. }
  422. };
  423. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  424. //Send Request
  425. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/auth_devices/trial"];
  426. NSURL *url = [NSURL URLWithString:urlString];
  427. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  428. request.requestMethod = @"POST";
  429. [request setPostBody:postData];
  430. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  431. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  432. postLength, @"Content-Length", nil];
  433. request.defaultResponseEncoding = NSUTF8StringEncoding;
  434. // [request setAuthenticationScheme:@"https"];//设置验证方式
  435. // [request setValidatesSecureCertificate:NO];//设置验证证书
  436. [request setRequestHeaders:requestHeaders];
  437. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  438. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  439. __block void(^processRequest)(void) = ^{
  440. dispatch_async(dispatch_get_main_queue(), ^{
  441. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  442. ActivityStatus status = weak_self.status;
  443. if ([info valueForKey:@"data"] &&
  444. [[info valueForKey:@"data"] valueForKey:@"device"]) {
  445. ActivityStatus tStatus = [(NSDictionary*)info[@"data"] status];
  446. //存储信息,并发送更新通知
  447. NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
  448. for (NSString *key in info[@"data"]) {
  449. [dic setValue:info[@"data"][key] forKey:key];
  450. }
  451. weak_self.detailInfo = dic;
  452. if (status != tStatus) {
  453. //发送通知
  454. NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
  455. [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
  456. object:self
  457. userInfo:info];
  458. }
  459. }
  460. //重置计时器
  461. [weak_self restartTimer];
  462. if (tComplention)
  463. tComplention(weak_self.status, info, request.error);
  464. });
  465. };
  466. [request setFailedBlock:^{
  467. processRequest();
  468. }];
  469. [request setCompletionBlock:^{
  470. processRequest();
  471. }];
  472. [request startAsynchronous];
  473. }
  474. - (void)getCodeWithEmail:(NSString*)email
  475. complention:(ActivityComplention)complention {
  476. __block ActivityComplention tComplention = complention;
  477. __block VerificationManager *weak_self = self;
  478. //Process Params
  479. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  480. if (!app_version.length)
  481. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  482. NSString *platform = @"DMG";
  483. #ifdef AppStore_Version
  484. #if Lite_Version
  485. platform = @"AppleStore";
  486. #else
  487. platform = @"AppleStorePro";
  488. #endif
  489. #endif
  490. NSDictionary *params =
  491. @{
  492. @"data":@{
  493. @"app_code":[self bundleIdentify]?:@"",
  494. @"email":email?:@"",
  495. @"unique_sn":[self udid]?:@"",
  496. @"platform":platform?:@"AppleStore"
  497. }
  498. };
  499. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  500. //Send Request
  501. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/getCode"];
  502. NSURL *url = [NSURL URLWithString:urlString];
  503. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  504. request.requestMethod = @"POST";
  505. [request setPostBody:postData];
  506. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  507. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  508. postLength, @"Content-Length", nil];
  509. request.defaultResponseEncoding = NSUTF8StringEncoding;
  510. // [request setAuthenticationScheme:@"https"];//设置验证方式
  511. // [request setValidatesSecureCertificate:NO];//设置验证证书
  512. [request setRequestHeaders:requestHeaders];
  513. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  514. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  515. __block void(^processRequest)(void) = ^{
  516. dispatch_async(dispatch_get_main_queue(), ^{
  517. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  518. if ([info valueForKey:@"data"] &&
  519. [[info valueForKey:@"data"] valueForKey:@"email"] &&
  520. [[info valueForKey:@"data"] valueForKey:@"share_code"]) {
  521. //存储信息,并发送更新通知
  522. NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
  523. [dic setValue:info[@"data"] forKey:@"invite"];
  524. weak_self.detailInfo = dic;
  525. [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  526. }];
  527. }
  528. //重置计时器
  529. [weak_self restartTimer];
  530. if (tComplention)
  531. tComplention(weak_self.status, info, request.error);
  532. });
  533. };
  534. [request setFailedBlock:^{
  535. processRequest();
  536. }];
  537. [request setCompletionBlock:^{
  538. processRequest();
  539. }];
  540. [request startAsynchronous];
  541. }
  542. //使用邀请码
  543. - (void)userCode:(NSString*)code
  544. complention:(ActivityComplention)complention {
  545. __block ActivityComplention tComplention = complention;
  546. __block VerificationManager *weak_self = self;
  547. //Process Params
  548. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  549. if (!app_version.length)
  550. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  551. BOOL iszhcn = !([NSLocalizedString(@"Language", nil) isEqualToString:@"English"] &&
  552. [NSLocalizedString(@"Language", nil) isEqualToString:@"Français"]);
  553. NSString *platform = @"DMG";
  554. #ifdef AppStore_Version
  555. #if Lite_Version
  556. platform = @"AppleStore";
  557. #else
  558. platform = @"AppleStorePro";
  559. #endif
  560. #endif
  561. NSDictionary *params =
  562. @{
  563. @"data":@{
  564. @"app_code":[self bundleIdentify]?:@"",
  565. @"code":code?:@"",
  566. @"unique_sn":[self udid]?:@"",
  567. @"lang":@(iszhcn),
  568. @"platform":platform?:@"AppleStore"
  569. }
  570. };
  571. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  572. //Send Request
  573. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/activeInvite"];
  574. NSURL *url = [NSURL URLWithString:urlString];
  575. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  576. request.requestMethod = @"POST";
  577. [request setPostBody:postData];
  578. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  579. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  580. postLength, @"Content-Length", nil];
  581. request.defaultResponseEncoding = NSUTF8StringEncoding;
  582. // [request setAuthenticationScheme:@"https"];//设置验证方式
  583. // [request setValidatesSecureCertificate:NO];//设置验证证书
  584. [request setRequestHeaders:requestHeaders];
  585. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  586. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  587. __block void(^processRequest)(void) = ^{
  588. dispatch_async(dispatch_get_main_queue(), ^{
  589. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  590. ActivityStatus status = weak_self.status;
  591. if ([info valueForKey:@"data"] &&
  592. [[info valueForKey:@"data"] valueForKey:@"device"]) {
  593. ActivityStatus tStatus = [(NSDictionary*)info[@"data"] status];
  594. weak_self.detailInfo = info[@"data"];
  595. if (status != tStatus) {
  596. //发送通知
  597. NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
  598. [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
  599. object:self
  600. userInfo:info];
  601. }
  602. [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  603. }];
  604. }
  605. //重置计时器
  606. [weak_self restartTimer];
  607. if (tComplention)
  608. tComplention(weak_self.status, info, request.error);
  609. });
  610. };
  611. [request setFailedBlock:^{
  612. processRequest();
  613. }];
  614. [request setCompletionBlock:^{
  615. processRequest();
  616. }];
  617. [request startAsynchronous];
  618. }
  619. - (void)modifyEmail:(NSString*)email
  620. complention:(ActivityComplention)complention {
  621. __block ActivityComplention tComplention = complention;
  622. __block VerificationManager *weak_self = self;
  623. //Process Params
  624. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  625. if (!app_version.length)
  626. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  627. BOOL iszhcn = !([NSLocalizedString(@"Language", nil) isEqualToString:@"English"] &&
  628. [NSLocalizedString(@"Language", nil) isEqualToString:@"Français"]);
  629. NSDictionary *params =
  630. @{
  631. @"data":@{
  632. @"app_code":[self bundleIdentify]?:@"",
  633. @"email":email?:@"",
  634. @"unique_sn":[self udid]?:@"",
  635. @"lang":@(iszhcn),
  636. }
  637. };
  638. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  639. //Send Request
  640. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/updateEmail"];
  641. NSURL *url = [NSURL URLWithString:urlString];
  642. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  643. request.requestMethod = @"POST";
  644. [request setPostBody:postData];
  645. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  646. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  647. postLength, @"Content-Length", nil];
  648. request.defaultResponseEncoding = NSUTF8StringEncoding;
  649. // [request setAuthenticationScheme:@"https"];//设置验证方式
  650. // [request setValidatesSecureCertificate:NO];//设置验证证书
  651. [request setRequestHeaders:requestHeaders];
  652. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  653. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  654. __block void(^processRequest)(void) = ^{
  655. dispatch_async(dispatch_get_main_queue(), ^{
  656. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  657. if ([info valueForKey:@"data"] &&
  658. [[info valueForKey:@"data"] valueForKey:@"email"] &&
  659. [[info valueForKey:@"data"] valueForKey:@"share_code"]) {
  660. //存储信息,并发送更新通知
  661. NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
  662. [dic setValue:info[@"data"] forKey:@"invite"];
  663. weak_self.detailInfo = dic;
  664. [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  665. }];
  666. }
  667. //重置计时器
  668. [weak_self restartTimer];
  669. if (tComplention)
  670. tComplention(weak_self.status, info, request.error);
  671. });
  672. };
  673. [request setFailedBlock:^{
  674. processRequest();
  675. }];
  676. [request setCompletionBlock:^{
  677. processRequest();
  678. }];
  679. [request startAsynchronous];
  680. }
  681. //给好友发送邀请码
  682. - (void)sendInvateEmails:(NSString*)emails
  683. code:(NSString*)code
  684. complention:(ActivityComplention)complention {
  685. __block ActivityComplention tComplention = complention;
  686. __block VerificationManager *weak_self = self;
  687. //Process Params
  688. NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
  689. if (!app_version.length)
  690. app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
  691. BOOL iszhcn = !([NSLocalizedString(@"Language", nil) isEqualToString:@"English"] &&
  692. [NSLocalizedString(@"Language", nil) isEqualToString:@"Français"]);
  693. NSDictionary *params =
  694. @{
  695. @"data":@{
  696. @"app_code":[self bundleIdentify]?:@"",
  697. @"email":emails?:@"",
  698. @"code":[code stringByReplacingOccurrencesOfString:@" " withString:@""]?:@"",
  699. @"unique_sn":[self udid]?:@"",
  700. @"lang":@(iszhcn),
  701. }
  702. };
  703. NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
  704. //Send Request
  705. NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/shareEmail"];
  706. NSURL *url = [NSURL URLWithString:urlString];
  707. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  708. request.requestMethod = @"POST";
  709. [request setPostBody:postData];
  710. NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
  711. NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  712. postLength, @"Content-Length", nil];
  713. request.defaultResponseEncoding = NSUTF8StringEncoding;
  714. // [request setAuthenticationScheme:@"https"];//设置验证方式
  715. // [request setValidatesSecureCertificate:NO];//设置验证证书
  716. [request setRequestHeaders:requestHeaders];
  717. [request addRequestHeader:@"Content-Type" value:@"application/json"];
  718. [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
  719. __block void(^processRequest)(void) = ^{
  720. dispatch_async(dispatch_get_main_queue(), ^{
  721. NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
  722. //重置计时器
  723. [weak_self restartTimer];
  724. if (tComplention)
  725. tComplention(weak_self.status, info, request.error);
  726. [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
  727. }];
  728. });
  729. };
  730. [request setFailedBlock:^{
  731. processRequest();
  732. }];
  733. [request setCompletionBlock:^{
  734. processRequest();
  735. }];
  736. [request startAsynchronous];
  737. }
  738. #pragma mark - Data Formatter
  739. - (BOOL)isValidLicenseCode:(NSString *)cdKey {
  740. NSString *validKey = [cdKey stringByReplacingOccurrencesOfString:@" " withString:@""];
  741. if (validKey.length != 19) {
  742. return NO;
  743. }
  744. //计算字符串长度
  745. NSInteger str_length = [validKey length];
  746. NSString *regex = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-";
  747. for (int i = 0; i<str_length; i++) {
  748. NSString *subStr = [validKey substringWithRange:NSMakeRange(i, 1)];
  749. if([regex rangeOfString:subStr].location == NSNotFound) {
  750. return NO;
  751. }
  752. }
  753. return YES;
  754. }
  755. + (NSString*)postStringWithObject:(id)value {
  756. NSString *string;
  757. if ([value isKindOfClass:[NSArray class]]) {
  758. string = @"[";
  759. BOOL isFirst = YES;
  760. for (id object in value) {
  761. if (isFirst) {
  762. isFirst = NO;
  763. }else {
  764. string = [string stringByAppendingString:@","];
  765. }
  766. string = [string stringByAppendingString:[VerificationManager postStringWithObject:object]];
  767. }
  768. string = [string stringByAppendingString:@"]"];
  769. }else if ([value isKindOfClass:[NSDictionary class]]) {
  770. string = @"{";
  771. BOOL isFirst = YES;
  772. for (NSString *key in [value allKeys]) {
  773. if (isFirst) {
  774. isFirst = NO;
  775. }else {
  776. string = [string stringByAppendingString:@","];
  777. }
  778. string = [string stringByAppendingFormat:@"\"%@\"", key];
  779. string = [string stringByAppendingString:@":"];
  780. string = [string stringByAppendingString:[VerificationManager postStringWithObject:[value valueForKey:key]]];
  781. }
  782. string = [string stringByAppendingString:@"}"];
  783. }else {
  784. string = [NSString stringWithFormat:@"\"%@\"", value];
  785. }
  786. return string;
  787. }
  788. + (NSString*)postStringWithDic:(NSDictionary*)dic {
  789. return [VerificationManager postStringWithObject:dic];
  790. }
  791. + (NSMutableData*)mutableDataWithDic:(NSDictionary*)dic {
  792. NSString *json = [VerificationManager postStringWithDic:dic];
  793. json = [json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  794. json = [json stringByReplacingOccurrencesOfString:@"\r\0" withString:@""];
  795. json = [json stringByReplacingOccurrencesOfString:@"\0" withString:@""];
  796. NSData *postData = [json dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
  797. return [postData mutableCopy];
  798. }
  799. @end
  800. #pragma mark - Test
  801. #if DEBUG
  802. @implementation VerificationManager (Test)
  803. //- (ActivityStatus)status {
  804. // return ActivityStatusVerification;
  805. //}
  806. - (void)updateVerificationStatus {
  807. [self updateStatus:ActivityStatusVerification postNo:true];
  808. }
  809. - (void)updateStatus:(ActivityStatus)status postNo:(bool)postNo {
  810. NSString *subValue = @"";
  811. NSString *deviceValue = @"";
  812. if (status == ActivityStatusNone) {
  813. deviceValue = @"";
  814. } else if (status == ActivityStatusTrial) {
  815. deviceValue = @"on_trial";
  816. } else if (status == ActivityStatusTrialExpire) {
  817. deviceValue = @"expired_trial";
  818. } else if (status == ActivityStatusVerification) {
  819. deviceValue = @"activated";
  820. } else if (status == ActivityStatusVerifExpire) {
  821. deviceValue = @"expired_license";
  822. } else if (status == ActivityStatusLicenseExpire) {
  823. deviceValue = @"";
  824. subValue = @"expired";
  825. }
  826. NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.detailInfo];
  827. dict[@"subscription"][@"status"] = subValue;
  828. dict[@"device"][@"status"] = deviceValue;
  829. self.detailInfo = dict;
  830. if (postNo) {
  831. //发送通知
  832. NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
  833. [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
  834. object:self
  835. userInfo:nil];
  836. }
  837. }
  838. @end
  839. #endif
  840. #pragma mark - NSDictionary + ActivityInfo
  841. @implementation NSDictionary (ActivityInfo)
  842. - (NSDate*)expireDate {
  843. if (self[@"device"][@"end_date"]) {
  844. return [self dateForValue:self[@"device"][@"end_date"]];
  845. } else if (self[@"subscription"][@"end_date"]) {
  846. return [self dateForValue:self[@"subscription"][@"end_date"]];
  847. }
  848. return nil;
  849. }
  850. - (NSDate*)createDate {
  851. if (self[@"device"][@"created_at"]) {
  852. return [self dateForValue:self[@"device"][@"created_at"]];
  853. }
  854. return nil;
  855. }
  856. - (ActivityStatus)status {
  857. ActivityStatus tStatus = ActivityStatusNone;
  858. if ([self[@"subscription"][@"status"] isEqualToString:@"expired"]) {
  859. tStatus = ActivityStatusLicenseExpire;
  860. }else{
  861. if ([self[@"device"][@"status"] isEqualToString:@"activated"]) {
  862. tStatus = ActivityStatusVerification;
  863. }else if ([self[@"device"][@"status"] isEqualToString:@"on_trial"]) {
  864. tStatus = ActivityStatusTrial;
  865. }else if ([self[@"device"][@"status"] isEqualToString:@"expired_trial"]) {
  866. tStatus = ActivityStatusTrialExpire;
  867. }else if ([self[@"device"][@"status"] isEqualToString:@"expired_license"]) {
  868. tStatus = ActivityStatusVerifExpire;
  869. }
  870. }
  871. if (ActivityStatusTrial == tStatus) {
  872. if (self.expireDate &&
  873. [NSDate date].timeIntervalSince1970 - [self expireDate].timeIntervalSince1970 > 0) {
  874. tStatus = ActivityStatusTrialExpire;
  875. }
  876. }else if (ActivityStatusVerification == tStatus) {
  877. if (self.expireDate &&
  878. [NSDate date].timeIntervalSince1970 - [self expireDate].timeIntervalSince1970 > 0) {
  879. tStatus = ActivityStatusVerifExpire;
  880. }
  881. if (self[@"dejvice"][@"status"] &&
  882. [self[@"device"][@"status"] isEqualToString:@"expired_license"]) {
  883. //激活码过期
  884. tStatus = ActivityStatusVerifExpire;
  885. }
  886. }
  887. return tStatus;
  888. }
  889. - (NSString*)licenseCode {
  890. return self[@"device"][@"cdkey"];
  891. }
  892. - (NSString*)shareCode {
  893. return self[@"invite"][@"share_code"]?:@"";
  894. }
  895. - (NSUInteger)invateUsersCount {
  896. return [self[@"invite"][@"new_users_num"] integerValue];
  897. }
  898. - (NSString*)fromCode {
  899. return self[@"invite"][@"from_code"]?:@"";
  900. }
  901. - (NSDate*)fetchInvateDate {
  902. if (self[@"invite"][@"created_at"]) {
  903. return [self dateForValue:self[@"invite"][@"created_at"]];
  904. }
  905. return nil;
  906. }
  907. - (NSDate*)dateForValue:(id)value {
  908. if ([value isKindOfClass:[NSString class]]) {
  909. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  910. [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  911. return [formatter dateFromString:[self[@"invite"][@"created_at"] substringToIndex:@"yyyy-MM-dd HH:mm:ss".length]];
  912. }else if ([value isKindOfClass:[NSNumber class]]) {
  913. return [NSDate dateWithTimeIntervalSince1970:[value doubleValue]];
  914. }
  915. return nil;
  916. }
  917. - (BOOL)repeatTrial {
  918. return [self[@"device"][@"trial_again"] boolValue];
  919. }
  920. - (NSUInteger)trialTimes {
  921. return [self[@"device"][@"trial_times"]?:@"1" intValue];
  922. }
  923. - (NSString *)email {
  924. return self[@"device"][@"email"]?:@"";
  925. }
  926. - (NSString *)accountName {
  927. return self[@"device"][@"contact_name"]?:@"";
  928. }
  929. - (NSUInteger)maxFreeDays {
  930. return [self[@"invite"][@"max_free_days"]?:@"365" intValue];
  931. }
  932. @end