12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154 |
- //
- // VerificationManager.m
- // Filmage Screen
- //
- // Created by 朱东勇 on 2018/2/8.
- // Copyright © 2018年 kdan mobile. All rights reserved.
- //
- #import "VerificationManager.h"
- #import "NSNULL+Filtration.h"
- #import "NSObject+DeviceInfo.h"
- #import "JSONKit.h"
- #import "ASIFormDataRequest.h"
- const NSString *kDeviceVerifyFinishNotification = @"kDeviceVerifyFinishNotification";
- const NSString *kDeviceActivateStatusChangeNotification = @"kDeviceActivateNotification";
- static VerificationManager *__verificationManager = nil;
- @interface VerificationManager ()
- @property (nonatomic, strong) NSTimer *timer;
- @property (nonatomic) BOOL isVerifing;
- @end
- @implementation VerificationManager
- + (VerificationManager*)manager {
- #if VERSION_DMG
- if (!__verificationManager)
- __verificationManager = [[VerificationManager alloc] init];
- #else
- return nil;
- #endif
- return __verificationManager;
- }
- + (VerificationManager*)defaultManager {
- #if VERSION_DMG
- if (!__verificationManager)
- __verificationManager = [[VerificationManager alloc] init];
- #else
- return nil;
- #endif
- return __verificationManager;
- }
- - (instancetype)init {
- self = [super init];
-
- self.autoVerification = YES;
-
- #if !DEBUG // 非测试环境时
- #if kTestMode // 测试模式时 报错
- //#error 服务器未切换到正式服务器!
- #endif
- #endif
-
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
-
- });
-
- return self;
- }
- #pragma mark - Setter & Getter
- - (ActivityStatus)status {
- return self.detailInfo.status;
- }
- - (BOOL)needUpgradeLicense {
- if ([self.detailInfo[@"device"][@"product_code"] isEqualToString:@"com.brother.pdfreaderpro.mac.product_1"] ||
- [self.detailInfo[@"device"][@"product_code"] isEqualToString:@"com.brother.pdfreaderpro.cross.platform.product_1"]) {
- return YES;
- }
- // if ([self.detailInfo[@"subscription"][@"product"][@"code"] isEqualToString:@"com.brother.pdfreaderpro.mac.product_1"]) {
- // return YES;
- // }
- return NO;
- }
- - (BOOL)secondTrialEnabled {
- return self.detailInfo.repeatTrial;
- }
- - (NSInteger)trialTimes {
- return self.detailInfo.trialTimes;
- }
- - (NSString *)licenseCode {
- return self.detailInfo.licenseCode;
- }
- - (NSString *)originLicenseCode {
- return self.detailInfo.originLicenseCode;
- }
- - (NSString *)email {
- return self.detailInfo.email?:@"";
- }
- - (NSString *)subscriptionEmail {
- return self.detailInfo.subscriptionEmail?:@"";
- }
- - (NSString *)accountName {
- return self.detailInfo.accountName;
- }
- - (BOOL)allowUnbind {
- return self.detailInfo.allowUnbind;
- }
- - (NSInteger)unbindTimes {
- return self.detailInfo.unbindTimes;
- }
- - (NSString*)udid {
- //#if DEBUG
- // NSString *cachePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"uuid.plist"];
- // NSMutableDictionary *info = [[NSDictionary dictionaryWithContentsOfFile:cachePath] mutableCopy];
- //
- // if (!info) {
- // info = [NSMutableDictionary dictionary];
- //
- // [info setValue:[NSString stringWithFormat:@"TestInvate%.0f", [NSDate date].timeIntervalSince1970]
- // forKey:@"uuid"];
- //
- //
- // [[NSFileManager defaultManager] createDirectoryAtPath:NSTemporaryDirectory()
- // withIntermediateDirectories:YES
- // attributes:nil
- // error:nil];
- // [info writeToFile:cachePath atomically:YES];
- // }
- //
- // return info[@"uuid"]?:(GetHardwareUUID()?:@"");
- //#endif
-
- return GetHardwareUUID()?:@"";
- }
- - (NSString*)bundleIdentify {
- return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"]?:@"";
- }
- - (void)setDetailInfo:(NSDictionary *)detailInfo {
- NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
- [defaults setValue:[detailInfo JSONData]
- forKey:@"detailInfo"];
- [defaults synchronize];
- }
- - (NSDictionary*)detailInfo {
- NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
- return [[[defaults valueForKey:@"detailInfo"] objectFromJSONData] filterNullObject];
- }
- //
- //- (void)setIsTest:(BOOL)isTest {
- // _isTest = isTest;
- //
- // [self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
- //
- // }];
- //}
- - (void)setAutoVerification:(BOOL)autoVerification {
- _autoVerification = autoVerification;
-
- [self restartTimer];
- }
- #pragma mark - Timer
- - (void)restartTimer {
- if (self.timer)
- [self.timer invalidate];
- self.timer = nil;
-
- if (self.autoVerification &&
- self.status != ActivityStatusNone) {
- self.timer = [NSTimer scheduledTimerWithTimeInterval:60 * 60//一个小时更新一次
- target:self
- selector:@selector(verificationFire)
- userInfo:nil
- repeats:NO];
- }
- }
- - (void)verificationFire {
- [self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
- }
- #pragma mark - Interface
- - (void)activateDeviceWithInfo:(NSDictionary*)info
- complention:(ActivityComplention)complention {
- if (![info[@"cdkey"] length]) {
- //激活码为空
- NSError *error = [NSError errorWithDomain:@""
- code:ActivityErrorTypeCDKeyEmpty
- userInfo:nil];
- if (complention)
- complention(NO, nil, error);
-
- return;
- }
- if (![self isValidLicenseCode:info[@"cdkey"]]) {
- //激活码格式不正确
- NSError *error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeFormatError
- userInfo:nil];
- if (complention)
- complention(NO, @{@"errors":@"FormatError"}, error);
-
- return;
- }
-
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
- NSDictionary *params =
- @{
- @"data":@{
- //激活信息
- @"subscription":@{
- @"app_code":[self bundleIdentify]?:@"",
- @"email":info[@"email"]?:@"",
- @"cdkey":info[@"cdkey"]?:@"",
- },
- //设备信息
- @"device":@{
- @"unique_sn":[self udid]?:@"",
- @"model":GetProductName()?:@"",
- @"os":GetSystemVersion()?:@"",
- @"time_zone":[[NSTimeZone localTimeZone] localizedName:NSTimeZoneNameStyleShortDaylightSaving locale:[NSLocale currentLocale]]?:@"",
- @"language":[[NSLocale currentLocale] localeIdentifier]?:@"",
- @"app_version":app_version?:@"",
- @"platform":@"DMG"
- }
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/auth_devices/activate"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
- request.defaultResponseEncoding = NSUTF8StringEncoding;
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
-
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
-
- NSError *error = request.error;
- if (info && [info isKindOfClass:[NSDictionary class]]) {
- if ([info valueForKey:@"errors"]) {
- NSString *detailKey = [[info[@"errors"] firstObject] valueForKey:@"detail_key"];
- if ([detailKey isEqualToString:@"exceed_max_device_num"]) {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeOutNumber
- userInfo:info];
- }else if ([detailKey isEqualToString:@"invalid_activate_info"]) {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeInvalidInfo
- userInfo:info];
- }else if ([detailKey isEqualToString:@"invalid_license_key"]) {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeCDKeyNotExist
- userInfo:info];
- }else if ([detailKey isEqualToString:@"license_not_match_product"]) {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeNotMatchProduct
- userInfo:info];
- }else if ([detailKey isEqualToString:@"license_expired"]) {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeCDKeyExpire
- userInfo:info];
- }else {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeUnknow
- userInfo:info];
- }
- }else if ([info valueForKey:@"error"]) {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeUnknow
- userInfo:info];
- }
- }else {
- if(error) {
- error = [NSError errorWithDomain:error.domain code:ActivityErrorTypeNetworkDisable userInfo:error.userInfo];
- } else {
- error = [NSError errorWithDomain:@"激活失败"
- code:ActivityErrorTypeUnknow
- userInfo:@{}];
- }
- }
-
- if (!error) {
- NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
-
- for (NSString *key in info[@"data"]) {
- [dic setValue:info[@"data"][key] forKey:key];
- }
-
- weak_self.detailInfo = dic;
-
- NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
- [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
- object:self
- userInfo:info];
-
- [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
- }
- [weak_self restartTimer];
-
-
- if (tComplention)
- tComplention(weak_self.status, info, error);
- });
- };
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- }
- - (void)verificationWithComplention:(ActivityComplention)complention {
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
-
- if (!self.isVerifing) {
- self.isVerifing = YES;
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
- NSString *platform = @"DMG";
- #if VERSION_FREE
-
- #if VERSION_DMG
-
- #else
- platform = @"AppleStore";
- #endif
-
- #else
- platform = @"AppleStorePro";
- #endif
-
- NSDictionary *params =
- @{
- @"data":@{
- //验证信息
- @"subscription":@{
- @"app_code":[self bundleIdentify]?:@"",
- // @"email":info[@"email"]?:@"",
- // @"cdkey":info[@"cdkey"]?:@"",
- },
- //设备信息
- @"device":@{
- @"unique_sn":[self udid]?:@"",
- @"model":GetProductName()?:@"",
- @"os":GetSystemVersion()?:@"",
- @"time_zone":[[NSTimeZone localTimeZone] localizedName:NSTimeZoneNameStyleShortDaylightSaving locale:[NSLocale currentLocale]]?:@"",
- @"language":[[NSLocale currentLocale] localeIdentifier]?:@"",
- @"app_version":app_version?:@"",
- @"platform":platform?:@"AppleStore"
- }
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/auth_devices/verify"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
-
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
-
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
- ActivityStatus status = weak_self.status;
- if ([info valueForKey:@"data"] &&
- [[info valueForKey:@"data"] valueForKey:@"device"]) {
- ActivityStatus tStatus = [(NSDictionary*)info[@"data"] status];
- //存储信息,并发送更新通知
- weak_self.detailInfo = info[@"data"];
-
- // if (status != tStatus ||
- // [[info valueForKey:@"data"] valueForKey:@"invite"]) {
- //发送通知
- NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
- [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
- object:weak_self
- userInfo:info];
- // }
- }
-
- [[NSNotificationCenter defaultCenter] postNotificationName:(NSString *)kDeviceVerifyFinishNotification
- object:nil
- userInfo:nil];
-
- weak_self.isVerifing = NO;
- //重置计时器
- [weak_self restartTimer];
-
- if (tComplention)
- tComplention(weak_self.status, info, request.error);
- });
- };
-
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- });
- }else {
- __block void(^waitBlock)(void) = ^{
- if (weak_self.isVerifing) {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- waitBlock();
- });
- }else {
- if (tComplention)
- tComplention(weak_self.status, @{@"data":weak_self.detailInfo?:@{}}, nil);
-
- waitBlock = NULL;
- }
- };
- waitBlock();
- }
- }
- - (void)trialForDays:(float)days
- complention:(ActivityComplention)complention {
- [self trialForDays:days email:nil name:nil complention:complention];
- }
- - (void)trialForDays:(float)days
- email:(NSString*)email
- name:(NSString*)name
- complention:(ActivityComplention)complention {
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
-
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
- NSDictionary *params =
- @{
- @"data":@{
- //激活信息
- @"subscription":@{
- @"app_code":[self bundleIdentify]?:@"",
- @"trail_days":@(MAX(days, 1)),
- @"email":email?:@"",
- @"contact_name":name?:@""
- },
- //设备信息
- @"device":@{
- @"unique_sn":[self udid]?:@"",
- @"model":GetProductName()?:@"",
- @"os":GetSystemVersion()?:@"",
- @"time_zone":[[NSTimeZone localTimeZone] localizedName:NSTimeZoneNameStyleShortDaylightSaving locale:[NSLocale currentLocale]]?:@"",
- @"language":[[NSLocale currentLocale] localeIdentifier]?:@"",
- @"app_version":app_version?:@""
- }
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/auth_devices/trial"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
- request.defaultResponseEncoding = NSUTF8StringEncoding;
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
-
- ActivityStatus status = weak_self.status;
- if ([info valueForKey:@"data"] &&
- [[info valueForKey:@"data"] valueForKey:@"device"]) {
- ActivityStatus tStatus = [(NSDictionary*)info[@"data"] status];
- //存储信息,并发送更新通知
- NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
-
- for (NSString *key in info[@"data"]) {
- [dic setValue:info[@"data"][key] forKey:key];
- }
-
- weak_self.detailInfo = dic;
-
- if (status != tStatus) {
- //发送通知
- NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
- [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
- object:self
- userInfo:info];
- }
- }
-
- //重置计时器
- [weak_self restartTimer];
-
- if (tComplention)
- tComplention(weak_self.status, info, request.error);
- });
- };
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- }
- - (void)getCodeWithEmail:(NSString*)email
- complention:(ActivityComplention)complention {
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
-
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
-
- NSString *platform = @"DMG";
- #ifdef AppStore_Version
- #if Lite_Version
- platform = @"AppleStore";
- #else
- platform = @"AppleStorePro";
- #endif
- #endif
-
- NSDictionary *params =
- @{
- @"data":@{
- @"app_code":[self bundleIdentify]?:@"",
- @"email":email?:@"",
- @"unique_sn":[self udid]?:@"",
- @"platform":platform?:@"AppleStore"
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/getCode"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
- request.defaultResponseEncoding = NSUTF8StringEncoding;
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
-
- if ([info valueForKey:@"data"] &&
- [[info valueForKey:@"data"] valueForKey:@"email"] &&
- [[info valueForKey:@"data"] valueForKey:@"share_code"]) {
- //存储信息,并发送更新通知
- NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
-
- [dic setValue:info[@"data"] forKey:@"invite"];
-
- weak_self.detailInfo = dic;
-
- [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
- }
-
- //重置计时器
- [weak_self restartTimer];
-
- if (tComplention)
- tComplention(weak_self.status, info, request.error);
- });
- };
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- }
- //使用邀请码
- - (void)userCode:(NSString*)code
- complention:(ActivityComplention)complention {
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
-
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
- BOOL iszhcn = !([NSLocalizedString(@"Language", nil) isEqualToString:@"English"] &&
- [NSLocalizedString(@"Language", nil) isEqualToString:@"Français"]);
- NSString *platform = @"DMG";
- #ifdef AppStore_Version
- #if Lite_Version
- platform = @"AppleStore";
- #else
- platform = @"AppleStorePro";
- #endif
- #endif
-
- NSDictionary *params =
- @{
- @"data":@{
- @"app_code":[self bundleIdentify]?:@"",
- @"code":code?:@"",
- @"unique_sn":[self udid]?:@"",
- @"lang":@(iszhcn),
- @"platform":platform?:@"AppleStore"
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/activeInvite"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
- request.defaultResponseEncoding = NSUTF8StringEncoding;
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
-
- ActivityStatus status = weak_self.status;
- if ([info valueForKey:@"data"] &&
- [[info valueForKey:@"data"] valueForKey:@"device"]) {
- ActivityStatus tStatus = [(NSDictionary*)info[@"data"] status];
- weak_self.detailInfo = info[@"data"];
-
- if (status != tStatus) {
- //发送通知
- NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
- [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
- object:self
- userInfo:info];
- }
-
- [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
- }
-
- //重置计时器
- [weak_self restartTimer];
-
- if (tComplention)
- tComplention(weak_self.status, info, request.error);
- });
- };
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- }
- - (void)modifyEmail:(NSString*)email
- complention:(ActivityComplention)complention {
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
-
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
- BOOL iszhcn = !([NSLocalizedString(@"Language", nil) isEqualToString:@"English"] &&
- [NSLocalizedString(@"Language", nil) isEqualToString:@"Français"]);
-
- NSDictionary *params =
- @{
- @"data":@{
- @"app_code":[self bundleIdentify]?:@"",
- @"email":email?:@"",
- @"unique_sn":[self udid]?:@"",
- @"lang":@(iszhcn),
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/updateEmail"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
- request.defaultResponseEncoding = NSUTF8StringEncoding;
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
- if ([info valueForKey:@"data"] &&
- [[info valueForKey:@"data"] valueForKey:@"email"] &&
- [[info valueForKey:@"data"] valueForKey:@"share_code"]) {
- //存储信息,并发送更新通知
- NSMutableDictionary *dic = [weak_self.detailInfo?:@{} mutableCopy];
-
- [dic setValue:info[@"data"] forKey:@"invite"];
-
- weak_self.detailInfo = dic;
-
- [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
- }
- //重置计时器
- [weak_self restartTimer];
-
- if (tComplention)
- tComplention(weak_self.status, info, request.error);
- });
- };
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- }
- //给好友发送邀请码
- - (void)sendInvateEmails:(NSString*)emails
- code:(NSString*)code
- complention:(ActivityComplention)complention {
- __block ActivityComplention tComplention = complention;
- __block VerificationManager *weak_self = self;
-
- //Process Params
- NSString *app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] description];
- if (!app_version.length)
- app_version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] description];
- BOOL iszhcn = !([NSLocalizedString(@"Language", nil) isEqualToString:@"English"] &&
- [NSLocalizedString(@"Language", nil) isEqualToString:@"Français"]);
-
- NSDictionary *params =
- @{
- @"data":@{
- @"app_code":[self bundleIdentify]?:@"",
- @"email":emails?:@"",
- @"code":[code stringByReplacingOccurrencesOfString:@" " withString:@""]?:@"",
- @"unique_sn":[self udid]?:@"",
- @"lang":@(iszhcn),
- }
- };
- NSMutableData *postData = [VerificationManager mutableDataWithDic:params];
-
- //Send Request
- NSString *urlString = [kVerificationServer stringByAppendingString:@"api/invites/shareEmail"];
- NSURL *url = [NSURL URLWithString:urlString];
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
-
- request.requestMethod = @"POST";
- [request setPostBody:postData];
- NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]];
- NSMutableDictionary *requestHeaders = [NSMutableDictionary dictionaryWithObjectsAndKeys:
- postLength, @"Content-Length", nil];
- request.defaultResponseEncoding = NSUTF8StringEncoding;
- // [request setAuthenticationScheme:@"https"];//设置验证方式
- // [request setValidatesSecureCertificate:NO];//设置验证证书
- [request setRequestHeaders:requestHeaders];
- [request addRequestHeader:@"Content-Type" value:@"application/json"];
- [request addRequestHeader:@"Accept" value:@"application/vnd.api+json;version=1"];
-
- __block void(^processRequest)(void) = ^{
- dispatch_async(dispatch_get_main_queue(), ^{
- NSDictionary *info = [[request.responseString objectFromJSONString] filterNullObject];
- //重置计时器
- [weak_self restartTimer];
-
- if (tComplention)
- tComplention(weak_self.status, info, request.error);
- [weak_self verificationWithComplention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
-
- }];
- });
- };
- [request setFailedBlock:^{
- processRequest();
- }];
- [request setCompletionBlock:^{
- processRequest();
- }];
- [request startAsynchronous];
- }
- #pragma mark - Data Formatter
- - (BOOL)isValidLicenseCode:(NSString *)cdKey {
- NSString *validKey = [cdKey stringByReplacingOccurrencesOfString:@" " withString:@""];
- if (validKey.length != 19) {
- return NO;
- }
- //计算字符串长度
- NSInteger str_length = [validKey length];
- NSString *regex = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-";
- for (int i = 0; i<str_length; i++) {
- NSString *subStr = [validKey substringWithRange:NSMakeRange(i, 1)];
- if([regex rangeOfString:subStr].location == NSNotFound) {
- return NO;
- }
- }
- return YES;
- }
- + (NSString*)postStringWithObject:(id)value {
- NSString *string;
-
- if ([value isKindOfClass:[NSArray class]]) {
- string = @"[";
- BOOL isFirst = YES;
-
- for (id object in value) {
- if (isFirst) {
- isFirst = NO;
- }else {
- string = [string stringByAppendingString:@","];
- }
- string = [string stringByAppendingString:[VerificationManager postStringWithObject:object]];
- }
-
- string = [string stringByAppendingString:@"]"];
- }else if ([value isKindOfClass:[NSDictionary class]]) {
- string = @"{";
- BOOL isFirst = YES;
-
- for (NSString *key in [value allKeys]) {
- if (isFirst) {
- isFirst = NO;
- }else {
- string = [string stringByAppendingString:@","];
- }
- string = [string stringByAppendingFormat:@"\"%@\"", key];
- string = [string stringByAppendingString:@":"];
- string = [string stringByAppendingString:[VerificationManager postStringWithObject:[value valueForKey:key]]];
- }
- string = [string stringByAppendingString:@"}"];
- }else {
- string = [NSString stringWithFormat:@"\"%@\"", value];
- }
-
- return string;
- }
- + (NSString*)postStringWithDic:(NSDictionary*)dic {
- return [VerificationManager postStringWithObject:dic];
- }
- + (NSMutableData*)mutableDataWithDic:(NSDictionary*)dic {
- NSString *json = [VerificationManager postStringWithDic:dic];
- json = [json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
- json = [json stringByReplacingOccurrencesOfString:@"\r\0" withString:@""];
- json = [json stringByReplacingOccurrencesOfString:@"\0" withString:@""];
- NSData *postData = [json dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
- return [postData mutableCopy];
- }
- @end
- #pragma mark - Test
- #if DEBUG
- @implementation VerificationManager (Test)
- //- (ActivityStatus)status {
- // return ActivityStatusVerification;
- //}
- - (void)updateVerificationStatus {
- [self updateStatus:ActivityStatusVerification postNo:true];
- }
- - (void)updateStatus:(ActivityStatus)status postNo:(bool)postNo {
- NSString *subValue = @"";
- NSString *deviceValue = @"";
- NSTimeInterval endTime = 0;
- if (status == ActivityStatusNone) {
- deviceValue = @"";
- } else if (status == ActivityStatusTrial) {
- deviceValue = @"on_trial";
- } else if (status == ActivityStatusTrialExpire) {
- deviceValue = @"expired_trial";
- } else if (status == ActivityStatusVerification) {
- deviceValue = @"activated";
- endTime = [NSDate date].timeIntervalSince1970 + 60 * 60;
- } else if (status == ActivityStatusVerifExpire) {
- deviceValue = @"expired_license";
- } else if (status == ActivityStatusLicenseExpire) {
- deviceValue = @"";
- subValue = @"expired";
- }
-
- NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.detailInfo];
- dict[@"subscription"][@"status"] = subValue;
- dict[@"device"][@"status"] = deviceValue;
- if (endTime != 0) {
- dict[@"device"][@"end_date"] = @(endTime);
- dict[@"subscription"][@"end_date"] = @(endTime);
- }
- self.detailInfo = dict;
- if (postNo) {
- //发送通知
- NSString *notificationName = (NSString *)kDeviceActivateStatusChangeNotification;
- [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
- object:self
- userInfo:nil];
- }
- }
- @end
- #endif
- #pragma mark - NSDictionary + ActivityInfo
- @implementation NSDictionary (ActivityInfo)
- - (NSDate*)expireDate {
- if (self[@"device"][@"end_date"]) {
- return [self dateForValue:self[@"device"][@"end_date"]];
- } else if (self[@"subscription"][@"end_date"]) {
- return [self dateForValue:self[@"subscription"][@"end_date"]];
- }
-
- return nil;
- }
- - (NSDate*)createDate {
- if (self[@"device"][@"created_at"]) {
- return [self dateForValue:self[@"device"][@"created_at"]];
- }
-
- return nil;
- }
- - (ActivityStatus)status {
- ActivityStatus tStatus = ActivityStatusNone;
- if ([self[@"subscription"][@"status"] isEqualToString:@"expired"]) {
- tStatus = ActivityStatusLicenseExpire;
- }else{
- if ([self[@"device"][@"status"] isEqualToString:@"activated"]) {
- tStatus = ActivityStatusVerification;
- }else if ([self[@"device"][@"status"] isEqualToString:@"on_trial"]) {
- tStatus = ActivityStatusTrial;
- }else if ([self[@"device"][@"status"] isEqualToString:@"expired_trial"]) {
- tStatus = ActivityStatusTrialExpire;
- }else if ([self[@"device"][@"status"] isEqualToString:@"expired_license"]) {
- tStatus = ActivityStatusVerifExpire;
- }
- }
- if (ActivityStatusTrial == tStatus) {
- if (self.expireDate &&
- [NSDate date].timeIntervalSince1970 - [self expireDate].timeIntervalSince1970 > 0) {
- tStatus = ActivityStatusTrialExpire;
- }
- }else if (ActivityStatusVerification == tStatus) {
- if (self.expireDate &&
- [NSDate date].timeIntervalSince1970 - [self expireDate].timeIntervalSince1970 > 0) {
- tStatus = ActivityStatusVerifExpire;
- }
- if (self[@"dejvice"][@"status"] &&
- [self[@"device"][@"status"] isEqualToString:@"expired_license"]) {
- //激活码过期
- tStatus = ActivityStatusVerifExpire;
- }
- }
- return tStatus;
- }
- - (NSString*)licenseCode {
- return self[@"device"][@"cdkey"];
- }
- - (NSString*)originLicenseCode {
- return self[@"device"][@"origin_cdkey"];
- }
- - (NSString*)shareCode {
- return self[@"invite"][@"share_code"]?:@"";
- }
- - (NSUInteger)invateUsersCount {
- return [self[@"invite"][@"new_users_num"] integerValue];
- }
- - (NSString*)fromCode {
- return self[@"invite"][@"from_code"]?:@"";
- }
- - (NSDate*)fetchInvateDate {
- if (self[@"invite"][@"created_at"]) {
- return [self dateForValue:self[@"invite"][@"created_at"]];
- }
-
- return nil;
- }
- - (NSDate*)dateForValue:(id)value {
- if ([value isKindOfClass:[NSString class]]) {
- NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
- [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
-
- return [formatter dateFromString:[self[@"invite"][@"created_at"] substringToIndex:@"yyyy-MM-dd HH:mm:ss".length]];
- }else if ([value isKindOfClass:[NSNumber class]]) {
- return [NSDate dateWithTimeIntervalSince1970:[value doubleValue]];
- }
-
- return nil;
- }
- - (BOOL)repeatTrial {
- return [self[@"device"][@"trial_again"] boolValue];
- }
- - (NSUInteger)trialTimes {
- return [self[@"device"][@"trial_times"]?:@"1" intValue];
- }
- - (NSString *)email {
- return self[@"device"][@"email"]?:@"";
- }
- - (NSString *)subscriptionEmail {
- return self[@"subscription"][@"email"]?:@"";
- }
- - (NSString *)accountName {
- return self[@"device"][@"contact_name"]?:@"";
- }
- - (NSUInteger)maxFreeDays {
- return [self[@"invite"][@"max_free_days"]?:@"365" intValue];
- }
- - (BOOL)allowUnbind {
- return [self[@"device"][@"allow_unbind"] boolValue];
- }
- - (NSInteger)unbindTimes {
- return [self[@"device"][@"unbind_time"]?:@"0" integerValue];
- }
- @end
|