VerificationManager.m 43 KB

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