AppDelegateBase.m 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347
  1. //
  2. // AppDelegateBase.m
  3. // iSales-UWAVER
  4. //
  5. // Created by Ray on 2018/8/9.
  6. // Copyright © 2018 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "AppDelegateBase.h"
  9. #import "UILabel+FontAppearance.h"
  10. #import "MainViewController.h"
  11. #import "RAPDFViewController.h"
  12. #import "ZipArchive.h"
  13. #import "DefaultAppearance.h"
  14. #import "OLDataProvider.h"
  15. //#import "AFHTTPSessionManager.h"
  16. #import "SelectUploadOrderViewController.h"
  17. #import "iSalesDB.h"
  18. #import "RANetwork.h"
  19. #import "NotificationNameCenter.h"
  20. #import "CustomerEditViewController.h"
  21. #import "CreateOrderViewController.h"
  22. #import "OrderDetailViewController.h"
  23. #import "AddressEditorViewController.h"
  24. #import "config.h"
  25. #import "Singleton.h"
  26. #import "Analytics.h"
  27. #import "GoogleAnalyst.h"
  28. #import "ERPUtils.h"
  29. #import "RANetwork.h"
  30. #ifdef BACKORDER_PROCESS
  31. #import "RAOrderEditorViewController.h"
  32. #endif
  33. #import "RAConvertor.h"
  34. #define UNZIP_OPEN_FAILED 0
  35. #define UNZIP_SUCCESS 1
  36. #define UNZIP_NO_SPACE 2
  37. #define UNZIP_FILE_DAMAGE 3
  38. @interface AppDelegateBase ()
  39. @property (nonatomic,strong) NSMutableDictionary *globalParameters;
  40. @property (nonatomic,strong) NSDate *forgroundDate;
  41. @end
  42. @implementation AppDelegateBase
  43. {
  44. #ifdef USE_SOFTSCAN
  45. DeviceInfo* _softScanDeviceInfo;
  46. #endif
  47. DeviceInfo* _deviceInfoToTrigger;
  48. NSMutableArray* _feedbackStack;
  49. id<ScannerEventsFeedback> _eventsFeedback;
  50. }
  51. @synthesize ScanApi;
  52. @synthesize ScanApiConsumer;
  53. @synthesize scanApiVersion;
  54. @synthesize price_hidden = _price_hidden;
  55. #pragma mark - Global Parameter
  56. - (NSMutableDictionary *)globalParameters {
  57. if (!_globalParameters) {
  58. _globalParameters = [NSMutableDictionary dictionary];
  59. }
  60. return _globalParameters;
  61. }
  62. - (void)setGlobalParameter:(id)param forKey:(NSString *)key {
  63. if (param == nil || key == nil) {
  64. return;
  65. }
  66. [self.globalParameters setObject:param forKey:key];
  67. }
  68. - (id)globalParameterForKey:(NSString *)key {
  69. if (key == nil) {
  70. return nil;
  71. }
  72. return [self.globalParameters objectForKey:key];
  73. }
  74. #pragma mark - Setter
  75. - (void)setUrgencyDic:(NSMutableDictionary *)urgencyDic {
  76. _urgencyDic = urgencyDic;
  77. [self setGlobalParameter:_urgencyDic forKey:@"urgencyDic"];
  78. }
  79. - (void)setCan_see_price:(bool)can_see_price {
  80. _can_see_price = can_see_price;
  81. [self setGlobalParameter:@(_can_see_price) forKey:@"can_see_price"];
  82. }
  83. - (void)setPrice_hidden:(bool)price_hidden {
  84. _price_hidden = price_hidden;
  85. [self setGlobalParameter:@(_price_hidden) forKey:@"price_hidden"];
  86. #ifdef RA_NOTIFICATION
  87. [ActiveViewController Notify:@"" Message:RA_NOTIFICATION_UPDATE_PRICE];
  88. #else
  89. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  90. [avc showHidePrice];
  91. #endif
  92. }
  93. - (void)setOffline_mode:(bool)offline_mode {
  94. _offline_mode = offline_mode;
  95. [self setGlobalParameter:@(_offline_mode) forKey:@"offline_mode"];
  96. }
  97. - (void)setUser:(NSString *)user {
  98. _user = user;
  99. [self setGlobalParameter:_user forKey:@"user"];
  100. }
  101. - (void)setPassword:(NSString *)password {
  102. _password = password;
  103. [self setGlobalParameter:_password forKey:@"password"];
  104. }
  105. #pragma mark - Normal
  106. -(void) set_priceHidden:(bool)price_hidden
  107. {
  108. [self setPrice_hidden:price_hidden];
  109. }
  110. -(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
  111. {
  112. if (self.user_type == USER_ROLE_CUSTOMER && _customerInfo) {
  113. return;
  114. }
  115. #ifdef RA_NOTIFICATION
  116. [ActiveViewController Notify:@"ContactListViewController" Message:RA_NOTIFICATION_REFRESH_UI];
  117. [ActiveViewController Notify:@"WatchListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  118. #else
  119. [((MainViewController*)self.main_vc) reloadContact:false immediately:false];
  120. [(MainViewController*)self.main_vc reloadWish:YES immediately:NO];
  121. #endif
  122. _customerInfo=customerInfo;
  123. // DebugLog(@"%@",_customerInfo.class);
  124. // DebugLog(@"%@",customerInfo.class);
  125. int count=customerInfo[@"count"];
  126. //assert(count==0);
  127. }
  128. -(void) set_main_button_panel
  129. {
  130. dispatch_async(dispatch_get_main_queue(), ^{
  131. if(self.main_vc==nil)
  132. return;
  133. MainViewController * main_vc= (MainViewController*)self.main_vc;
  134. if(self.user_type==USER_ROLE_CUSTOMER)
  135. {
  136. main_vc.customer_bp.hidden=false;
  137. main_vc.employee_bp.hidden = true;
  138. }
  139. else
  140. {
  141. main_vc.customer_bp.hidden=true;
  142. main_vc.employee_bp.hidden = false;
  143. }
  144. });
  145. }
  146. -(void) update_count_mark
  147. {
  148. dispatch_async(dispatch_get_main_queue(), ^{
  149. if(self.main_vc==nil)
  150. return;
  151. MainViewController * main_vc= (MainViewController*)self.main_vc;
  152. //contact button
  153. if(self.user==nil)
  154. {
  155. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  156. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  157. main_vc.btnContact.hidden = YES;
  158. }
  159. else
  160. {
  161. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  162. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  163. if(self.customerInfo==nil)
  164. {
  165. // contact=@"No Name"; if(customerinfo==nil)
  166. // {
  167. contact=@"Select Contact";
  168. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  169. }
  170. else
  171. {
  172. if(contact==nil||contact.length==0)
  173. {
  174. contact=@"No Name";
  175. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  176. }
  177. else
  178. {
  179. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  180. }
  181. }
  182. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  183. if(contact.length>0)
  184. [arr_contact addObject:contact];
  185. if(customer.length>0)
  186. [arr_contact addObject:customer];
  187. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  188. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  189. }
  190. //cart
  191. if(self.user==nil||self.cart_count==0)
  192. {
  193. main_vc.label_ccount.hidden = true;
  194. main_vc.label_cccount.hidden=true;
  195. }
  196. else
  197. {
  198. NSString* strcount;
  199. if(self.cart_count>999)
  200. strcount=@"999+";
  201. else
  202. strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
  203. main_vc.label_ccount.text = strcount;
  204. if(strcount.length==1)
  205. main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
  206. if(strcount.length==2)
  207. main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
  208. if(strcount.length==3)
  209. main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
  210. if(strcount.length==4)
  211. main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
  212. main_vc.label_ccount.hidden = false;
  213. main_vc.label_cccount.text = strcount;
  214. if(strcount.length==1)
  215. main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
  216. if(strcount.length==2)
  217. main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
  218. if(strcount.length==3)
  219. main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
  220. if(strcount.length==4)
  221. main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
  222. main_vc.label_cccount.hidden = false;
  223. }
  224. //wishlist
  225. if(self.user==nil||self.wish_count==0)
  226. {
  227. main_vc.label_wcount.hidden = true;
  228. main_vc.label_cwcount.hidden = true;
  229. }
  230. else
  231. {
  232. NSString* strcount;
  233. if(self.wish_count>999)
  234. strcount=@"999+";
  235. else
  236. strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
  237. main_vc.label_wcount.text = strcount;
  238. if(strcount.length==1)
  239. main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
  240. if(strcount.length==2)
  241. main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
  242. if(strcount.length==3)
  243. main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
  244. if(strcount.length==4)
  245. main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
  246. main_vc.label_wcount.hidden = false;
  247. main_vc.label_cwcount.text = strcount;
  248. if(strcount.length==1)
  249. main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
  250. if(strcount.length==2)
  251. main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
  252. if(strcount.length==3)
  253. main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
  254. if(strcount.length==4)
  255. main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
  256. main_vc.label_cwcount.hidden = false;
  257. }
  258. });
  259. }
  260. -(void) closeOrder
  261. {
  262. self.order_code = nil;
  263. self.order_customer_id = nil;
  264. if(self.user_type!=USER_ROLE_CUSTOMER)
  265. {
  266. self.customerInfo = nil;
  267. self.contact_id = nil;
  268. }
  269. // [self SetMode:nil];
  270. // [self SetSo:nil];
  271. #ifdef RA_NOTIFICATION
  272. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  273. #else
  274. [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
  275. [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
  276. #endif
  277. }
  278. -(void) switchToPreviousVC
  279. {
  280. MainViewController * main_vc= (MainViewController*)self.main_vc;
  281. [main_vc switchToPreviousVC];
  282. }
  283. -(void) SetMode:(NSString*)mode1
  284. {
  285. __block NSString* blockmode= mode1;
  286. dispatch_async(dispatch_get_main_queue(), ^{
  287. if(self.offline_mode)
  288. blockmode =@"Regular Mode";
  289. if(self.main_vc==nil)
  290. return;
  291. MainViewController * main_vc= (MainViewController*)self.main_vc;
  292. if(self.user==nil)
  293. {
  294. NSString* title = [NSString stringWithFormat:@"Sign in"];
  295. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  296. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  297. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  298. main_vc.btnContact.hidden = YES;
  299. main_vc.labelMode.text=nil;
  300. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  301. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
  302. // main_vc.buttonUser.hidden=true;
  303. // main_vc.buttonUser.hidden=false;
  304. // [main_vc.headerView setNeedsDisplay];
  305. // [main_vc.headerView setNeedsLayout];
  306. return;
  307. }
  308. else
  309. {
  310. if(self.user_type==USER_ROLE_CUSTOMER)
  311. {
  312. NSString* title = [NSString stringWithFormat:@"%@",self.user];
  313. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  314. main_vc.labelMode.text=nil;
  315. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  316. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
  317. // main_vc.buttonUser.hidden=true;
  318. // main_vc.buttonUser.hidden=false;
  319. // [main_vc.headerView setNeedsDisplay];
  320. // [main_vc.headerView setNeedsLayout];
  321. }
  322. else
  323. {
  324. if([blockmode isEqualToString:@"Regular Mode"])
  325. {
  326. self.mode=@"RM";
  327. NSString* title = self.user;
  328. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  329. main_vc.labelMode.text=self.mode;
  330. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  331. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
  332. // main_vc.buttonUser.hidden=true;
  333. // main_vc.buttonUser.hidden=false;
  334. // [main_vc.headerView setNeedsDisplay];
  335. // [main_vc.headerView setNeedsLayout];
  336. }
  337. else
  338. {
  339. self.mode=@"TM";
  340. NSString* title = self.user;
  341. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  342. main_vc.labelMode.text=self.mode;
  343. [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
  344. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x009966) forState:UIControlStateNormal];
  345. // main_vc.buttonUser.hidden=true;
  346. // main_vc.buttonUser.hidden=false;
  347. // [main_vc.headerView setNeedsDisplay];
  348. // [main_vc.headerView setNeedsLayout];
  349. }
  350. }
  351. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  352. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  353. if(self.customerInfo==nil)
  354. {
  355. // contact=@"No Name"; if(customerinfo==nil)
  356. // {
  357. contact=@"Select Contact";
  358. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  359. }
  360. else
  361. {
  362. if(contact==nil||contact.length==0)
  363. {
  364. contact=@"No Name";
  365. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  366. }
  367. else
  368. {
  369. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  370. }
  371. }
  372. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  373. if(contact.length>0)
  374. [arr_contact addObject:contact];
  375. if(customer.length>0)
  376. [arr_contact addObject:customer];
  377. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  378. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  379. }
  380. });
  381. }
  382. -(void) SetSo:(NSString *)So
  383. {
  384. dispatch_async(dispatch_get_main_queue(), ^{
  385. if(self.main_vc==nil)
  386. return;
  387. MainViewController * main_vc= (MainViewController*)self.main_vc;
  388. if (self.user_type == USER_ROLE_CUSTOMER) {
  389. if (So == nil) {
  390. // 释放订单
  391. [Singleton sharedInstance].currentOrderIsMerged = NO;
  392. }
  393. }
  394. if(self.user==nil)
  395. {
  396. // NSString* title = [NSString stringWithFormat:@"Sign in"];
  397. main_vc.labelSo.text=nil;
  398. return;
  399. }
  400. else
  401. {
  402. // if(self.user_type==USER_ROLE_CUSTOMER)
  403. // {
  404. //
  405. //
  406. // main_vc.labelSo.text=nil;
  407. // // main_vc.buttonUser.hidden=true;
  408. // // main_vc.buttonUser.hidden=false;
  409. // // [main_vc.headerView setNeedsDisplay];
  410. // // [main_vc.headerView setNeedsLayout];
  411. // }
  412. // else
  413. {
  414. if(So.length==0)
  415. main_vc.labelSo.text=nil;
  416. else
  417. {
  418. NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
  419. main_vc.labelSo.text=text;
  420. }
  421. }
  422. }
  423. });
  424. }
  425. //- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
  426. // if ([rootViewController isKindOfClass:[UITabBarController class]]) {
  427. // UITabBarController* tabBarController = (UITabBarController*)rootViewController;
  428. // return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
  429. // } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
  430. // UINavigationController* navigationController = (UINavigationController*)rootViewController;
  431. // return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
  432. // } else if (rootViewController.presentedViewController) {
  433. // UIViewController* presentedViewController = rootViewController.presentedViewController;
  434. // return [self topViewControllerWithRootViewController:presentedViewController];
  435. // } else {
  436. // return rootViewController;
  437. // }
  438. //}
  439. //- (UIViewController*)topViewController {
  440. // return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  441. //}
  442. //-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  443. ////   // Get topmost/visible view controller
  444. // UIViewController *currentViewController = [self topViewController];
  445. //
  446. // if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
  447. //
  448. // return UIInterfaceOrientationMaskPortrait;
  449. // }
  450. ////
  451. ////   // Only allow portrait (standard behaviour)
  452. // return UIInterfaceOrientationMaskAll;
  453. //}
  454. void UncaughtExceptionHandler(NSException *exception) {
  455. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  456. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  457. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  458. NSString *versionNum = @"";
  459. versionNum = [NSString stringWithFormat:@"Version: %@ %@ Build %@",COMPANY_SHORT_NAME,version,build];
  460. versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  461. /**
  462. * 获取异常崩溃信息
  463. */
  464. NSArray *callStack = [exception callStackSymbols];
  465. NSString *reason = [exception reason];
  466. NSString *name = [exception name];
  467. NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name: %@\n exception_reason: \n%@ \n exception_callStackSymbols: \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
  468. content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  469. NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
  470. if ([Singleton sharedInstance].currentDB) {
  471. [iSalesDB close_db:[Singleton sharedInstance].currentDB];
  472. }
  473. [iSalesDB execSql:sql];
  474. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  475. [appDelegate writeUrgencyCache];
  476. }
  477. - (void)handleErrorLog {
  478. __block NSMutableArray *err_array = [NSMutableArray array];
  479. [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  480. const char *version_char = (char *)sqlite3_column_text(stmt, 0);
  481. const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
  482. const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
  483. if (version_char == NULL)
  484. version_char = "";
  485. if (errlog_char == NULL)
  486. errlog_char = "";
  487. if (dateTime_char == NULL)
  488. dateTime_char = "";
  489. NSString *version_str = [NSString stringWithUTF8String:version_char];
  490. NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
  491. NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
  492. NSDictionary *err_dic = @{
  493. @"version" : version_str,
  494. @"errlog" : errlog_str,
  495. @"time" : dateTime_str
  496. };
  497. [err_array addObject:err_dic];
  498. }];
  499. if (err_array.count) {
  500. // 首先上传
  501. for (NSDictionary *err_dic in err_array) {
  502. NSString *version = [err_dic objectForKey:@"version"];
  503. NSString *errlog = [err_dic objectForKey:@"errlog"];
  504. NSString *time = [err_dic objectForKey:@"time"];
  505. NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
  506. NSDictionary *ret = [RANetwork err_log:errlog result:result module:@"crash" code:0];
  507. // 上传成功之后清除纪录
  508. if ([[ret objectForKey:@"result"] integerValue] == 2) {
  509. [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
  510. }
  511. }
  512. }
  513. }
  514. - (void)dealWithUrgencyFile {
  515. NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
  516. if (tmp_urgencyDic.allKeys.count > 2) {
  517. [self.urgencyDic removeAllObjects];
  518. [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
  519. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  520. UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  521. NSString *user = [tmp_urgencyDic objectForKey:@"user"];
  522. if (![user isEqualToString:self.user]) {
  523. return;
  524. }
  525. BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
  526. if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
  527. return;
  528. }
  529. id count = [tmp_urgencyDic objectForKey:@"count"];
  530. int level_count = count ? [count integerValue] : 0;
  531. if (!level_count) {
  532. return;
  533. }
  534. for (int i = 0; i < level_count; i++) {
  535. NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
  536. NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
  537. NSString *className = [urgencyDic objectForKey:@"class_name"];
  538. NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
  539. NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
  540. dispatch_async(dispatch_get_main_queue(), ^{
  541. if ([className isEqualToString:@"CustomerEditViewController"]) {
  542. // CustomerEditViewController
  543. NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
  544. BOOL new_customer = [urgencyDic objectForKey:@"new_customer"];
  545. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  546. [params setValue:contact_id forKey:@"contact_id"];
  547. CustomerEditViewController * cuseditVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"CustomerEditViewController"];
  548. cuseditVC.bnewcustomer=new_customer;
  549. cuseditVC.url_type = URL_RESTORE;
  550. cuseditVC.request_url= new_customer ? URL_NEW_CUSTOMER : URL_EDIT_CUSTOMER;
  551. cuseditVC.params = params;
  552. cuseditVC.content_data_download = restored_data;
  553. // cuseditVC.delegate=self;
  554. [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
  555. [mainVC.navigationController pushViewController:cuseditVC animated:false];
  556. } else if ([className isEqualToString:@"CreateOrderViewController"] || [className isEqualToString:@"RAOrderEditorViewController"]) {
  557. // CreateOrderViewController
  558. NSString *order_code = [urgencyDic objectForKey:@"order_code"];
  559. int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
  560. NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
  561. NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
  562. NSString *so = [urgencyDic objectForKey:@"order_so"];
  563. self.order_customer_id = order_customer_id;
  564. // 首先通过order code 打开订单
  565. NSDictionary* order_json = [RANetwork open_Order:order_code];
  566. dispatch_async(dispatch_get_main_queue(), ^{
  567. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  568. if([[order_json valueForKey:@"result"] intValue]==2)
  569. {
  570. self.order_code = order_code;
  571. self.order_status = order_status;
  572. [self SetSo:so];
  573. if (userType != USER_ROLE_CUSTOMER) {
  574. self.customerInfo = [[[RANetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
  575. self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  576. }
  577. #ifdef RA_NOTIFICATION
  578. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  579. #else
  580. [mainVC reloadOrder:true immediately:false];
  581. [mainVC reloadCart:true immediately:false];
  582. #endif
  583. }
  584. else
  585. {
  586. [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Open Order" controller:mainVC] ;
  587. }
  588. });
  589. // 再place order
  590. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  591. if ([className isEqualToString:@"CreateOrderViewController"]) {
  592. CreateOrderViewController * orderinfoVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"CreateOrderViewController"];
  593. orderinfoVC.disable_dropdown_refresh=true;
  594. orderinfoVC.url_type = URL_RESTORE;
  595. orderinfoVC.request_url=URL_CARTDELIVERY;
  596. orderinfoVC.params = params;
  597. orderinfoVC.content_data_download = restored_data;
  598. orderinfoVC.resumeOrder = YES;
  599. [mainVC.navigationController pushViewController:orderinfoVC animated:true];
  600. }
  601. #ifdef BACKORDER_PROCESS
  602. else if ([className isEqualToString:@"RAOrderEditorViewController"]) {
  603. RAOrderEditorViewController *orderEditorVC = [mainStoryBoard instantiateViewControllerWithIdentifier:@"RAOrderEditorViewController"];
  604. [orderEditorVC recoveryFromUrgencyDic:urgencyDic];
  605. [mainVC.navigationController pushViewController:orderEditorVC animated:YES];
  606. }
  607. #endif
  608. } else if ([className isEqualToString:@"AddressEditorViewController"]) {
  609. // AddressEditorViewController
  610. AddressEditorViewController * addressVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"AddressEditorViewController"];
  611. addressVC.url_type = URL_RESTORE;
  612. addressVC.request_url=URL_ADDRESS_EDOTOR;
  613. NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
  614. params[@"is_subaction"]=@"true";
  615. addressVC.params = params;
  616. addressVC.content_data_download = restored_data;
  617. [mainVC.navigationController pushViewController:addressVC animated:true];
  618. }// class_name
  619. });
  620. }
  621. }
  622. }
  623. - (void)handleUrgencyFile {
  624. __weak typeof(self) weakself = self;
  625. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  626. if (weakself) {
  627. __strong typeof(weakself) strongself = weakself;
  628. [strongself dealWithUrgencyFile];
  629. }
  630. });
  631. }
  632. - (void)writeUrgencyCache {
  633. if (!self.user) {
  634. return;
  635. }
  636. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  637. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  638. // [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
  639. [self.urgencyDic writeToFile:urgencyFile atomically:NO];
  640. // Place Order恢复是否能提交订单
  641. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
  642. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
  643. if ([Singleton sharedInstance].currentOrderIsMerged && [Singleton sharedInstance].permissions_submit_order) {
  644. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
  645. }
  646. }
  647. - (NSMutableDictionary *)readUrgencyCache {
  648. // 检查本地urgency文件,存在则加载进_urgencyDic
  649. NSFileManager *manager = [NSFileManager defaultManager];
  650. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  651. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  652. NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
  653. if ([manager fileExistsAtPath:urgencyFile]) {
  654. resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
  655. [manager removeItemAtPath:urgencyFile error:nil];
  656. }
  657. self.urgencyDic = [NSMutableDictionary dictionary];
  658. return resultDic;
  659. }
  660. - (void)initialExceptionHandler {
  661. if (exception_switch == 1) {
  662. NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
  663. }
  664. }
  665. - (void)becomeObserver {
  666. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
  667. }
  668. - (void)dealloc {
  669. [[NSNotificationCenter defaultCenter] removeObserver:self];
  670. }
  671. - (void)setUpGoogleAnalytics {
  672. // 初始化Google Analytics
  673. NSError *configureError;
  674. [[GGLContext sharedInstance] configureWithError:&configureError];
  675. if (configureError) {
  676. DebugLog(@"congigure googleAnalytics error: %@",configureError);
  677. }
  678. GAI *gai = [GAI sharedInstance];
  679. gai.trackUncaughtExceptions = YES;
  680. id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
  681. // Enable IDFA collection.
  682. tracker.allowIDFACollection = YES;
  683. // gai.dispatchInterval = 120;// 每隔 2 分钟调度一次数据
  684. // 调试使用
  685. // gai.logger.logLevel = kGAILogLevelVerbose;
  686. // [[GAI sharedInstance] setDryRun:YES];
  687. //
  688. }
  689. //-(void)test_descrypt
  690. //{
  691. // sqlite3 *db = [iSalesDB get_db];
  692. //
  693. // int result= [iSalesDB AddExFunction:db];
  694. //
  695. // NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  696. // sqlite3_stmt * statement;
  697. //
  698. //
  699. // if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  700. // {
  701. //
  702. //
  703. // while (sqlite3_step(statement) == SQLITE_ROW)
  704. // {
  705. //
  706. //
  707. // char *url = (char*)sqlite3_column_text(statement, 0);
  708. // if(url==nil)
  709. // url="";
  710. // NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  711. // DebugLog(nsurl);
  712. //
  713. //
  714. //
  715. //
  716. // }
  717. // // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  718. //
  719. //
  720. // sqlite3_finalize(statement);
  721. // }
  722. //
  723. // [iSalesDB close_db:db];
  724. //}
  725. //
  726. //-(void)test_descrypt1
  727. //{
  728. // sqlite3 *db = [iSalesDB get_db];
  729. //
  730. // int result= [iSalesDB AddExFunction:db];
  731. //
  732. // NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
  733. //
  734. // [iSalesDB execSql:sqlindex];
  735. ////
  736. //// NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  737. //// sqlite3_stmt * statement;
  738. ////
  739. ////
  740. ////
  741. //// if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  742. //// {
  743. ////
  744. ////
  745. //// while (sqlite3_step(statement) == SQLITE_ROW)
  746. //// {
  747. ////
  748. ////
  749. //// char *url = (char*)sqlite3_column_text(statement, 0);
  750. //// if(url==nil)
  751. //// url="";
  752. //// NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  753. //// DebugLog(nsurl);
  754. ////
  755. ////
  756. ////
  757. ////
  758. //// }
  759. //// // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  760. ////
  761. ////
  762. //// sqlite3_finalize(statement);
  763. //// }
  764. //
  765. // [iSalesDB close_db:db];
  766. //}
  767. - (void)applicationWillResignActive:(UIApplication *)application
  768. {
  769. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  770. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  771. }
  772. - (void)applicationDidEnterBackground:(UIApplication *)application
  773. {
  774. [self download_offline:false checkdiskspace:false];
  775. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  776. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  777. NSTimeInterval timing = [[NSDate date] timeIntervalSinceDate:self.forgroundDate];
  778. self.forgroundDate = nil;
  779. #if defined(BUILD_NPD) || defined(BUILD_USAI)
  780. [GoogleAnalyst trackTimingWithCategory:@"foreground" interval:timing name:@"user used time" label:nil];
  781. #endif
  782. }
  783. - (void)applicationWillEnterForeground:(UIApplication *)application
  784. {
  785. // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  786. }
  787. - (void)applicationDidBecomeActive:(UIApplication *)application
  788. {
  789. if(self.download_task!=nil)
  790. [self download_offline:true checkdiskspace:false];
  791. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  792. self.forgroundDate = [NSDate date];
  793. }
  794. -(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
  795. {
  796. DebugLog(@"======================================");
  797. DebugLog(@"===== MEMORY WORRING ! ==========");
  798. DebugLog(@"======================================");
  799. }
  800. - (void)applicationWillTerminate:(UIApplication *)application
  801. {
  802. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  803. }
  804. -(void) Logout
  805. {
  806. MainViewController * main_vc= (MainViewController*)self.main_vc;
  807. [main_vc logoutOrder];
  808. [main_vc logoutCart];
  809. [main_vc logoutWish];
  810. [main_vc logoutContact];
  811. [main_vc logoutCategory];
  812. [main_vc logoutDocuments];
  813. [main_vc logoutPortfolio];
  814. [main_vc hideMenu];
  815. [main_vc switchToHome];
  816. self.user = nil;
  817. self.password=nil;
  818. self.user_icon=nil;
  819. self.user_type = USER_ROLE_UNKNOWN;
  820. self.bLogin = false;
  821. self.contact_id=nil;
  822. self.customerInfo = nil;
  823. self.order_code = nil;
  824. [self.recent_model removeAllObjects];
  825. [self SetMode:nil];
  826. }
  827. //disable apn
  828. //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  829. //{
  830. // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
  831. // DebugLog(@"regisger success:%@",deviceToken);
  832. //
  833. // //注册成功,将deviceToken保存到应用服务器数据库中
  834. //}
  835. #pragma mark - background download
  836. -(bool)isdownloading:(NSString*) file
  837. {
  838. return true;
  839. }
  840. -(long long)getcurrentLength:(int) taskidx
  841. {
  842. int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
  843. return position;
  844. }
  845. -(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  846. {
  847. //操作有两种,start stop;
  848. //结果有四种, wait , downloading, pause, finish
  849. dispatch_async(dispatch_get_main_queue(), ^{
  850. NSString* file_name=[url lastPathComponent];
  851. //暂停<->开始转换
  852. // bool isdownloading = [self isdownloading:file_name];
  853. if (start)
  854. {//开始下载
  855. DebugLog(@"%d start",taskidx);
  856. self.current_task=taskidx;
  857. NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  858. // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  859. //
  860. //
  861. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  862. //
  863. // //设置请求头(GET)
  864. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  865. // [request setValue:range forHTTPHeaderField:@"Range"];
  866. //
  867. // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  868. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  869. //设置请求头(GET)
  870. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  871. [request setValue:range forHTTPHeaderField:@"Range"];
  872. self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  873. }else{ //暂停
  874. DebugLog(@"%d pause",taskidx);
  875. [self.connection cancel];
  876. self.connection = nil;
  877. }
  878. });
  879. }
  880. -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order
  881. {
  882. [self add_downloadlog:@"Begin sync, please wait."];
  883. [self add_downloadlog:@"Prepare upload data."];
  884. // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
  885. NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order];
  886. NSString* upfile=upjson[@"file"];
  887. {
  888. NSData* data = [NSData dataWithContentsOfFile: upfile];
  889. UIApplication * app = [UIApplication sharedApplication];
  890. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  891. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  892. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  893. if(appDelegate.user!=nil)
  894. [params setValue:appDelegate.user forKey:@"user"];
  895. // if(appDelegate.contact_id!=nil)
  896. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  897. if(appDelegate.password!=nil)
  898. [params setValue:appDelegate.password forKey:@"password"];
  899. #if TARGET_IPHONE_SIMULATOR//模拟器
  900. [params setValue:@"simulator_uuid" forKey:@"idfv"];
  901. #elif TARGET_OS_IPHONE//真机
  902. UIDevice * dev = [UIDevice currentDevice];
  903. NSUUID* uuid =dev.identifierForVendor;
  904. [params setValue:uuid.UUIDString forKey:@"idfv"];
  905. #endif
  906. __weak typeof(self) weakSelf = self;
  907. [NetworkUtils upload:data FileName:[upfile lastPathComponent] Params:params ToHost:URL_UPLOAD_OFFLINE Result:^(NSMutableDictionary *json) {
  908. if([[json valueForKey:@"result"] intValue]==2)
  909. {
  910. NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  911. if (out_of_stock_ids) {
  912. [RAUtils message_alert:[NSString stringWithFormat:@"Below orders were not submitted because some models were out of stock. You can check from order history under online mode.\n %@",out_of_stock_ids] title:@"Warning" controller:self.main_vc];
  913. }
  914. [weakSelf add_downloadlog:@"Upload successful."];
  915. appDelegate.disable_trigger=true;
  916. NSString* so_id=[RAConvertor arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  917. [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  918. [iSalesDB execSql:@"delete from wishlist"];
  919. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  920. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  921. [iSalesDB execSql:@"delete from offline_portfolio"];
  922. [iSalesDB execSql:@"delete from offline_pdf"];
  923. [OLDataProvider offline_clear_PDFCache];
  924. NSString* contactMap = json[@"contactMap"];
  925. if(contactMap.length>0)
  926. {
  927. NSDictionary* contactjson = [RAConvertor string2dict:contactMap];
  928. NSArray *keys= [contactjson allKeys];
  929. //遍历keys
  930. for(int i=0;i<[keys count];i++)
  931. {
  932. //得到当前key
  933. NSString *key=[keys objectAtIndex:i];
  934. //如果key不是pic,说明value是字符类型,比如name:Boris
  935. NSString* value = [contactjson valueForKey:key];
  936. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  937. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  938. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  939. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  940. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  941. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  942. }
  943. }
  944. // NSDictionary* contactjson= upjson[@"contact"];
  945. // NSDictionary* wishlistjson= upjson[@"wishlist"];
  946. // NSDictionary* orderjson= upjson[@"order"];
  947. appDelegate.disable_trigger=false;
  948. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  949. [defaults removeObjectForKey:@"Forcedownload"];
  950. [defaults setBool:true forKey:@"Forcedownload"];
  951. [defaults synchronize];
  952. [weakSelf download_offline:ver useInternalAddress:buseinternaladdress];
  953. }
  954. else
  955. {
  956. [weakSelf add_downloadlog:[json valueForKey:@"msg"]];
  957. [weakSelf add_downloadlog:@"Sync canceled."];
  958. [weakSelf.settingUI onSyncFinish];
  959. }
  960. } Progress:^(NSURLSessionTask *task, double progress) {
  961. } DecryptHandler:nil];
  962. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  963. //
  964. // serializer.timeoutInterval=300;
  965. //
  966. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_OFFLINE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  967. // [formData appendPartWithFileData:data name:@"upfile" fileName:[upfile lastPathComponent] mimeType:@"application/zip"];
  968. // } error:nil];
  969. //
  970. //
  971. //
  972. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  973. //
  974. // NSProgress *progress = nil;
  975. //
  976. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  977. //
  978. //
  979. //
  980. // if (error) {
  981. //
  982. // NSString* err_msg = [error localizedDescription];
  983. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  984. //
  985. //
  986. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  987. //
  988. // DebugLog(@"data string: %@",str);
  989. // [self add_downloadlog:err_msg];
  990. // [self add_downloadlog:@"Can not connect to server please try again."];
  991. // [self.settingUI onSyncFinish];
  992. //
  993. // } else {
  994. // DebugLog(@"response ");
  995. //
  996. //
  997. //
  998. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  999. //
  1000. // // 再将NSData转为字符串
  1001. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1002. //
  1003. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  1004. //
  1005. // DebugLog(@"data string: %@",jsonStr);
  1006. //
  1007. // NSDictionary* json = responseObject;
  1008. //
  1009. //
  1010. // if([[json valueForKey:@"result"] intValue]==2)
  1011. // {
  1012. // NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  1013. // if (out_of_stock_ids) {
  1014. // [RAUtils message_alert:[NSString stringWithFormat:@"Below orders were not submitted because some models were out of stock. You can check from order history under online mode.\n %@",out_of_stock_ids] title:@"Warning" controller:self.main_vc];
  1015. // }
  1016. //
  1017. // [self add_downloadlog:@"Upload successful."];
  1018. // appDelegate.disable_trigger=true;
  1019. // NSString* so_id=[RAUtils arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  1020. //
  1021. // [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  1022. // [iSalesDB execSql:@"delete from wishlist"];
  1023. // [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  1024. // [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  1025. // [iSalesDB execSql:@"delete from offline_portfolio"];
  1026. // [iSalesDB execSql:@"delete from offline_pdf"];
  1027. // [OLDataProvider offline_clear_PDFCache];
  1028. //
  1029. // NSString* contactMap = json[@"contactMap"];
  1030. // if(contactMap.length>0)
  1031. // {
  1032. // NSDictionary* contactjson = [RAUtils string2dict:contactMap];
  1033. // NSArray *keys= [contactjson allKeys];
  1034. // //遍历keys
  1035. // for(int i=0;i<[keys count];i++)
  1036. // {
  1037. // //得到当前key
  1038. // NSString *key=[keys objectAtIndex:i];
  1039. // //如果key不是pic,说明value是字符类型,比如name:Boris
  1040. // NSString* value = [contactjson valueForKey:key];
  1041. //
  1042. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1043. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1044. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1045. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1046. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1047. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1048. //
  1049. // }
  1050. // }
  1051. // // NSDictionary* contactjson= upjson[@"contact"];
  1052. // // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1053. // // NSDictionary* orderjson= upjson[@"order"];
  1054. //
  1055. // appDelegate.disable_trigger=false;
  1056. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1057. // [defaults removeObjectForKey:@"Forcedownload"];
  1058. // [defaults setBool:true forKey:@"Forcedownload"];
  1059. // [defaults synchronize];
  1060. //
  1061. // [self download_offline:ver useInternalAddress:buseinternaladdress];
  1062. //
  1063. // }
  1064. // else
  1065. // {
  1066. // [self add_downloadlog:[json valueForKey:@"msg"]];
  1067. // [self add_downloadlog:@"Sync canceled."];
  1068. // [self.settingUI onSyncFinish];
  1069. // }
  1070. //
  1071. //
  1072. // }
  1073. // // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  1074. // }];
  1075. //
  1076. //
  1077. //
  1078. //
  1079. //
  1080. //
  1081. //
  1082. // [uploadTask resume];
  1083. }
  1084. return;
  1085. }
  1086. -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
  1087. {
  1088. NSString *plistPath = [RAUtils get_config_path];
  1089. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1090. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1091. {
  1092. ver= nil;
  1093. [self add_downloadlog:@"App required a fully sync."];
  1094. }
  1095. if(self.downloading)
  1096. return;
  1097. self.downloading=true;
  1098. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1099. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1100. NSString* pvid = [defaults stringForKey:@"vid"] ;
  1101. [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
  1102. NSMutableDictionary* json=[[RANetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
  1103. if([json[@"result"] intValue]!=2)
  1104. {
  1105. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1106. [self.settingUI onSyncFinish];
  1107. dispatch_async(dispatch_get_main_queue(), ^{
  1108. // self.downloadlog=nil;
  1109. self.downloading=false;
  1110. });
  1111. return;
  1112. }
  1113. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1114. NSMutableDictionary* download_json=nil;
  1115. // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1116. NSString* downSerial=[json valueForKey:@"downSerial"];
  1117. [defaults removeObjectForKey:@"downSerial"];
  1118. [defaults setValue:downSerial forKey:@"downSerial"];
  1119. [defaults synchronize];
  1120. // sleep(3);
  1121. //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1122. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1123. int count=0;
  1124. // __block bool preparing = true;
  1125. while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1126. {
  1127. sleep(RETRY_DELAY);
  1128. count++;
  1129. download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1130. }
  1131. //服务器准备数据完毕,进入处理数据逻辑。
  1132. if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1133. {
  1134. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1135. dispatch_async(dispatch_get_main_queue(), ^{
  1136. // self.downloadlog=nil;
  1137. self.downloading=false;
  1138. });
  1139. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1140. [self.settingUI onSyncFinish];
  1141. return;
  1142. //一直没取到json,出错处理
  1143. }
  1144. else
  1145. {
  1146. if([download_json[@"count"] intValue]==0)
  1147. {
  1148. //没有找到更新包,当前是最新版本
  1149. [self add_downloadlog:@"You are up-to-date!"];
  1150. dispatch_async(dispatch_get_main_queue(), ^{
  1151. // self.downloadlog=nil;
  1152. self.downloading=false;
  1153. });
  1154. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1155. [self.settingUI onSyncFinish];
  1156. return;
  1157. }
  1158. else
  1159. {
  1160. [self add_downloadlog:@"Find a new version, downloading..."];
  1161. self.download_task = [download_json mutableCopy];
  1162. // self.download_task[@"abcdef"]=@"abcdef";
  1163. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1164. [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1165. [self download_offline:true checkdiskspace:true];
  1166. return;
  1167. }
  1168. }
  1169. });
  1170. }
  1171. -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
  1172. {
  1173. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1174. bool forcedownload = [defaults boolForKey:@"Forcedownload"];
  1175. if(forcedownload|| ver==nil)
  1176. {
  1177. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1178. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1179. syncVC.action_string=@"Download";
  1180. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1181. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1182. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1183. [parent presentViewController:navi animated:YES completion:^{
  1184. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1185. DebugLog(@"about present.........");
  1186. // self.btop = false;
  1187. // <#code#>
  1188. }];
  1189. }
  1190. else
  1191. {
  1192. NSArray* arr_order=nil;
  1193. arr_order=[OLDataProvider enumOfflineOrder];
  1194. // if(arr_order.count>0)
  1195. // {
  1196. //
  1197. // {
  1198. // SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
  1199. // vc.returnValue = ^(NSArray* SelectedOrder){
  1200. //
  1201. // [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
  1202. // SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1203. // syncVC.action_string=@"Download";
  1204. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1205. //
  1206. //
  1207. //
  1208. //
  1209. //
  1210. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1211. //
  1212. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1213. // [parent presentViewController:navi animated:YES completion:^{
  1214. //
  1215. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1216. //
  1217. // DebugLog(@"about present.........");
  1218. //
  1219. // // self.btop = false;
  1220. // // <#code#>
  1221. // }];
  1222. // };
  1223. //
  1224. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
  1225. //
  1226. //
  1227. //
  1228. //
  1229. //
  1230. //
  1231. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1232. // [parent presentViewController:navi animated:YES completion:^{
  1233. //
  1234. //
  1235. // }];
  1236. // }
  1237. //
  1238. //
  1239. // }
  1240. // else
  1241. {
  1242. [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order];
  1243. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1244. syncVC.action_string=@"Download";
  1245. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1246. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1247. [parent presentViewController:navi animated:YES completion:^{
  1248. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1249. DebugLog(@"about present.........");
  1250. // self.btop = false;
  1251. // <#code#>
  1252. }];
  1253. }
  1254. }
  1255. }
  1256. -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
  1257. {
  1258. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1259. if(start)
  1260. {
  1261. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1262. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1263. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1264. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1265. long long needsize = size+500;
  1266. if(needsize>freespace &&checkdiskspace)
  1267. {
  1268. //size not enough.
  1269. NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
  1270. [self add_downloadlog:space];
  1271. [self.settingUI onSyncFinish];
  1272. return ;
  1273. }
  1274. NSString* temp = NSTemporaryDirectory();
  1275. NSString * ver = self.download_task[@"ver"];
  1276. NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
  1277. //创建版本临时目录
  1278. NSFileManager* fileManager = [NSFileManager defaultManager];
  1279. BOOL bdir=YES;
  1280. if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
  1281. {
  1282. NSError *error = nil;
  1283. bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1284. if(!bsuccess)
  1285. DebugLog(@"Create temp folder failed");
  1286. // if(bsuccess)
  1287. // {
  1288. // sqlite3 *db = [self get_db];
  1289. //
  1290. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  1291. // [iSalesDB close_db:db];
  1292. // }
  1293. }
  1294. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
  1295. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1296. if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
  1297. {
  1298. NSError *error = nil;
  1299. bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1300. if(!bsuccess)
  1301. DebugLog(@"Create cache folder failed");
  1302. }
  1303. NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
  1304. NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
  1305. // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
  1306. // {
  1307. //
  1308. // NSError *error = nil;
  1309. // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
  1310. //
  1311. // if(!bsuccess)
  1312. // DebugLog(@"Create resource folder failed");
  1313. //
  1314. // }
  1315. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1316. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  1317. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  1318. NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
  1319. // tempdb=[documents stringByAppendingPathComponent:DBNAME];
  1320. NSError *error = nil;
  1321. bdir=NO;
  1322. if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
  1323. {
  1324. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  1325. if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
  1326. {
  1327. DebugLog(@"copy database failed");
  1328. }
  1329. }
  1330. bdir=YES;
  1331. error=nil;
  1332. int count = [[self.download_task valueForKey:@"count"] intValue];
  1333. bool alldone=true;
  1334. bool trouble=false;
  1335. bool response = false;
  1336. for (int i = 0;i<count;i++)
  1337. {
  1338. NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
  1339. NSString* url = [itemjson valueForKey:@"url"];
  1340. NSString* type = [itemjson valueForKey:@"type"];
  1341. {
  1342. #ifdef DEBUG
  1343. //调试模式下跳过下载图片
  1344. if([type isEqualToString:@"img"])
  1345. {
  1346. itemjson[@"status"]=@"finish";
  1347. continue;
  1348. }
  1349. #endif
  1350. }
  1351. NSString* status = itemjson[@"status"];
  1352. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1353. if(! [status isEqualToString:@"finish"])
  1354. {
  1355. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1356. {
  1357. [self handle_download:url start:start type:type taskid:i];
  1358. alldone=false;
  1359. break;
  1360. }
  1361. else
  1362. {
  1363. alldone=false;
  1364. trouble=true;
  1365. response = [itemjson[@"response"] boolValue];
  1366. break;
  1367. }
  1368. }
  1369. }
  1370. if(trouble)
  1371. {
  1372. NSString* msg =@"offline sync got some trouble, sync canceled.";
  1373. if(response==false)
  1374. {
  1375. msg=@"Cannot connect to server, please check your network.";
  1376. }
  1377. [self add_downloadlog:msg];
  1378. dispatch_async(dispatch_get_main_queue(), ^{
  1379. // self.downloadlog=nil;
  1380. self.downloading=false;
  1381. });
  1382. [self.settingUI onSyncFinish];
  1383. }
  1384. else if(alldone)
  1385. {
  1386. [self add_downloadlog:@"Finalizing download..."];
  1387. //全部下载完成;
  1388. //写入当前版本
  1389. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1390. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1391. NSString* lastsync = [formatter stringFromDate:[NSDate date]];
  1392. NSString* ver= self.download_task[@"ver"];
  1393. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1394. NSString *cachefolder = [paths objectAtIndex:0];
  1395. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  1396. //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
  1397. if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
  1398. {
  1399. DebugLog(@"move image folder failed");
  1400. [self add_downloadlog:@"move image folder failed"];
  1401. trouble=true;
  1402. }
  1403. else
  1404. {
  1405. DebugLog(@"move image folder successful");
  1406. }
  1407. error=nil;
  1408. // copy temp db to cache.
  1409. if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
  1410. {
  1411. if(![fileManager removeItemAtPath:database_path error:nil])
  1412. {
  1413. DebugLog(@"delete database failed");
  1414. }
  1415. else
  1416. {
  1417. if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1418. {
  1419. DebugLog(@"copy database failed");
  1420. [self add_downloadlog:@"copy database failed"];
  1421. trouble=true;
  1422. }
  1423. else{
  1424. BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1425. // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
  1426. }
  1427. }
  1428. }
  1429. else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1430. {
  1431. DebugLog(@"copy database failed");
  1432. BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1433. [self add_downloadlog:@"copy database failed"];
  1434. trouble=true;
  1435. }
  1436. // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
  1437. // {
  1438. // DebugLog(@"move db file failed");
  1439. // }
  1440. // else
  1441. // {
  1442. // DebugLog(@"move db file successful");
  1443. // }
  1444. error=nil;
  1445. if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
  1446. {
  1447. DebugLog(@"move data folder failed");
  1448. [self add_downloadlog:@"move data folder failed"];
  1449. trouble=true;
  1450. }
  1451. else
  1452. {
  1453. DebugLog(@"move data folder successful");
  1454. }
  1455. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1456. if(trouble)
  1457. {
  1458. [self add_downloadlog:@"offline sync failed."];
  1459. // 尚缺更新失败还原逻辑。
  1460. }
  1461. else
  1462. {
  1463. [self add_downloadlog:@"offline sync complete."];
  1464. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1465. [defaults removeObjectForKey:@"OfflineVer"];
  1466. [defaults setValue:ver forKey:@"OfflineVer"];
  1467. [defaults removeObjectForKey:@"LastSync"];
  1468. [defaults setValue:lastsync forKey:@"LastSync"];
  1469. [defaults removeObjectForKey:@"vid"];
  1470. [defaults setValue:self.vid forKey:@"vid"];
  1471. [defaults removeObjectForKey:@"Forcedownload"];
  1472. NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1473. [defaults removeObjectForKey:@"downSerial"];
  1474. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1475. [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1476. [defaults synchronize];
  1477. NSString *plistPath = [RAUtils get_config_path];
  1478. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1479. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1480. {
  1481. config_list[@"NEED_FULLY_SYNC"] = @"false";
  1482. [config_list writeToFile:plistPath atomically:YES];
  1483. }
  1484. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1485. NSDictionary* editor_json = [RANetwork finish_download_Offline:downSerial];
  1486. });
  1487. }
  1488. dispatch_async(dispatch_get_main_queue(), ^{
  1489. // self.downloadlog=nil;
  1490. self.downloading=false;
  1491. self.download_task=nil;
  1492. self.vid=nil;
  1493. [self.settingUI onSyncFinish];
  1494. });
  1495. }
  1496. }
  1497. else
  1498. {
  1499. int count = [[self.download_task valueForKey:@"count"] intValue];
  1500. for (int i = 0;i<count;i++)
  1501. {
  1502. NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
  1503. NSString* url = [itemjson valueForKey:@"url"];
  1504. NSString* type = [itemjson valueForKey:@"type"];
  1505. NSString* status = itemjson[@"status"];
  1506. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1507. if(! [status isEqualToString:@"finish"])
  1508. {
  1509. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1510. {
  1511. [self handle_download:url start:start type:type taskid:i];
  1512. break;
  1513. }
  1514. }
  1515. }
  1516. dispatch_async(dispatch_get_main_queue(), ^{
  1517. self.downloading=false;
  1518. });
  1519. }
  1520. }
  1521. -(void) add_downloadlog:(NSString*) newtext
  1522. {
  1523. // if(!self.downloading)
  1524. // return;
  1525. dispatch_async(dispatch_get_main_queue(), ^{
  1526. NSString* date;
  1527. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1528. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1529. date = [formatter stringFromDate:[NSDate date]];
  1530. if(newtext.length<=0)
  1531. return;
  1532. NSString* text = self.downloadlog;
  1533. if(text.length==0)
  1534. text=@"";
  1535. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1536. self.downloadlog = text;
  1537. [self.settingUI onLogUpdate];
  1538. });
  1539. }
  1540. -(int)unpack
  1541. {
  1542. //return;
  1543. //DebugLog(_fileName);
  1544. ///Users/Ray/Library/Developer/CoreSimulator/Devices/0852B217-599B-41C2-95BA-4755B02B7FA0/data/Containers/Data/Application/FC6AC5D0-2ADF-4A3B-935D-059078622031/Library/Caches/apache-tomcat-8.0.22.zip
  1545. //文件路径
  1546. // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  1547. NSString* temp = NSTemporaryDirectory();
  1548. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1549. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
  1550. NSString * ver = self.download_task[@"ver"];
  1551. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
  1552. NSString *zipFile = [temp stringByAppendingPathComponent:location];
  1553. ZipArchive* zip = [[ZipArchive alloc] init];
  1554. // filename stringByDeletingPathExtension
  1555. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1556. // NSString *cachefolder = [paths objectAtIndex:0];
  1557. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1558. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1559. //
  1560. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1561. // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  1562. //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
  1563. // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
  1564. DebugLog(@"path: %@",unZipTo);
  1565. if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
  1566. BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
  1567. if( NO==result )
  1568. {
  1569. // int aaa=0;
  1570. //解压失败
  1571. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1572. if(freespace<=10)
  1573. {
  1574. return UNZIP_NO_SPACE;
  1575. }
  1576. [zip UnzipCloseFile];
  1577. //文件损坏,删除文件重试
  1578. NSFileManager* fileManager=[NSFileManager defaultManager];
  1579. BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
  1580. [fileManager removeItemAtPath:unZipTo error:nil];
  1581. return UNZIP_FILE_DAMAGE;
  1582. }
  1583. else
  1584. {
  1585. [zip UnzipCloseFile];
  1586. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
  1587. NSFileManager *fileManager = [NSFileManager defaultManager];
  1588. [fileManager removeItemAtPath:zipFile error:nil];
  1589. return UNZIP_SUCCESS;
  1590. //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
  1591. }
  1592. //[zip UnzipCloseFile];
  1593. }
  1594. else
  1595. {
  1596. //打开文件失败,通常是文件路径有问题或密码错误。
  1597. return UNZIP_OPEN_FAILED;
  1598. NSFileManager *fileManager = [NSFileManager defaultManager];
  1599. [fileManager removeItemAtPath:zipFile error:nil];
  1600. }
  1601. // [zip release];
  1602. }
  1603. #pragma mark - NSURLConnectionDelegate
  1604. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  1605. DebugLog(@"%d error message:%@",self.current_task,error);
  1606. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1607. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  1608. currenttask[@"status"] = @"pause";
  1609. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1610. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1611. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1612. // self.currentLength = 0;
  1613. // self.fileLength = 0;
  1614. [self.fileHandle closeFile];
  1615. self.fileHandle = nil;
  1616. [self.connection cancel];
  1617. self.connection = nil;
  1618. [self download_offline:true checkdiskspace:false];
  1619. }
  1620. #pragma mark - NSURLConnectionDataDelegate
  1621. /**
  1622. *请求失败
  1623. */
  1624. /**
  1625. *接收到服务器的响应
  1626. */
  1627. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  1628. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  1629. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  1630. DebugLog(@"%d begin",self.current_task);
  1631. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1632. //获取下载文件大小
  1633. // self.fileLength = response.expectedContentLength;
  1634. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1635. //获取文件名
  1636. //self.fileName = response.suggestedFilename;
  1637. currenttask[@"fileName"] = response.suggestedFilename;
  1638. currenttask[@"response"] = @"true";
  1639. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  1640. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1641. //文件路径
  1642. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  1643. NSString * ver = self.download_task[@"ver"];
  1644. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  1645. NSString *filePath = [temp stringByAppendingPathComponent:location];
  1646. DebugLog(@"save to: %@",filePath);
  1647. if (position>0) {
  1648. //不需要创建文件;
  1649. //创建一个用来写数据的文件句柄
  1650. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1651. return;
  1652. }
  1653. // 第一次获取的才是文件正确大小
  1654. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  1655. //创建一个空的文件到沙盒
  1656. NSFileManager *fileManager = [NSFileManager defaultManager];
  1657. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  1658. //创建一个用来写数据的文件句柄
  1659. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1660. }else{
  1661. //debug 这里缺少文件的情况还没处理
  1662. [self.connection cancel];
  1663. self.connection = nil;
  1664. DebugLog(@"该文件不存在");
  1665. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",httpresponse.statusCode];
  1666. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  1667. [self add_downloadlog:str_status];
  1668. }
  1669. }
  1670. /**
  1671. *接收到服务器返回的数据(可能被调用多次)
  1672. */
  1673. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  1674. //移动到文件末尾
  1675. [self.fileHandle seekToEndOfFile];
  1676. //写入数据到文件
  1677. [self.fileHandle writeData:data];
  1678. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1679. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1680. position += data.length;
  1681. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  1682. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1683. //更新画面中的进度
  1684. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  1685. double progress = (double)position/fileLength;
  1686. self.file_progress = progress;
  1687. [self.settingUI onProgressUpdate];
  1688. }
  1689. /**
  1690. *服务器返回数据完了
  1691. */
  1692. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  1693. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1694. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  1695. DebugLog(@"%d finish",self.current_task);
  1696. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  1697. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1698. // self.currentLength = 0;
  1699. // self.fileLength = 0;
  1700. [self.fileHandle closeFile];
  1701. self.fileHandle = nil;
  1702. int result=[self unpack];
  1703. NSString* temp = NSTemporaryDirectory();
  1704. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1705. NSString * ver = self.download_task[@"ver"];
  1706. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1707. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1708. switch (result) {
  1709. case UNZIP_FILE_DAMAGE:
  1710. {
  1711. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1712. currenttask[@"status"] = @"pause";
  1713. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1714. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1715. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1716. // self.currentLength = 0;
  1717. // self.fileLength = 0;
  1718. [self.fileHandle closeFile];
  1719. self.fileHandle = nil;
  1720. [self.connection cancel];
  1721. self.connection = nil;
  1722. break;
  1723. }
  1724. case UNZIP_SUCCESS:
  1725. {
  1726. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  1727. if([type isEqualToString:@"img"])
  1728. {
  1729. NSString* parent_path = self.download_task[@"path"];
  1730. if(parent_path.length==0)
  1731. parent_path=@"";
  1732. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  1733. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  1734. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  1735. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1736. BOOL bdir=YES;
  1737. NSError *error = nil;
  1738. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  1739. {
  1740. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1741. if(!bsuccess)
  1742. DebugLog(@"Create temp folder failed");
  1743. }
  1744. error=nil;
  1745. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  1746. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  1747. // NSError *error = nil;
  1748. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  1749. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  1750. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  1751. // backupItemName:backup
  1752. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  1753. // resultingItemURL:nil error:&error])
  1754. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  1755. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  1756. {
  1757. DebugLog(@"move image folder failed");
  1758. }
  1759. else
  1760. {
  1761. currenttask[@"status"] = @"finish";
  1762. DebugLog(@"move image folder successful");
  1763. }
  1764. }
  1765. else if([type isEqualToString:@"sql"])
  1766. {
  1767. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  1768. NSString * ver = self.download_task[@"ver"];
  1769. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  1770. tempdb=[temp stringByAppendingPathComponent:tempdb];
  1771. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  1772. [self add_downloadlog:@"updating local database..."];
  1773. @try {
  1774. char *errmsg=NULL;
  1775. appDelegate.disable_trigger=true;
  1776. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  1777. {
  1778. sqlite3_exec(tdb, "drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;drop trigger if exists offline_portfolio_insert;drop trigger if exists offline_portfolio_update;drop trigger if exists offline_portfolio_delete;drop trigger if exists offline_pdf_insert;drop trigger if exists offline_pdf_update;drop trigger if exists offline_pdf_delete;offline_pdf;", NULL, NULL, &errmsg);
  1779. sqlite3_free(errmsg);
  1780. DebugLog(@"开启事务");
  1781. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  1782. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  1783. int count = [orderjson[@"count"] intValue];
  1784. for(int i=0;i<count;i++)
  1785. {
  1786. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  1787. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  1788. NSError *error = nil;
  1789. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  1790. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  1791. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  1792. {
  1793. //throw exception;
  1794. if(errmsg==nil)
  1795. errmsg="Unknown error.";
  1796. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  1797. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  1798. }
  1799. sqlite3_free(errmsg);
  1800. }
  1801. sqlite3_exec(tdb, "CREATE TRIGGER if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists wishlist_update after update on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;", NULL, NULL, &errmsg);
  1802. }
  1803. //提交事务
  1804. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  1805. DebugLog(@"提交事务");
  1806. sqlite3_free(errmsg);
  1807. }
  1808. [self add_downloadlog:@"updating local database successful"];
  1809. currenttask[@"status"] = @"finish";
  1810. }
  1811. @catch (NSException *exception) {
  1812. char *errmsg=NULL;
  1813. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  1814. [self add_downloadlog:@"updating local database failed rollback..."];
  1815. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  1816. DebugLog(@"回滚事务");
  1817. }
  1818. else
  1819. {
  1820. [self add_downloadlog:@"rollback failed."];
  1821. }
  1822. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1823. currenttask[@"status"] = @"pause";
  1824. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1825. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  1826. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1827. // self.currentLength = 0;
  1828. // self.fileLength = 0;
  1829. [self.fileHandle closeFile];
  1830. self.fileHandle = nil;
  1831. [self.connection cancel];
  1832. self.connection = nil;
  1833. //break;
  1834. }
  1835. @finally {
  1836. appDelegate.disable_trigger=false;
  1837. sqlite3_close(tdb);
  1838. // [iSalesDB close_db:tdb];
  1839. // [self SelectData];
  1840. }
  1841. }
  1842. else if([type isEqualToString:@"script"])
  1843. {
  1844. currenttask[@"status"] = @"finish";
  1845. }
  1846. else if([type isEqualToString:@"resource"])
  1847. {
  1848. currenttask[@"status"] = @"finish";
  1849. }
  1850. int c=self.current_task+1;
  1851. double t=[ self.download_task[@"count"] doubleValue];
  1852. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  1853. self.overall_progress = oprogress;
  1854. [self.settingUI onProgressUpdate];
  1855. break;
  1856. }
  1857. case UNZIP_NO_SPACE:
  1858. {
  1859. [self add_downloadlog:@"Disk space not enough."];
  1860. break;
  1861. }
  1862. case UNZIP_OPEN_FAILED:
  1863. {
  1864. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  1865. break;
  1866. }
  1867. default:
  1868. break;
  1869. }
  1870. [self download_offline:true checkdiskspace:false];
  1871. }
  1872. -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
  1873. {
  1874. RAPDFViewController *ViewController = [self.main_vc.storyboard instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
  1875. ViewController.url = url;
  1876. ViewController.canSave = false;
  1877. ViewController.mail_content = content;
  1878. if(soid==nil)
  1879. soid =@"";
  1880. if(company==nil)
  1881. company =@"";
  1882. ViewController.save_name =soid;
  1883. NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
  1884. if(send_to.length>0)
  1885. {
  1886. arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  1887. // customer_email compo
  1888. // [send_to addObject:customer_email];
  1889. }
  1890. ViewController.mail_to = arrsend_to;
  1891. #if defined(BUILD_NPD) || defined(BUILD_USAI)
  1892. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];//[arr_subject componentsJoinedByString:@" : "];
  1893. if (self.user_type == USER_ROLE_CUSTOMER && ![Singleton sharedInstance].currentOrderIsMerged) {
  1894. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  1895. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  1896. }
  1897. #else
  1898. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];
  1899. #endif
  1900. ViewController.mail_subject = subject;
  1901. // NSString* subject;
  1902. // if (company.length==0) {
  1903. // NSString* cur_time =[RAUtils current_date];
  1904. // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
  1905. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  1906. // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
  1907. //
  1908. //
  1909. // NSMutableArray* send_to = [[NSMutableArray alloc]init];
  1910. // if(customer_email.length>0)
  1911. // {
  1912. // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  1913. // // customer_email compo
  1914. // // [send_to addObject:customer_email];
  1915. // }
  1916. // ViewController.mail_to = send_to;
  1917. // }
  1918. // else
  1919. // {
  1920. // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
  1921. // }
  1922. // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
  1923. // ViewController.mail_subject = subject;
  1924. ViewController.autoPrint=true;
  1925. ViewController.hidenavi = false;
  1926. [self.main_vc.navigationController pushViewController:ViewController animated:YES];
  1927. // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
  1928. }
  1929. //-(void) addScannerReceiver:(NSString*)classname
  1930. //{
  1931. // [self.arr_scannerReceiver addObject:classname];
  1932. //}
  1933. -(void) setScannerDelegate:(id<ScanApiHelperDelegate>)delegate
  1934. {
  1935. [ScanApi setDelegate:delegate];
  1936. }
  1937. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  1938. {
  1939. self.window.backgroundColor = [UIColor whiteColor];
  1940. // [RAUtils expression_varable:nil regex:nil];
  1941. self.disable_trigger = false;
  1942. [self initialExceptionHandler];
  1943. [self becomeObserver];
  1944. #ifdef BUILD_NPD
  1945. [self setUpGoogleAnalytics];
  1946. #endif
  1947. [DefaultAppearance init_appearance];
  1948. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1949. NSString *cachefolder = [paths objectAtIndex:0];
  1950. NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
  1951. // upfolder = [upfolder stringByAppendingPathComponent:serial];
  1952. NSFileManager* fileManager = [NSFileManager defaultManager];
  1953. BOOL bdir=YES;
  1954. if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
  1955. {
  1956. NSError *error = nil;
  1957. bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1958. if(!bsuccess)
  1959. DebugLog(@"Create UPLOAD folder failed");
  1960. }
  1961. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  1962. if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
  1963. {
  1964. NSError *error = nil;
  1965. bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
  1966. if(!bsuccess)
  1967. DebugLog(@"Create PDF Cache folder failed");
  1968. }
  1969. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  1970. //
  1971. // DebugLog(@"文件已经存在了");
  1972. //
  1973. // }
  1974. // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
  1975. // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
  1976. //
  1977. //
  1978. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1979. // NSString *documents = [paths objectAtIndex:0];
  1980. // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
  1981. //
  1982. //
  1983. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  1984. //
  1985. // DebugLog(@"文件已经存在了");
  1986. //
  1987. // }
  1988. // else
  1989. // {
  1990. //
  1991. //
  1992. //
  1993. // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
  1994. //
  1995. // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
  1996. //
  1997. // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
  1998. //
  1999. // [[NSFileManager defaultManager] createFileAtPath:dist_path
  2000. //
  2001. // contents:mainBundleFile
  2002. //
  2003. // attributes:nil];
  2004. //
  2005. // }
  2006. self.recent_model = [[NSMutableDictionary alloc]init];
  2007. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2008. bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
  2009. self.offline_mode = offline;
  2010. // Override point for customization after application launch.
  2011. if ( [iSalesDB initializeDb]!=0)
  2012. DebugLog(@"init db failed");
  2013. // disable apn
  2014. // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
  2015. self.contact_id=nil;
  2016. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2017. NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
  2018. if([enable_cache isEqualToString:@"false"])
  2019. self.bEnable_Cache = false;
  2020. else
  2021. self.bEnable_Cache = true;
  2022. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  2023. self.build =[infoDict objectForKey:@"CFBundleVersion"];
  2024. //scanner
  2025. _feedbackStack=[[NSMutableArray alloc]init];
  2026. self.devices=[[NSMutableArray alloc]init];
  2027. // change this to YES if you want SingleEntry to
  2028. // confirm the decoded data
  2029. self.doAppDataConfirmation=NO;
  2030. if(ScanApi==nil){
  2031. #ifdef USE_SOFTSCAN
  2032. // this is useful for SoftScan to keep a handle
  2033. // that is used in the trigger button
  2034. _softScanDeviceInfo=nil;
  2035. #endif
  2036. ScanApi=[[ScanApiHelper alloc]init];
  2037. [ScanApi setDelegate:self];
  2038. self.enable_ScannerLog = true;
  2039. self.api_Status= API_STOP;
  2040. // UIApplication * app = [UIApplication sharedApplication];
  2041. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  2042. //
  2043. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2044. bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
  2045. if(autolaunch==true)
  2046. [self enableScanner:autolaunch];
  2047. }
  2048. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2049. [self handleErrorLog];
  2050. });
  2051. return YES;
  2052. }
  2053. #pragma mark - Feedback stack
  2054. -(void)pushFeedback:(id<ScannerEventsFeedback>)feedback{
  2055. long index =[_feedbackStack indexOfObject:feedback];
  2056. if(index!=NSNotFound)
  2057. {
  2058. // if(index!=_feedbackStack.count-1)
  2059. // {
  2060. // [_feedbackStack exchangeObjectAtIndex:index withObjectAtIndex:_feedbackStack.count-1];
  2061. // _eventsFeedback = feedback;
  2062. // }
  2063. }
  2064. else
  2065. {
  2066. [_feedbackStack addObject:feedback];
  2067. }
  2068. _eventsFeedback = feedback;
  2069. // if(_eventsFeedback != feedback){
  2070. // if(_eventsFeedback!=nil){
  2071. // [_feedbackStack addObject:_eventsFeedback];
  2072. // }
  2073. // _eventsFeedback=feedback;
  2074. //// [self generateDeviceArrivals];
  2075. // }
  2076. }
  2077. -(void)popFeedback:(id<ScannerEventsFeedback>)feedback{
  2078. [_feedbackStack removeObject:feedback];
  2079. if(_feedbackStack.count>0)
  2080. _eventsFeedback = _feedbackStack[_feedbackStack.count-1];
  2081. else
  2082. _eventsFeedback = nil;
  2083. // if(_eventsFeedback ==feedback){
  2084. // if(_feedbackStack.count>0){
  2085. // id<ScannerEventsFeedback> newDelegate=[_feedbackStack objectAtIndex:_feedbackStack.count-1];
  2086. // [_feedbackStack removeLastObject];
  2087. // _eventsFeedback = newDelegate;
  2088. // // generate a device Arrival for each scanner we've already receive
  2089. // // so that the new view can be aware of the connected scanners
  2090. //// [self generateDeviceArrivals];
  2091. // }
  2092. // else{
  2093. // _eventsFeedback=nil;
  2094. // }
  2095. // }
  2096. }
  2097. -(void)setFeedback:(id<ScannerEventsFeedback>)feedback
  2098. {
  2099. _eventsFeedback = feedback;
  2100. }
  2101. #pragma mark - ScanApiHelper complete delegates
  2102. // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
  2103. // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
  2104. // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
  2105. // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
  2106. // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
  2107. // callback received when the Get Symbology Status is completed
  2108. -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
  2109. [self addlog:@"onGetSymbologyDpm:"];
  2110. SKTRESULT result=[[scanObj Msg]Result];
  2111. if(SKTSUCCESS(result)){
  2112. DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
  2113. if(deviceInfo!=nil){
  2114. ISktScanSymbology* symbology=[[scanObj Property]Symbology];
  2115. if([symbology getStatus]==kSktScanSymbologyStatusDisable){
  2116. [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
  2117. }
  2118. }
  2119. }
  2120. else{
  2121. // an error message should be displayed here
  2122. // indicating that the DPM symbology status cannot be retrieved
  2123. }
  2124. }
  2125. // callback received when the Set Symbology Status is completed
  2126. -(void)onSetSymbology:(ISktScanObject*)scanObj{
  2127. [self addlog:@"onSetSymbology:"];
  2128. SKTRESULT result=[[scanObj Msg]Result];
  2129. if(!SKTSUCCESS(result)){
  2130. // display an error message saying a symbology cannot be set
  2131. }
  2132. }
  2133. /**
  2134. *
  2135. */
  2136. -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
  2137. [self addlog:@"onSetDataConfirmationMode:"];
  2138. SKTRESULT result=[[scanObj Msg]Result];
  2139. if(SKTSUCCESS(result)){
  2140. [self addlog:@"DataConfirmation Mode OK"];
  2141. }
  2142. else{
  2143. [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
  2144. }
  2145. }
  2146. /**
  2147. *
  2148. */
  2149. -(void) onDataConfirmation:(ISktScanObject*)scanObj{
  2150. [self addlog:@"onDataConfirmation:"];
  2151. SKTRESULT result=[[scanObj Msg]Result];
  2152. if(SKTSUCCESS(result)){
  2153. [self addlog:@"Data Confirmed OK"];
  2154. }
  2155. else{
  2156. [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
  2157. }
  2158. }
  2159. /**
  2160. *
  2161. */
  2162. -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
  2163. [self addlog:@"onSetLocalDecodeAction:"];
  2164. SKTRESULT result=[[scanObj Msg]Result];
  2165. if(SKTSUCCESS(result)){
  2166. [self addlog:@"Local Decode Action OK"];
  2167. }
  2168. else{
  2169. [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
  2170. }
  2171. }
  2172. /**
  2173. *
  2174. */
  2175. -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
  2176. SKTRESULT result=[[scanObj Msg]Result];
  2177. if(SKTSUCCESS(result)){
  2178. ISktScanProperty* property=[scanObj Property];
  2179. [self addlog:@"SoftScan status:"];
  2180. if([property getByte]==kSktScanEnableSoftScan){
  2181. [self addlog:@"SoftScan is ENABLED"];
  2182. _softScannerEnabled=TRUE;
  2183. }
  2184. else{
  2185. _softScannerEnabled=FALSE;
  2186. [self addlog:@"SoftScan is DISABLED"];
  2187. }
  2188. }
  2189. else{
  2190. [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
  2191. }
  2192. }
  2193. /**
  2194. *
  2195. */
  2196. -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
  2197. [self addlog:@"onSetSoftScanStatus:"];
  2198. SKTRESULT result=[[scanObj Msg]Result];
  2199. if(SKTSUCCESS(result)){
  2200. [self addlog:@"SoftScan set status success"];
  2201. }
  2202. else{
  2203. [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
  2204. }
  2205. }
  2206. /**
  2207. *
  2208. */
  2209. -(void) onSetTrigger:(ISktScanObject*)scanObj{
  2210. [self addlog:@"onSetTrigger:"];
  2211. SKTRESULT result=[[scanObj Msg]Result];
  2212. if(SKTSUCCESS(result)){
  2213. [self addlog:@"Trigger set success"];
  2214. }
  2215. else{
  2216. [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
  2217. }
  2218. }
  2219. /**
  2220. *
  2221. */
  2222. -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
  2223. [self addlog:@"onGetScanApiVersion:"];
  2224. SKTRESULT result=[[scanObj Msg]Result];
  2225. if(SKTSUCCESS(result))
  2226. {
  2227. ISktScanProperty*property=[scanObj Property];
  2228. if([property getType]==kSktScanPropTypeVersion)
  2229. {
  2230. scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
  2231. [[property Version]getMajor],
  2232. [[property Version]getMiddle],
  2233. [[property Version]getMinor],
  2234. [[property Version]getBuild]];
  2235. }
  2236. }
  2237. else{
  2238. scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
  2239. }
  2240. [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
  2241. }
  2242. /**
  2243. *
  2244. */
  2245. #ifdef USE_SOFTSCAN
  2246. -(void) onSetOverlayView:(ISktScanObject*)scanObj{
  2247. SKTRESULT result=[[scanObj Msg]Result];
  2248. if(SKTSUCCESS(result)){
  2249. [self addlog:@"Overlay view set success"];
  2250. }
  2251. else{
  2252. [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
  2253. }
  2254. }
  2255. #endif
  2256. /**
  2257. * called each time a device connects to the host
  2258. * @param result contains the result of the connection
  2259. * @param newDevice contains the device information
  2260. */
  2261. -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
  2262. [self addlog:@"onDeviceArrival:"];
  2263. [self updateDevicesList:deviceInfo Add:YES];
  2264. #ifdef USE_SOFTSCAN
  2265. // if the scanner is a SoftScan scanner
  2266. if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
  2267. // _softScannerTriggerBtn.hidden=NO;
  2268. _softScanDeviceInfo=deviceInfo;
  2269. if(_deviceInfoToTrigger==nil)
  2270. _deviceInfoToTrigger=deviceInfo;
  2271. NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
  2272. [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
  2273. [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
  2274. }
  2275. else
  2276. #endif
  2277. {
  2278. if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
  2279. // _softScannerTriggerBtn.hidden=NO;
  2280. _deviceInfoToTrigger=deviceInfo;
  2281. }
  2282. if(_doAppDataConfirmation==YES){
  2283. // switch the comment between the 2 following lines for handling the
  2284. // data confirmation beep from the scanner (local)
  2285. // if none is set, the scanner will beep only once when SingleEntry actually
  2286. // confirm the decoded data, otherwise the scanner will beep twice, one locally,
  2287. // and one when SingleEntry will confirm the decoded data
  2288. [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
  2289. // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
  2290. }
  2291. // for demonstration only, let's make sure the DPM is enabled
  2292. // first interrogate the scanner to see if it's already enabled
  2293. // and in the onGetSymbologyDpm callback, if the DPM is not already set
  2294. // then we send a Symbology property to enable it.
  2295. [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
  2296. }
  2297. }
  2298. /**
  2299. * called each time a device disconnect from the host
  2300. * @param deviceRemoved contains the device information
  2301. */
  2302. -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
  2303. [self addlog:@"onDeviceRemoval:"];
  2304. [self updateDevicesList:deviceRemoved Add:NO];
  2305. if(_deviceInfoToTrigger==deviceRemoved){
  2306. _deviceInfoToTrigger=nil;
  2307. }
  2308. #ifdef USE_SOFTSCAN
  2309. if(_softScanDeviceInfo==deviceRemoved){
  2310. _softScanDeviceInfo=nil;
  2311. }
  2312. if(_deviceInfoToTrigger==nil)
  2313. _deviceInfoToTrigger=_softScanDeviceInfo;
  2314. #endif
  2315. if(_deviceInfoToTrigger==nil){
  2316. // _softScannerTriggerBtn.hidden=YES;
  2317. }
  2318. }
  2319. /**
  2320. * called each time ScanAPI is reporting an error
  2321. * @param result contains the error code
  2322. */
  2323. -(void) onError:(SKTRESULT) result{
  2324. [self addlog:@"onError:"];
  2325. [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2326. #ifdef RA_NOTIFICATION
  2327. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2328. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2329. }
  2330. #else
  2331. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2332. [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2333. #endif
  2334. // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
  2335. }
  2336. /**
  2337. * called each time ScanAPI receives decoded data from scanner
  2338. * @param deviceInfo contains the device information from which
  2339. * the data has been decoded
  2340. * @param decodedData contains the decoded data information
  2341. */
  2342. -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2343. [self addlog:@"onDecodedDataResult:"];
  2344. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2345. if(SKTSUCCESS(result)){
  2346. NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  2347. #ifdef RA_NOTIFICATION
  2348. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2349. [_eventsFeedback onDecodedData:cleanString];
  2350. }
  2351. #else
  2352. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2353. [avc onDecodedData:cleanString];
  2354. #endif
  2355. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2356. [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
  2357. if(_doAppDataConfirmation==YES){
  2358. [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2359. }
  2360. }
  2361. }
  2362. -(void) test_onDecodedDataResult:(NSString*) value
  2363. {
  2364. [self addlog:@"onDecodedDataResult:"];
  2365. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2366. if(true){
  2367. #ifdef RA_NOTIFICATION
  2368. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2369. [_eventsFeedback onDecodedData:value];
  2370. }
  2371. #else
  2372. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2373. [avc onDecodedData:value];
  2374. #endif
  2375. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2376. [self addlog:value];
  2377. // if(_doAppDataConfirmation==YES){
  2378. // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2379. // }
  2380. }
  2381. }
  2382. //-(void) didRotated
  2383. //{
  2384. //
  2385. //}
  2386. /**
  2387. * called when ScanAPI initialization has been completed
  2388. * @param result contains the initialization result
  2389. */
  2390. -(void) onScanApiInitializeComplete:(SKTRESULT) result{
  2391. [self addlog:@"onScanApiInitializeComplete:"];
  2392. if(SKTSUCCESS(result))
  2393. {
  2394. self.api_Status = API_START;
  2395. NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
  2396. [self addlog:strlog];
  2397. #ifdef USE_SOFTSCAN
  2398. // make sure we support SoftScan
  2399. [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2400. // check if SoftScan is enabled
  2401. [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
  2402. #else
  2403. // disable support SoftScan (Default, not really needed if it was never activated)
  2404. [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2405. #endif
  2406. // ask for ScanAPI version (not a requirement but always nice to know)
  2407. [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
  2408. // configure ScanAPI for doing App Data confirmation,
  2409. // if TRUE then SingleEntry will confirm the decoded data
  2410. if(_doAppDataConfirmation==YES){
  2411. [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
  2412. }
  2413. #ifdef RA_NOTIFICATION
  2414. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2415. [_eventsFeedback onStatusChanged:@"Waiting for scanner..."];
  2416. }
  2417. #else
  2418. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2419. [avc onStatusChanged:@"Waiting for scanner..."];
  2420. #endif
  2421. self.Status_Text = @"Waiting for scanner...";
  2422. // _Status.text=@"Waiting for scanner...";
  2423. }
  2424. else{
  2425. #ifdef RA_NOTIFICATION
  2426. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2427. [_eventsFeedback onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2428. }
  2429. #else
  2430. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2431. [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2432. #endif
  2433. self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2434. // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2435. NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2436. [self addlog:strlog];
  2437. }
  2438. }
  2439. /**
  2440. * called when ScanAPI has been terminated. This will be
  2441. * the last message received from ScanAPI
  2442. */
  2443. -(void) onScanApiTerminated{
  2444. [self addlog:@"onScanApiTerminated:"];
  2445. [ScanApiConsumer invalidate];
  2446. ScanApiConsumer= nil;
  2447. [self addlog:@"ScanApiConsumer invalidate"];
  2448. self.api_Status = API_STOP;
  2449. #ifdef RA_NOTIFICATION
  2450. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2451. [_eventsFeedback onStatusChanged:@"Off"];
  2452. }
  2453. #else
  2454. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2455. [avc onStatusChanged:@"Off"];
  2456. #endif
  2457. self.Status_Text =@"Off";
  2458. // _Status.text = @"Off";
  2459. }
  2460. /**
  2461. * called when an error occurs during the retrieval
  2462. * of a ScanObject from ScanAPI.
  2463. * @param result contains the retrieval error code
  2464. */
  2465. -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
  2466. [self addlog:@"onErrorRetrievingScanObject:"];
  2467. [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2468. //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
  2469. #ifdef RA_NOTIFICATION
  2470. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2471. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2472. }
  2473. #else
  2474. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2475. [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2476. #endif
  2477. }
  2478. #pragma mark - Scaner
  2479. -(void)onTimer: (NSTimer*)theTimer{
  2480. if(theTimer==ScanApiConsumer){
  2481. // [self addlog:@"ScanApi::doScanApiReceive:"];
  2482. [ScanApi doScanApiReceive];
  2483. }
  2484. }
  2485. -(void) addlog:(NSString*) newtext
  2486. {
  2487. if(!self.enable_ScannerLog)
  2488. return;
  2489. dispatch_async(dispatch_get_main_queue(), ^{
  2490. NSString* date;
  2491. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  2492. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  2493. date = [formatter stringFromDate:[NSDate date]];
  2494. if(newtext.length<=0)
  2495. return;
  2496. NSString* text = self.log;
  2497. if(text.length==0)
  2498. text=@"";
  2499. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  2500. self.log = text;
  2501. #ifdef RA_NOTIFICATION
  2502. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onLogUpdate)])){
  2503. [_eventsFeedback onLogUpdate];
  2504. }
  2505. #else
  2506. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2507. [avc onLogUpdate];
  2508. #endif
  2509. });
  2510. }
  2511. - (void)enableScanner:(bool)enable {
  2512. [self addlog:@"Enable scanner:"];
  2513. if(enable)
  2514. {
  2515. [self addlog:@"Enable"];
  2516. self.api_Status = API_INIT;
  2517. #ifdef RA_NOTIFICATION
  2518. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2519. [_eventsFeedback onStatusChanged:@"Initialize..."];
  2520. }
  2521. #else
  2522. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2523. [avc onStatusChanged:@"Initialize..."];
  2524. #endif
  2525. self.Status_Text = @"Initialize...";
  2526. [ScanApi open];
  2527. [self addlog:@"ScanApi open"];
  2528. ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
  2529. [self addlog:@"ScanApiConsumer init"];
  2530. // [ScanApi close];
  2531. // [self addlog:@"ScanApi opent"];
  2532. }
  2533. else
  2534. {
  2535. [self addlog:@"Disable"];
  2536. // [ScanApiConsumer invalidate];
  2537. // ScanApiConsumer= nil;
  2538. // [self addlog:@"ScanApiConsumer invalidate"];
  2539. self.api_Status = API_CLOSING;
  2540. #ifdef RA_NOTIFICATION
  2541. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2542. [_eventsFeedback onStatusChanged:@"Stoping..."];
  2543. }
  2544. #else
  2545. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2546. [avc onStatusChanged:@"Stoping..."];
  2547. #endif
  2548. self.Status_Text = @"Stoping...";
  2549. [ScanApi close];
  2550. [self addlog:@"ScanApi close"];
  2551. }
  2552. }
  2553. #pragma mark - Device Info List management
  2554. -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
  2555. [self addlog:@"updateDevicesList:"];
  2556. if(add==YES){
  2557. [self.devices addObject:deviceInfo];
  2558. }
  2559. else{
  2560. [self.devices removeObject:deviceInfo];
  2561. }
  2562. NSMutableString* temp=[[NSMutableString alloc]init];
  2563. for (DeviceInfo* info in self.devices) {
  2564. [temp appendString:[info getName]];
  2565. [temp appendString:@"\n"];
  2566. }
  2567. if(self.devices.count>0)
  2568. [temp appendString:@"ready to scan"];
  2569. else
  2570. [temp appendString:@"Waiting for Scanner..."];
  2571. // _Status.text=temp ;
  2572. [self addlog:temp];
  2573. #ifdef RA_NOTIFICATION
  2574. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2575. [_eventsFeedback onStatusChanged:temp];
  2576. }
  2577. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2578. [_eventsFeedback OnUpdateDevicesList];
  2579. }
  2580. #else
  2581. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2582. [avc onStatusChanged:temp];
  2583. [avc OnUpdateDevicesList];
  2584. #endif
  2585. self.Status_Text = temp;
  2586. // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
  2587. // [self.dev_table reloadData];
  2588. }
  2589. @end