VerificationManager.m 44 KB

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