AppDelegateBase.m 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733
  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 "SelectUploadOrderViewController.h"
  16. #import "iSalesDB.h"
  17. #import "RANetwork.h"
  18. #import "NotificationNameCenter.h"
  19. #import "CustomerEditViewController.h"
  20. #import "CreateOrderViewController.h"
  21. #import "OrderDetailViewController.h"
  22. #import "AddressEditorViewController.h"
  23. #import "config.h"
  24. #import "RASingleton.h"
  25. #ifdef GOOGLE_ANALYTICS
  26. #import "Analytics.h"
  27. #import "GoogleAnalyst.h"
  28. #endif
  29. #import "ERPUtils.h"
  30. #import "RANetwork.h"
  31. #import "RASingleton.h"
  32. #ifdef BACKORDER_PROCESS
  33. #import "RAOrderEditorViewController.h"
  34. #endif
  35. #import "RAConvertor.h"
  36. //#import "config.h"
  37. #define UNZIP_OPEN_FAILED 0
  38. #define UNZIP_SUCCESS 1
  39. #define UNZIP_NO_SPACE 2
  40. #define UNZIP_FILE_DAMAGE 3
  41. @interface AppDelegateBase ()
  42. @end
  43. @implementation AppDelegateBase
  44. {
  45. #ifdef USE_SOFTSCAN
  46. DeviceInfo* _softScanDeviceInfo;
  47. #endif
  48. DeviceInfo* _deviceInfoToTrigger;
  49. NSMutableArray* _feedbackStack;
  50. id<ScannerEventsFeedback> _eventsFeedback;
  51. }
  52. @synthesize ScanApi;
  53. @synthesize ScanApiConsumer;
  54. @synthesize scanApiVersion;
  55. @synthesize price_hidden = _price_hidden;
  56. #pragma mark - Global Parameter
  57. //- (NSMutableDictionary *)globalParameters {
  58. // if (!_globalParameters) {
  59. // _globalParameters = [NSMutableDictionary dictionary];
  60. // }
  61. // return _globalParameters;
  62. //}
  63. //
  64. //- (void)setGlobalParameter:(id)param forKey:(NSString *)key {
  65. // if (param == nil || key == nil) {
  66. // return;
  67. // }
  68. // [self.globalParameters setObject:param forKey:key];
  69. //}
  70. //
  71. //- (id)globalParameterForKey:(NSString *)key {
  72. // if (key == nil) {
  73. // return nil;
  74. // }
  75. // return [self.globalParameters objectForKey:key];
  76. //}
  77. #pragma mark - Setter
  78. //
  79. //- (void)setAlert_sold_in_quantities:(bool)alert_sold_in_quantities
  80. //{
  81. // _alert_sold_in_quantities =alert_sold_in_quantities;
  82. //}
  83. - (void)setUrgencyDic:(NSMutableDictionary *)urgencyDic {
  84. _urgencyDic = urgencyDic;
  85. [RASingleton.sharedInstance setGlobalParameter:_urgencyDic forKey:@"urgencyDic"];
  86. }
  87. - (void)setCan_see_price:(bool)can_see_price {
  88. _can_see_price = can_see_price;
  89. [RASingleton.sharedInstance setGlobalParameter:@(_can_see_price) forKey:@"can_see_price"];
  90. }
  91. - (void)setPrice_hidden:(bool)price_hidden {
  92. _price_hidden = price_hidden;
  93. [RASingleton.sharedInstance setGlobalParameter:@(_price_hidden) forKey:@"price_hidden"];
  94. #ifdef RA_NOTIFICATION
  95. [ActiveViewController Notify:@"" Message:RA_NOTIFICATION_UPDATE_PRICE];
  96. #else
  97. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  98. [avc showHidePrice];
  99. #endif
  100. }
  101. - (void)setOffline_mode:(bool)offline_mode {
  102. _offline_mode = offline_mode;
  103. [RASingleton.sharedInstance setGlobalParameter:@(_offline_mode) forKey:@"offline_mode"];
  104. }
  105. - (void)setUser:(NSString *)user {
  106. _user = user;
  107. RASingleton.sharedInstance.user = user;
  108. [RASingleton.sharedInstance setGlobalParameter:_user forKey:@"user"];
  109. }
  110. - (void)setUser_type:(long)user_type
  111. {
  112. _user_type = user_type;
  113. }
  114. - (void)setPassword:(NSString *)password {
  115. _password = password;
  116. [RASingleton.sharedInstance setGlobalParameter:_password forKey:@"password"];
  117. }
  118. #pragma mark - Normal
  119. -(void) set_priceHidden:(bool)price_hidden
  120. {
  121. [self setPrice_hidden:price_hidden];
  122. }
  123. -(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
  124. {
  125. if (self.user_type == USER_ROLE_CUSTOMER && _customerInfo) {
  126. return;
  127. }
  128. #ifdef RA_NOTIFICATION
  129. [ActiveViewController Notify:@"ContactListViewController" Message:RA_NOTIFICATION_REFRESH_UI];
  130. //切换账号应该不需要刷新wishlist,此处如果刷新,会使wishlist新建订单自动添加出错。
  131. // [ActiveViewController Notify:@"WatchListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  132. #else
  133. [((MainViewController*)self.main_vc) reloadContact:false immediately:false];
  134. [(MainViewController*)self.main_vc reloadWish:YES immediately:NO];
  135. #endif
  136. _customerInfo=customerInfo;
  137. // DebugLog(@"%@",_customerInfo.class);
  138. // DebugLog(@"%@",customerInfo.class);
  139. // int count=customerInfo[@"count"];
  140. //assert(count==0);
  141. }
  142. -(void) set_main_button_panel
  143. {
  144. return;
  145. // dispatch_async(dispatch_get_main_queue(), ^{
  146. // if(self.main_vc==nil)
  147. // return;
  148. // MainViewController * main_vc= (MainViewController*)self.main_vc;
  149. // if(self.user_type==USER_ROLE_CUSTOMER)
  150. // {
  151. // main_vc.customer_bp.hidden=false;
  152. // main_vc.employee_bp.hidden = true;
  153. // }
  154. // else
  155. // {
  156. // main_vc.customer_bp.hidden=true;
  157. // main_vc.employee_bp.hidden = false;
  158. // }
  159. // });
  160. }
  161. //#ifdef SCANNER_ORDER
  162. //- (void)updateScanButton:(BOOL)enable
  163. //{
  164. // MainViewController * mainvc=(MainViewController * )self.main_vc;
  165. // mainvc.btnScan.enabled = enable;
  166. //}
  167. //#endif
  168. -(void) update_count_mark
  169. {
  170. dispatch_async(dispatch_get_main_queue(), ^{
  171. if(self.main_vc==nil)
  172. return;
  173. MainViewController * main_vc= (MainViewController*)self.main_vc;
  174. //contact button
  175. if(self.user==nil)
  176. {
  177. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  178. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  179. main_vc.btnContact.hidden = YES;
  180. }
  181. else
  182. {
  183. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  184. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  185. if(self.customerInfo==nil)
  186. {
  187. // contact=@"No Name"; if(customerinfo==nil)
  188. // {
  189. contact=@"Select Contact";
  190. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  191. }
  192. else
  193. {
  194. if(contact==nil||contact.length==0)
  195. {
  196. contact=@"No Name";
  197. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  198. }
  199. else
  200. {
  201. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  202. }
  203. }
  204. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  205. if(contact.length>0)
  206. [arr_contact addObject:contact];
  207. if(customer.length>0)
  208. [arr_contact addObject:customer];
  209. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  210. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  211. }
  212. //cart
  213. if(self.user==nil||self.cart_count==0)
  214. {
  215. main_vc.label_ccount.hidden = true;
  216. main_vc.label_cccount.hidden=true;
  217. }
  218. else
  219. {
  220. NSString* strcount;
  221. if(self.cart_count>999)
  222. strcount=@"999+";
  223. else
  224. strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
  225. main_vc.label_ccount.text = strcount;
  226. if(strcount.length==1)
  227. main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
  228. if(strcount.length==2)
  229. main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
  230. if(strcount.length==3)
  231. main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
  232. if(strcount.length==4)
  233. main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
  234. main_vc.label_ccount.hidden = false;
  235. main_vc.label_cccount.text = strcount;
  236. if(strcount.length==1)
  237. main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
  238. if(strcount.length==2)
  239. main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
  240. if(strcount.length==3)
  241. main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
  242. if(strcount.length==4)
  243. main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
  244. main_vc.label_cccount.hidden = false;
  245. }
  246. //wishlist
  247. if(self.user==nil||self.wish_count==0)
  248. {
  249. main_vc.label_wcount.hidden = true;
  250. main_vc.label_cwcount.hidden = true;
  251. }
  252. else
  253. {
  254. NSString* strcount;
  255. if(self.wish_count>999)
  256. strcount=@"999+";
  257. else
  258. strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
  259. main_vc.label_wcount.text = strcount;
  260. if(strcount.length==1)
  261. main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
  262. if(strcount.length==2)
  263. main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
  264. if(strcount.length==3)
  265. main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
  266. if(strcount.length==4)
  267. main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
  268. main_vc.label_wcount.hidden = false;
  269. main_vc.label_cwcount.text = strcount;
  270. if(strcount.length==1)
  271. main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
  272. if(strcount.length==2)
  273. main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
  274. if(strcount.length==3)
  275. main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
  276. if(strcount.length==4)
  277. main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
  278. main_vc.label_cwcount.hidden = false;
  279. }
  280. });
  281. }
  282. -(void) closeOrder
  283. {
  284. self.order_code = nil;
  285. self.order_customer_id = nil;
  286. if(self.user_type!=USER_ROLE_CUSTOMER)
  287. {
  288. self.customerInfo = nil;
  289. self.contact_id = nil;
  290. }
  291. // [self SetMode:nil];
  292. // [self SetSo:nil];
  293. #ifdef RA_NOTIFICATION
  294. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  295. #else
  296. [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
  297. [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
  298. #endif
  299. // [self updateScanButton:false];
  300. }
  301. -(void) switchToPreviousVC
  302. {
  303. MainViewController * main_vc= (MainViewController*)self.main_vc;
  304. [main_vc switchToPreviousVC];
  305. }
  306. -(void) SetMode:(NSString*)mode1
  307. {
  308. __block NSString* blockmode= mode1;
  309. dispatch_async(dispatch_get_main_queue(), ^{
  310. if(self.offline_mode)
  311. blockmode =@"Regular Mode";
  312. if(self.main_vc==nil)
  313. return;
  314. MainViewController * main_vc= (MainViewController*)self.main_vc;
  315. if(self.user==nil)
  316. {
  317. NSString* title = [NSString stringWithFormat:@"Sign in"];
  318. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  319. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  320. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  321. main_vc.btnContact.hidden = YES;
  322. main_vc.labelMode.text=nil;
  323. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  324. return;
  325. }
  326. else
  327. {
  328. #ifndef SCANNER_ORDER
  329. main_vc.btnContact.hidden = NO;
  330. #endif
  331. if(self.user_type==USER_ROLE_CUSTOMER)
  332. {
  333. NSString* title = [NSString stringWithFormat:@"%@",self.user];
  334. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  335. main_vc.labelMode.text=nil;
  336. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  337. }
  338. else
  339. {
  340. if([blockmode isEqualToString:@"Regular Mode"])
  341. {
  342. self.mode=@"RM";
  343. NSString* title = self.user;
  344. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  345. main_vc.labelMode.text=self.mode;
  346. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  347. }
  348. else
  349. {
  350. self.mode=@"TM";
  351. NSString* title = self.user;
  352. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  353. main_vc.labelMode.text=self.mode;
  354. [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
  355. }
  356. }
  357. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  358. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  359. if(self.customerInfo==nil)
  360. {
  361. // contact=@"No Name"; if(customerinfo==nil)
  362. // {
  363. contact=@"Select Contact";
  364. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  365. }
  366. else
  367. {
  368. if(contact==nil||contact.length==0)
  369. {
  370. contact=@"No Name";
  371. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  372. }
  373. else
  374. {
  375. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  376. }
  377. }
  378. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  379. if(contact.length>0)
  380. [arr_contact addObject:contact];
  381. if(customer.length>0)
  382. [arr_contact addObject:customer];
  383. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  384. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  385. }
  386. });
  387. }
  388. -(void) SetSo:(NSString *)So
  389. {
  390. dispatch_async(dispatch_get_main_queue(), ^{
  391. if(self.main_vc==nil)
  392. return;
  393. MainViewController * main_vc= (MainViewController*)self.main_vc;
  394. if (self.user_type == USER_ROLE_CUSTOMER) {
  395. if (So == nil) {
  396. // 释放订单
  397. [RASingleton sharedInstance].currentOrderIsMerged = NO;
  398. }
  399. }
  400. if(self.user==nil)
  401. {
  402. // NSString* title = [NSString stringWithFormat:@"Sign in"];
  403. main_vc.labelSo.text=nil;
  404. return;
  405. }
  406. else
  407. {
  408. {
  409. if(So.length==0)
  410. main_vc.labelSo.text=nil;
  411. else
  412. {
  413. NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
  414. main_vc.labelSo.text=text;
  415. }
  416. }
  417. }
  418. });
  419. }
  420. //- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
  421. // if ([rootViewController isKindOfClass:[UITabBarController class]]) {
  422. // UITabBarController* tabBarController = (UITabBarController*)rootViewController;
  423. // return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
  424. // } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
  425. // UINavigationController* navigationController = (UINavigationController*)rootViewController;
  426. // return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
  427. // } else if (rootViewController.presentedViewController) {
  428. // UIViewController* presentedViewController = rootViewController.presentedViewController;
  429. // return [self topViewControllerWithRootViewController:presentedViewController];
  430. // } else {
  431. // return rootViewController;
  432. // }
  433. //}
  434. //- (UIViewController*)topViewController {
  435. // return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  436. //}
  437. //-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  438. ////   // Get topmost/visible view controller
  439. // UIViewController *currentViewController = [self topViewController];
  440. //
  441. // if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
  442. //
  443. // return UIInterfaceOrientationMaskPortrait;
  444. // }
  445. ////
  446. ////   // Only allow portrait (standard behaviour)
  447. // return UIInterfaceOrientationMaskAll;
  448. //}
  449. void UncaughtExceptionHandler(NSException *exception) {
  450. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  451. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  452. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  453. NSString *versionNum = @"";
  454. versionNum = [NSString stringWithFormat:@"Version: %@ %@ Build %@",COMPANY_SHORT_NAME,version,build];
  455. versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  456. /**
  457. * 获取异常崩溃信息
  458. */
  459. NSArray *callStack = [exception callStackSymbols];
  460. NSString *reason = [exception reason];
  461. NSString *name = [exception name];
  462. NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name: %@\n exception_reason: \n%@ \n exception_callStackSymbols: \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
  463. content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  464. NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
  465. if ([RASingleton sharedInstance].currentDB) {
  466. [iSalesDB close_db:[RASingleton sharedInstance].currentDB];
  467. }
  468. [iSalesDB execSql:sql];
  469. dispatch_async(dispatch_get_main_queue(), ^{
  470. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  471. [appDelegate writeUrgencyCache];
  472. });
  473. #ifdef SCANNER_ORDER
  474. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  475. [appDelegate saveUploadTasks];
  476. #endif
  477. }
  478. - (void)handleErrorLog {
  479. #ifdef SCANNER_ORDER
  480. return;
  481. #else
  482. __block NSMutableArray *err_array = [NSMutableArray array];
  483. [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  484. const char *version_char = (char *)sqlite3_column_text(stmt, 0);
  485. const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
  486. const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
  487. if (version_char == NULL)
  488. version_char = "";
  489. if (errlog_char == NULL)
  490. errlog_char = "";
  491. if (dateTime_char == NULL)
  492. dateTime_char = "";
  493. NSString *version_str = [NSString stringWithUTF8String:version_char];
  494. NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
  495. NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
  496. NSDictionary *err_dic = @{
  497. @"version" : version_str,
  498. @"errlog" : errlog_str,
  499. @"time" : dateTime_str
  500. };
  501. [err_array addObject:err_dic];
  502. }];
  503. if (err_array.count) {
  504. // 首先上传
  505. for (NSDictionary *err_dic in err_array) {
  506. NSString *version = [err_dic objectForKey:@"version"];
  507. NSString *errlog = [err_dic objectForKey:@"errlog"];
  508. NSString *time = [err_dic objectForKey:@"time"];
  509. NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
  510. // NSDictionary *ret = [RANetwork err_log:errlog result:result module:@"crash" code:0];
  511. dispatch_async(dispatch_get_main_queue(), ^{
  512. [RANetwork request_err_log:errlog result:result module:@"crash" code:0 completionHandler:^(NSMutableDictionary *result) {
  513. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  514. // 上传成功之后清除纪录
  515. if ([[result objectForKey:@"result"] integerValue] == 2) {
  516. [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
  517. }
  518. });
  519. }];
  520. });
  521. }
  522. }
  523. #endif
  524. }
  525. - (void)dealWithUrgencyFile {
  526. NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
  527. if (tmp_urgencyDic.allKeys.count > 2) {
  528. [self.urgencyDic removeAllObjects];
  529. [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
  530. // UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  531. NSString *user = [tmp_urgencyDic objectForKey:@"user"];
  532. if (![user isEqualToString:self.user]) {
  533. return;
  534. }
  535. BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
  536. if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
  537. return;
  538. }
  539. id count = [tmp_urgencyDic objectForKey:@"count"];
  540. int level_count = count ? (int)[count integerValue] : 0;
  541. if (!level_count) {
  542. return;
  543. }
  544. for (int i = 0; i < level_count; i++) {
  545. NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
  546. NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
  547. NSString *className = [urgencyDic objectForKey:@"class_name"];
  548. NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
  549. NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
  550. dispatch_async(dispatch_get_main_queue(), ^{
  551. if ([className isEqualToString:@"CustomerEditViewController"]) {
  552. // CustomerEditViewController
  553. NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
  554. BOOL new_customer = [urgencyDic objectForKey:@"new_customer"];
  555. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  556. [params setValue:contact_id forKey:@"contact_id"];
  557. CustomerEditViewController * cuseditVC =[[CustomerEditViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  558. cuseditVC.bnewcustomer=new_customer;
  559. cuseditVC.url_type = URL_RESTORE;
  560. cuseditVC.request_url= new_customer ? URL_NEW_CUSTOMER : URL_EDIT_CUSTOMER;
  561. cuseditVC.params = params;
  562. cuseditVC.content_data_download = restored_data;
  563. // cuseditVC.delegate=self;
  564. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  565. [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
  566. [mainVC.navigationController pushViewController:cuseditVC animated:false];
  567. } else if ([className isEqualToString:@"CreateOrderViewController"] || [className isEqualToString:@"RAOrderEditorViewController"]) {
  568. // CreateOrderViewController
  569. NSString *order_code = [urgencyDic objectForKey:@"order_code"];
  570. int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
  571. NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
  572. NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
  573. NSString *so = [urgencyDic objectForKey:@"order_so"];
  574. self.order_customer_id = order_customer_id;
  575. [RANetwork request_open_order:order_code completionHandler:^(NSMutableDictionary *result) {
  576. NSDictionary* order_json = result;
  577. // [waitalert dismissViewControllerAnimated:YES completion:nil];
  578. if([[order_json valueForKey:@"result"] intValue]==2)
  579. {
  580. self.order_code = order_code;
  581. self.order_status = order_status;
  582. [self SetSo:so];
  583. if (userType != USER_ROLE_CUSTOMER) {
  584. [RANetwork request_contactinfo:order_customer_id completionHandler:^(NSMutableDictionary *result) {
  585. self.customerInfo = [result[@"customerInfo"] mutableCopy];
  586. self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  587. }];
  588. // self.customerInfo = [[[RANetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
  589. //
  590. // self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  591. }
  592. #ifdef RA_NOTIFICATION
  593. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  594. #else
  595. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  596. [mainVC reloadOrder:true immediately:false];
  597. [mainVC reloadCart:true immediately:false];
  598. #endif
  599. }
  600. else
  601. {
  602. // MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  603. [RAUtils message_box:@"Open Order" message:[order_json valueForKey:@"err_msg"] completion:nil];
  604. }
  605. }];
  606. // 再place order
  607. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  608. if ([className isEqualToString:@"CreateOrderViewController"]) {
  609. CreateOrderViewController * orderinfoVC = [[CreateOrderViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  610. orderinfoVC.disable_dropdown_refresh=true;
  611. orderinfoVC.url_type = URL_RESTORE;
  612. orderinfoVC.request_url=URL_CARTDELIVERY;
  613. orderinfoVC.params = params;
  614. orderinfoVC.content_data_download = restored_data;
  615. orderinfoVC.resumeOrder = YES;
  616. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  617. [mainVC.navigationController pushViewController:orderinfoVC animated:true];
  618. }
  619. #ifdef BACKORDER_PROCESS
  620. else if ([className isEqualToString:@"RAOrderEditorViewController"]) {
  621. RAOrderEditorViewController *orderEditorVC = [[RAOrderEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  622. [orderEditorVC recoveryFromUrgencyDic:urgencyDic];
  623. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  624. [mainVC.navigationController pushViewController:orderEditorVC animated:YES];
  625. }
  626. #endif
  627. } else if ([className isEqualToString:@"AddressEditorViewController"]) {
  628. // AddressEditorViewController
  629. AddressEditorViewController * addressVC = [[AddressEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  630. addressVC.url_type = URL_RESTORE;
  631. addressVC.request_url=URL_ADDRESS_EDOTOR;
  632. NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
  633. params[@"is_subaction"]=@"true";
  634. addressVC.params = params;
  635. addressVC.content_data_download = restored_data;
  636. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  637. [mainVC.navigationController pushViewController:addressVC animated:true];
  638. }// class_name
  639. });
  640. }
  641. }
  642. }
  643. - (void)handleUrgencyFile {
  644. __weak typeof(self) weakself = self;
  645. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  646. if (weakself) {
  647. __strong typeof(weakself) strongself = weakself;
  648. [strongself dealWithUrgencyFile];
  649. }
  650. });
  651. }
  652. - (void)writeUrgencyCache {
  653. if (!self.user) {
  654. return;
  655. }
  656. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  657. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  658. // [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
  659. [self.urgencyDic writeToFile:urgencyFile atomically:NO];
  660. // Place Order恢复是否能提交订单
  661. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
  662. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
  663. if ([RASingleton sharedInstance].currentOrderIsMerged && [RASingleton sharedInstance].permissions_submit_order) {
  664. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
  665. }
  666. }
  667. - (NSMutableDictionary *)readUrgencyCache {
  668. // 检查本地urgency文件,存在则加载进_urgencyDic
  669. NSFileManager *manager = [NSFileManager defaultManager];
  670. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  671. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  672. NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
  673. if ([manager fileExistsAtPath:urgencyFile]) {
  674. resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
  675. [manager removeItemAtPath:urgencyFile error:nil];
  676. }
  677. self.urgencyDic = [NSMutableDictionary dictionary];
  678. return resultDic;
  679. }
  680. - (void)initialExceptionHandler {
  681. if (exception_switch == 1) {
  682. NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
  683. }
  684. }
  685. - (void)becomeObserver {
  686. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
  687. }
  688. - (void)dealloc {
  689. [[NSNotificationCenter defaultCenter] removeObserver:self];
  690. }
  691. #ifdef SCANNER_ORDER
  692. -(void) setAddress:(NSString *)address
  693. {
  694. _address = address;
  695. _uploadurl = [address stringByAppendingPathComponent:URL_SCAN_UPLOAD];// [NSString stringWithFormat:@"%@%@",address,URL_SCAN_UPLOAD];
  696. NSString * file = [NSString stringWithFormat:URL_SCAN_DOWNLOAD,[RADataProvider getSiteName]];
  697. _downloadurl =[address stringByAppendingPathComponent:file] ; // [NSString stringWithFormat:@"%@%@",address,URL_SCAN_DOWNLOAD];
  698. }
  699. #endif
  700. #ifdef GOOGLE_ANALYTICS
  701. - (void)setUpGoogleAnalytics {
  702. // 初始化Google Analytics
  703. NSError *configureError;
  704. [[GGLContext sharedInstance] configureWithError:&configureError];
  705. if (configureError) {
  706. DebugLog(@"congigure googleAnalytics error: %@",configureError);
  707. }
  708. GAI *gai = [GAI sharedInstance];
  709. gai.trackUncaughtExceptions = YES;
  710. id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
  711. // Enable IDFA collection.
  712. tracker.allowIDFACollection = YES;
  713. // gai.dispatchInterval = 120;// 每隔 2 分钟调度一次数据
  714. // 调试使用
  715. // gai.logger.logLevel = kGAILogLevelVerbose;
  716. // [[GAI sharedInstance] setDryRun:YES];
  717. //
  718. }
  719. #endif
  720. //-(void)test_descrypt
  721. //{
  722. // sqlite3 *db = [iSalesDB get_db];
  723. //
  724. // int result= [iSalesDB AddExFunction:db];
  725. //
  726. // NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  727. // sqlite3_stmt * statement;
  728. //
  729. //
  730. // if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  731. // {
  732. //
  733. //
  734. // while (sqlite3_step(statement) == SQLITE_ROW)
  735. // {
  736. //
  737. //
  738. // char *url = (char*)sqlite3_column_text(statement, 0);
  739. // if(url==nil)
  740. // url="";
  741. // NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  742. // DebugLog(nsurl);
  743. //
  744. //
  745. //
  746. //
  747. // }
  748. // // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  749. //
  750. //
  751. // sqlite3_finalize(statement);
  752. // }
  753. //
  754. // [iSalesDB close_db:db];
  755. //}
  756. //
  757. //-(void)test_descrypt1
  758. //{
  759. // sqlite3 *db = [iSalesDB get_db];
  760. //
  761. // int result= [iSalesDB AddExFunction:db];
  762. //
  763. // NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
  764. //
  765. // [iSalesDB execSql:sqlindex];
  766. ////
  767. //// NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  768. //// sqlite3_stmt * statement;
  769. ////
  770. ////
  771. ////
  772. //// if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  773. //// {
  774. ////
  775. ////
  776. //// while (sqlite3_step(statement) == SQLITE_ROW)
  777. //// {
  778. ////
  779. ////
  780. //// char *url = (char*)sqlite3_column_text(statement, 0);
  781. //// if(url==nil)
  782. //// url="";
  783. //// NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  784. //// DebugLog(nsurl);
  785. ////
  786. ////
  787. ////
  788. ////
  789. //// }
  790. //// // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  791. ////
  792. ////
  793. //// sqlite3_finalize(statement);
  794. //// }
  795. //
  796. // [iSalesDB close_db:db];
  797. //}
  798. - (void)applicationWillResignActive:(UIApplication *)application
  799. {
  800. // 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.
  801. // 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.
  802. }
  803. - (void)applicationDidEnterBackground:(UIApplication *)application
  804. {
  805. [self download_offline:false checkdiskspace:false];
  806. // 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.
  807. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  808. #if defined(GOOGLE_ANALYTICS)
  809. NSTimeInterval timing = [[NSDate date] timeIntervalSinceDate:self.forgroundDate];
  810. self.forgroundDate = nil;
  811. [GoogleAnalyst trackTimingWithCategory:@"foreground" interval:timing name:@"user used time" label:nil];
  812. #endif
  813. }
  814. - (void)applicationWillEnterForeground:(UIApplication *)application
  815. {
  816. // 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.
  817. }
  818. - (void)applicationDidBecomeActive:(UIApplication *)application
  819. {
  820. if(self.download_task!=nil)
  821. [self download_offline:true checkdiskspace:false];
  822. // 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.
  823. self.forgroundDate = [NSDate date];
  824. #ifdef SCANNER_ORDER
  825. [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
  826. configure.autoRemoveFinish = YES;
  827. }];
  828. if (!self.uploadManager) {
  829. self.uploadManager=[RAUploadManager sharedManager];
  830. }
  831. #endif
  832. }
  833. #ifdef SCANNER_ORDER
  834. -(RAUploadManager *)uploadManager
  835. {
  836. [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
  837. configure.autoRemoveFinish = YES;
  838. }];
  839. if (!_uploadManager) {
  840. _uploadManager=[RAUploadManager sharedManager];
  841. }
  842. return _uploadManager;
  843. }
  844. #endif
  845. -(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
  846. {
  847. DebugLog(@"======================================");
  848. DebugLog(@"===== MEMORY WORRING ! ==========");
  849. DebugLog(@"======================================");
  850. }
  851. - (void)applicationWillTerminate:(UIApplication *)application
  852. {
  853. #ifdef SCANNER_ORDER
  854. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  855. [self saveUploadTasks];
  856. #endif
  857. }
  858. -(void) Logout
  859. {
  860. // 由于之前使用dispatch_async(dispatch_get_main_queue(), ^{}) 在用户切换时登出后刷新SideMenu User仍然显示
  861. dispatch_main_async_safe(^{
  862. MainViewController * main_vc= (MainViewController*)self.main_vc;
  863. [main_vc logoutOrder];
  864. [main_vc logoutCart];
  865. [main_vc logoutWish];
  866. [main_vc logoutContact];
  867. [main_vc logoutCategory];
  868. [main_vc logoutDocuments];
  869. [main_vc logoutPortfolio];
  870. #ifdef RA_NOTIFICATION
  871. [ActiveViewController Notify:@"SearchViewController" Message:RA_NOTIFICATION_CLEAR_DATA];
  872. #endif
  873. [main_vc hideMenu];
  874. [main_vc switchToHome];
  875. self.user = nil;
  876. self.password=nil;
  877. self.user_icon=nil;
  878. self.user_type = USER_ROLE_UNKNOWN;
  879. self.bLogin = false;
  880. self.contact_id=nil;
  881. self.customerInfo = nil;
  882. self.order_code = nil;
  883. [self.recent_model removeAllObjects];
  884. [self SetMode:nil];
  885. #ifdef SCANNER_ORDER
  886. self.available_price_group = nil;
  887. [RADataProvider default_price_group];
  888. #endif
  889. });
  890. }
  891. -(void)setOrder_code:(NSString *)order_code
  892. {
  893. _order_code = order_code;
  894. if(order_code==nil)
  895. DebugLog(@"Clear order code");
  896. else
  897. DebugLog(@"New order code %@",order_code);
  898. }
  899. - (void)checkLogin:(BOOL)reloadCurVC {
  900. [((MainViewController *)self.main_vc) checklogin:reloadCurVC];
  901. }
  902. //disable apn
  903. //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  904. //{
  905. // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
  906. // DebugLog(@"regisger success:%@",deviceToken);
  907. //
  908. // //注册成功,将deviceToken保存到应用服务器数据库中
  909. //}
  910. #pragma mark - background download
  911. -(bool)isdownloading:(NSString*) file
  912. {
  913. return true;
  914. }
  915. -(long long)getcurrentLength:(int) taskidx
  916. {
  917. int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
  918. return position;
  919. }
  920. -(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  921. {
  922. //操作有两种,start stop;
  923. //结果有四种, wait , downloading, pause, finish
  924. dispatch_async(dispatch_get_main_queue(), ^{
  925. // debug;
  926. // NSString* file_name=[url lastPathComponent];
  927. //暂停<->开始转换
  928. // bool isdownloading = [self isdownloading:file_name];
  929. if (start)
  930. {//开始下载
  931. DebugLog(@"%d start",taskidx);
  932. self.current_task=taskidx;
  933. NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  934. // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  935. //
  936. //
  937. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  938. //
  939. // //设置请求头(GET)
  940. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  941. // [request setValue:range forHTTPHeaderField:@"Range"];
  942. //
  943. // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  944. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  945. //设置请求头(GET)
  946. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  947. [request setValue:range forHTTPHeaderField:@"Range"];
  948. self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  949. }else{ //暂停
  950. DebugLog(@"%d pause",taskidx);
  951. [self.connection cancel];
  952. self.connection = nil;
  953. }
  954. });
  955. }
  956. -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order params:(NSMutableDictionary*) add_params
  957. {
  958. assert(add_params[@"user"]!=nil);
  959. assert(add_params[@"password"]!=nil);
  960. // assert(add_params[@"contact_id"]!=nil);
  961. [self add_downloadlog:@"Begin sync, please wait."];
  962. [self add_downloadlog:@"Prepare upload data."];
  963. // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
  964. NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order params:add_params];
  965. NSString* upfile=upjson[@"file"];
  966. {
  967. NSData* data = [NSData dataWithContentsOfFile: upfile];
  968. // UIApplication * app = [UIApplication sharedApplication];
  969. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  970. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  971. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  972. if(add_params[@"user"]!=nil)
  973. [params setValue:add_params[@"user"] forKey:@"user"];
  974. // if(appDelegate.contact_id!=nil)
  975. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  976. if(add_params[@"password"]!=nil)
  977. [params setValue:add_params[@"password"] forKey:@"password"];
  978. #if TARGET_IPHONE_SIMULATOR//模拟器
  979. [params setValue:@"simulator_uuid" forKey:@"idfv"];
  980. #elif TARGET_OS_IPHONE//真机
  981. UIDevice * dev = [UIDevice currentDevice];
  982. NSUUID* uuid =dev.identifierForVendor;
  983. [params setValue:uuid.UUIDString forKey:@"idfv"];
  984. #endif
  985. __weak typeof(self) weakSelf = self;
  986. [NetworkUtils upload:data FileName:[upfile lastPathComponent] Params:params ToHost:URL_UPLOAD_OFFLINE Result:^(NSMutableDictionary *json) {
  987. if([[json valueForKey:@"result"] intValue]==2)
  988. {
  989. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  990. // 清理数据库要放入线程中执行
  991. NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  992. if (out_of_stock_ids) {
  993. [RAUtils message_box:@"Warning" message:[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] completion:nil];
  994. }
  995. [weakSelf add_downloadlog:@"Upload successful."];
  996. // [iSalesDB disable_trigger]
  997. [iSalesDB disable_trigger];
  998. NSString* so_id=[RAConvertor arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  999. [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  1000. [iSalesDB execSql:@"delete from wishlist"];
  1001. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  1002. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  1003. [iSalesDB execSql:@"delete from offline_portfolio"];
  1004. [iSalesDB execSql:@"delete from offline_pdf"];
  1005. [OLDataProvider offline_clear_PDFCache];
  1006. NSString* contactMap = json[@"contactMap"];
  1007. if(contactMap.length>0)
  1008. {
  1009. NSDictionary* contactjson = [RAConvertor string2dict:contactMap];
  1010. NSArray *keys= [contactjson allKeys];
  1011. //遍历keys
  1012. for(int i=0;i<[keys count];i++)
  1013. {
  1014. //得到当前key
  1015. NSString *key=[keys objectAtIndex:i];
  1016. //如果key不是pic,说明value是字符类型,比如name:Boris
  1017. NSString* value = [contactjson valueForKey:key];
  1018. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1019. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1020. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1021. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1022. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1023. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1024. }
  1025. }
  1026. // NSDictionary* contactjson= upjson[@"contact"];
  1027. // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1028. // NSDictionary* orderjson= upjson[@"order"];
  1029. // [iSalesDB enable_trigger]
  1030. [iSalesDB enable_trigger];
  1031. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1032. [defaults removeObjectForKey:@"Forcedownload"];
  1033. [defaults setBool:true forKey:@"Forcedownload"];
  1034. [defaults synchronize];
  1035. dispatch_async(dispatch_get_main_queue(), ^{
  1036. //下载函数要从主线程调用
  1037. [weakSelf download_offline:ver useInternalAddress:buseinternaladdress];
  1038. });
  1039. });
  1040. }
  1041. else
  1042. {
  1043. [weakSelf add_downloadlog:[json valueForKey:@"msg"]];
  1044. [weakSelf add_downloadlog:@"Sync canceled."];
  1045. [weakSelf.settingUI onSyncFinish];
  1046. }
  1047. } Progress:^(NSURLSessionTask *task, double progress) {
  1048. } DecryptHandler:nil];
  1049. }
  1050. return;
  1051. }
  1052. -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
  1053. {
  1054. NSString *plistPath = [RAUtils get_config_path];
  1055. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1056. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1057. {
  1058. ver= nil;
  1059. [self add_downloadlog:@"App required a fully sync."];
  1060. }
  1061. if(self.downloading)
  1062. return;
  1063. self.downloading=true;
  1064. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1065. NSString* pvid = [defaults stringForKey:@"vid"] ;
  1066. [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
  1067. [RANetwork request_new_offline_ticket:ver useInternalAddress:false vid:pvid completionHandler:^(NSMutableDictionary *result) {
  1068. NSMutableDictionary* json= result;
  1069. if([json[@"result"] intValue]!=2)
  1070. {
  1071. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1072. [self.settingUI onSyncFinish];
  1073. // self.downloadlog=nil;
  1074. self.downloading=false;
  1075. return;
  1076. }
  1077. else
  1078. {
  1079. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1080. __block NSMutableDictionary* download_json=nil;
  1081. // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1082. NSString* downSerial=[json valueForKey:@"downSerial"];
  1083. [defaults removeObjectForKey:@"downSerial"];
  1084. [defaults setValue:downSerial forKey:@"downSerial"];
  1085. [defaults synchronize];
  1086. // sleep(3);
  1087. //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1088. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1089. // int count=0;
  1090. // // __block bool preparing = true;
  1091. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1092. // {
  1093. // sleep(RETRY_DELAY);
  1094. //
  1095. //
  1096. // count++;
  1097. //// download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1098. //
  1099. // [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1100. // download_json=result;
  1101. // }];
  1102. //
  1103. //
  1104. //
  1105. //
  1106. // }
  1107. [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1108. download_json=result;
  1109. if([download_json[@"result"] intValue]!=RESULT_TRUE)
  1110. {
  1111. [self add_downloadlog:download_json[@"err_msg"]];
  1112. [self add_downloadlog:@"Download Abort."];
  1113. dispatch_async(dispatch_get_main_queue(), ^{
  1114. // self.downloadlog=nil;
  1115. self.downloading=false;
  1116. [self.settingUI onSyncFinish];
  1117. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1118. [defaults removeObjectForKey:@"Forcedownload"];
  1119. [defaults setBool:true forKey:@"Forcedownload"];
  1120. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1121. // [defaults removeObjectForKey:@"downSerial"];
  1122. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1123. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1124. [defaults synchronize];
  1125. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1126. });
  1127. return;
  1128. }
  1129. //服务器准备数据完毕,进入处理数据逻辑。
  1130. if([download_json[@"request_count"] intValue]>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1131. {
  1132. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1133. dispatch_async(dispatch_get_main_queue(), ^{
  1134. // self.downloadlog=nil;
  1135. self.downloading=false;
  1136. });
  1137. dispatch_async(dispatch_get_main_queue(), ^{
  1138. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1139. });
  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. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1154. [defaults removeObjectForKey:@"Forcedownload"];
  1155. [defaults setBool:FALSE forKey:@"Forcedownload"];
  1156. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1157. // [defaults removeObjectForKey:@"downSerial"];
  1158. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1159. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1160. [defaults synchronize];
  1161. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1162. });
  1163. // dispatch_async(dispatch_get_main_queue(), ^{
  1164. //
  1165. // });
  1166. [self.settingUI onSyncFinish];
  1167. return;
  1168. }
  1169. else
  1170. {
  1171. [self add_downloadlog:@"Find a new version, downloading..."];
  1172. self.download_task = [download_json mutableCopy];
  1173. // self.download_task[@"abcdef"]=@"abcdef";
  1174. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1175. [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1176. [self download_offline:true checkdiskspace:true];
  1177. return;
  1178. }
  1179. }
  1180. }];
  1181. }
  1182. }];
  1183. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1184. //
  1185. //
  1186. //
  1187. //
  1188. // NSMutableDictionary* json=[[RANetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
  1189. //
  1190. //
  1191. // if([json[@"result"] intValue]!=2)
  1192. // {
  1193. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1194. // [self.settingUI onSyncFinish];
  1195. // dispatch_async(dispatch_get_main_queue(), ^{
  1196. // // self.downloadlog=nil;
  1197. // self.downloading=false;
  1198. // });
  1199. // return;
  1200. // }
  1201. //
  1202. //
  1203. // dispatch_async(dispatch_get_main_queue(), ^{
  1204. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1205. // });
  1206. //
  1207. //
  1208. // NSMutableDictionary* download_json=nil;
  1209. //
  1210. // // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1211. // NSString* downSerial=[json valueForKey:@"downSerial"];
  1212. //
  1213. // [defaults removeObjectForKey:@"downSerial"];
  1214. // [defaults setValue:downSerial forKey:@"downSerial"];
  1215. //
  1216. // [defaults synchronize];
  1217. //
  1218. // // sleep(3);
  1219. // //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1220. //
  1221. //
  1222. // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1223. // int count=0;
  1224. // // __block bool preparing = true;
  1225. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1226. // {
  1227. // sleep(RETRY_DELAY);
  1228. //
  1229. //
  1230. // count++;
  1231. // download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1232. //
  1233. //
  1234. //
  1235. //
  1236. // }
  1237. //
  1238. // //服务器准备数据完毕,进入处理数据逻辑。
  1239. // if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1240. // {
  1241. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1242. // dispatch_async(dispatch_get_main_queue(), ^{
  1243. // // self.downloadlog=nil;
  1244. // self.downloading=false;
  1245. // });
  1246. // dispatch_async(dispatch_get_main_queue(), ^{
  1247. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1248. // });
  1249. // [self.settingUI onSyncFinish];
  1250. // return;
  1251. // //一直没取到json,出错处理
  1252. // }
  1253. // else
  1254. // {
  1255. // if([download_json[@"count"] intValue]==0)
  1256. // {
  1257. // //没有找到更新包,当前是最新版本
  1258. // [self add_downloadlog:@"You are up-to-date!"];
  1259. // dispatch_async(dispatch_get_main_queue(), ^{
  1260. // // self.downloadlog=nil;
  1261. // self.downloading=false;
  1262. // });
  1263. // dispatch_async(dispatch_get_main_queue(), ^{
  1264. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1265. // });
  1266. // [self.settingUI onSyncFinish];
  1267. // return;
  1268. // }
  1269. // else
  1270. // {
  1271. // [self add_downloadlog:@"Find a new version, downloading..."];
  1272. // self.download_task = [download_json mutableCopy];
  1273. // // self.download_task[@"abcdef"]=@"abcdef";
  1274. // long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1275. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1276. // [self download_offline:true checkdiskspace:true];
  1277. // return;
  1278. // }
  1279. //
  1280. // }
  1281. //
  1282. // });
  1283. }
  1284. #ifdef SCANNER_ORDER
  1285. //- (NSString *)price0_name
  1286. //{
  1287. // if(_price0_name.length==0)
  1288. // {
  1289. // return @"DDP";
  1290. // }
  1291. // else
  1292. // return _price0_name;
  1293. //}
  1294. //- (NSString *)price1_name
  1295. //{
  1296. // if(_price1_name.length==0)
  1297. // {
  1298. // return @"Unit Price";
  1299. // }
  1300. // else
  1301. // return _price1_name;
  1302. //}
  1303. //- (NSString *)price2_name
  1304. //{
  1305. // if(_price2_name.length==0)
  1306. // {
  1307. // return @"Special";
  1308. // }
  1309. // else
  1310. // return _price2_name;
  1311. //}
  1312. //- (NSString *)price3_name
  1313. //{
  1314. // if(_price3_name.length==0)
  1315. // {
  1316. // return @"Net Price";
  1317. // }
  1318. // else
  1319. // return _price3_name;
  1320. //}
  1321. #endif
  1322. -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
  1323. {
  1324. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1325. bool forcedownload = [defaults boolForKey:@"Forcedownload"];
  1326. if(forcedownload|| ver==nil)
  1327. {
  1328. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1329. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1330. syncVC.action_string=@"Download";
  1331. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1332. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1333. navi.modalInPresentation = true;
  1334. navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
  1335. [parent presentViewController:navi animated:YES completion:^{
  1336. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1337. DebugLog(@"about present.........");
  1338. // self.btop = false;
  1339. // <#code#>
  1340. }];
  1341. }
  1342. else
  1343. {
  1344. NSArray* arr_order=nil;
  1345. arr_order=[OLDataProvider enumOfflineOrder];
  1346. // if(arr_order.count>0)
  1347. // {
  1348. //
  1349. // {
  1350. // SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
  1351. // vc.returnValue = ^(NSArray* SelectedOrder){
  1352. //
  1353. // [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
  1354. // SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1355. // syncVC.action_string=@"Download";
  1356. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1357. //
  1358. //
  1359. //
  1360. //
  1361. //
  1362. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1363. //
  1364. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1365. // [parent presentViewController:navi animated:YES completion:^{
  1366. //
  1367. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1368. //
  1369. // DebugLog(@"about present.........");
  1370. //
  1371. // // self.btop = false;
  1372. // // <#code#>
  1373. // }];
  1374. // };
  1375. //
  1376. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
  1377. //
  1378. //
  1379. //
  1380. //
  1381. //
  1382. //
  1383. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1384. // [parent presentViewController:navi animated:YES completion:^{
  1385. //
  1386. //
  1387. // }];
  1388. // }
  1389. //
  1390. //
  1391. // }
  1392. // else
  1393. // {
  1394. NSMutableDictionary* add_params=[NSMutableDictionary new];
  1395. add_params[@"user"]=self.user;
  1396. add_params[@"password"]=self.password;
  1397. add_params[@"contact_id"]=self.contact_id;
  1398. [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order params:add_params];
  1399. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1400. syncVC.action_string=@"Download";
  1401. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1402. navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
  1403. [parent presentViewController:navi animated:YES completion:^{
  1404. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1405. DebugLog(@"about present.........");
  1406. // self.btop = false;
  1407. // <#code#>
  1408. }];
  1409. // }
  1410. }
  1411. }
  1412. -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
  1413. {
  1414. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1415. if(start)
  1416. {
  1417. dispatch_async(dispatch_get_main_queue(), ^{
  1418. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1419. });
  1420. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1421. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1422. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1423. long long needsize = size+500;
  1424. if(needsize>freespace &&checkdiskspace)
  1425. {
  1426. //size not enough.
  1427. NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
  1428. [self add_downloadlog:space];
  1429. [self.settingUI onSyncFinish];
  1430. return ;
  1431. }
  1432. NSString* temp = NSTemporaryDirectory();
  1433. NSString * ver = self.download_task[@"ver"];
  1434. NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
  1435. //创建版本临时目录
  1436. NSFileManager* fileManager = [NSFileManager defaultManager];
  1437. BOOL bdir=YES;
  1438. if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
  1439. {
  1440. NSError *error = nil;
  1441. bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1442. if(!bsuccess)
  1443. DebugLog(@"Create temp folder failed");
  1444. // if(bsuccess)
  1445. // {
  1446. // sqlite3 *db = [self get_db];
  1447. //
  1448. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  1449. // [iSalesDB close_db:db];
  1450. // }
  1451. }
  1452. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
  1453. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1454. if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
  1455. {
  1456. NSError *error = nil;
  1457. bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1458. if(!bsuccess)
  1459. DebugLog(@"Create cache folder failed");
  1460. }
  1461. NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
  1462. NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
  1463. // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
  1464. // {
  1465. //
  1466. // NSError *error = nil;
  1467. // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
  1468. //
  1469. // if(!bsuccess)
  1470. // DebugLog(@"Create resource folder failed");
  1471. //
  1472. // }
  1473. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1474. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  1475. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  1476. NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
  1477. // tempdb=[documents stringByAppendingPathComponent:DBNAME];
  1478. NSError *error = nil;
  1479. bdir=NO;
  1480. if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
  1481. {
  1482. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  1483. if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
  1484. {
  1485. DebugLog(@"copy database failed");
  1486. }
  1487. }
  1488. bdir=YES;
  1489. error=nil;
  1490. int count = [[self.download_task valueForKey:@"count"] intValue];
  1491. bool alldone=true;
  1492. bool trouble=false;
  1493. bool response = false;
  1494. for (int i = 0;i<count;i++)
  1495. {
  1496. NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
  1497. NSString* url = [itemjson valueForKey:@"url"];
  1498. NSString* type = [itemjson valueForKey:@"type"];
  1499. {
  1500. #ifdef DEBUG
  1501. //调试模式下跳过下载图片
  1502. if([type isEqualToString:@"img"])
  1503. {
  1504. itemjson[@"status"]=@"finish";
  1505. continue;
  1506. }
  1507. #endif
  1508. }
  1509. NSString* status = itemjson[@"status"];
  1510. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1511. if(! [status isEqualToString:@"finish"])
  1512. {
  1513. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1514. {
  1515. // [self handle_download:url start:start type:type taskid:i];
  1516. [self handle_download1:url start:start type:type taskid:i];
  1517. alldone=false;
  1518. break;
  1519. }
  1520. else
  1521. {
  1522. alldone=false;
  1523. trouble=true;
  1524. response = [itemjson[@"response"] boolValue];
  1525. break;
  1526. }
  1527. }
  1528. }
  1529. if(trouble)
  1530. {
  1531. NSString* msg =@"offline sync got some trouble, sync canceled.";
  1532. if(response==false)
  1533. {
  1534. msg=@"Cannot connect to server, please check your network.";
  1535. }
  1536. [self add_downloadlog:msg];
  1537. dispatch_async(dispatch_get_main_queue(), ^{
  1538. // self.downloadlog=nil;
  1539. self.downloading=false;
  1540. });
  1541. [self.settingUI onSyncFinish];
  1542. }
  1543. else if(alldone)
  1544. {
  1545. [self add_downloadlog:@"Finalizing download..."];
  1546. //全部下载完成;
  1547. //写入当前版本
  1548. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1549. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1550. NSString* lastsync = [formatter stringFromDate:[NSDate date]];
  1551. NSString* ver= self.download_task[@"ver"];
  1552. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1553. NSString *cachefolder = [paths objectAtIndex:0];
  1554. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  1555. //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
  1556. if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
  1557. {
  1558. DebugLog(@"move image folder failed");
  1559. [self add_downloadlog:@"move image folder failed"];
  1560. trouble=true;
  1561. }
  1562. else
  1563. {
  1564. DebugLog(@"move image folder successful");
  1565. }
  1566. error=nil;
  1567. // copy temp db to cache.
  1568. if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
  1569. {
  1570. if(![fileManager removeItemAtPath:database_path error:nil])
  1571. {
  1572. DebugLog(@"delete database failed");
  1573. }
  1574. else
  1575. {
  1576. if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1577. {
  1578. DebugLog(@"copy database failed");
  1579. [self add_downloadlog:@"copy database failed"];
  1580. trouble=true;
  1581. }
  1582. else{
  1583. //debug
  1584. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1585. [fileManager removeItemAtPath:tempdb error:nil];
  1586. // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
  1587. }
  1588. }
  1589. }
  1590. else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1591. {
  1592. DebugLog(@"copy database failed");
  1593. //debug;
  1594. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1595. [fileManager removeItemAtPath:tempdb error:nil];
  1596. [self add_downloadlog:@"copy database failed"];
  1597. trouble=true;
  1598. }
  1599. // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
  1600. // {
  1601. // DebugLog(@"move db file failed");
  1602. // }
  1603. // else
  1604. // {
  1605. // DebugLog(@"move db file successful");
  1606. // }
  1607. error=nil;
  1608. if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
  1609. {
  1610. DebugLog(@"move data folder failed");
  1611. [self add_downloadlog:@"move data folder failed"];
  1612. trouble=true;
  1613. }
  1614. else
  1615. {
  1616. DebugLog(@"move data folder successful");
  1617. }
  1618. dispatch_async(dispatch_get_main_queue(), ^{
  1619. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1620. });
  1621. if(trouble)
  1622. {
  1623. [self add_downloadlog:@"offline sync failed."];
  1624. // 尚缺更新失败还原逻辑。
  1625. }
  1626. else
  1627. {
  1628. [self add_downloadlog:@"offline sync complete."];
  1629. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1630. [defaults removeObjectForKey:@"OfflineVer"];
  1631. [defaults setValue:ver forKey:@"OfflineVer"];
  1632. [defaults removeObjectForKey:@"LastSync"];
  1633. [defaults setValue:lastsync forKey:@"LastSync"];
  1634. [defaults removeObjectForKey:@"vid"];
  1635. [defaults setValue:self.vid forKey:@"vid"];
  1636. [defaults removeObjectForKey:@"Forcedownload"];
  1637. NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1638. [defaults removeObjectForKey:@"downSerial"];
  1639. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1640. [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1641. [defaults synchronize];
  1642. NSString *plistPath = [RAUtils get_config_path];
  1643. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1644. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1645. {
  1646. config_list[@"NEED_FULLY_SYNC"] = @"false";
  1647. [config_list writeToFile:plistPath atomically:YES];
  1648. }
  1649. [RANetwork request_complete_offline_ticket:downSerial completionHandler:^(NSMutableDictionary *result) {
  1650. }];
  1651. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1652. //
  1653. //
  1654. // //debug
  1655. //// NSDictionary* editor_json = [RANetwork finish_download_Offline:downSerial];
  1656. // [RANetwork finish_download_Offline:downSerial];
  1657. //
  1658. //
  1659. // });
  1660. }
  1661. dispatch_async(dispatch_get_main_queue(), ^{
  1662. // self.downloadlog=nil;
  1663. self.downloading=false;
  1664. self.download_task=nil;
  1665. self.vid=nil;
  1666. [self.settingUI onSyncFinish];
  1667. });
  1668. }
  1669. }
  1670. else
  1671. {
  1672. int count = [[self.download_task valueForKey:@"count"] intValue];
  1673. for (int i = 0;i<count;i++)
  1674. {
  1675. NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
  1676. NSString* url = [itemjson valueForKey:@"url"];
  1677. NSString* type = [itemjson valueForKey:@"type"];
  1678. NSString* status = itemjson[@"status"];
  1679. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1680. if(! [status isEqualToString:@"finish"])
  1681. {
  1682. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1683. {
  1684. // [self handle_download:url start:start type:type taskid:i];
  1685. [self handle_download1:url start:start type:type taskid:i];
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. dispatch_async(dispatch_get_main_queue(), ^{
  1691. self.downloading=false;
  1692. });
  1693. }
  1694. }
  1695. -(void) add_downloadlog:(NSString*) newtext
  1696. {
  1697. // if(!self.downloading)
  1698. // return;
  1699. dispatch_async(dispatch_get_main_queue(), ^{
  1700. NSString* date;
  1701. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1702. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1703. date = [formatter stringFromDate:[NSDate date]];
  1704. if(newtext.length<=0)
  1705. return;
  1706. NSString* text = self.downloadlog;
  1707. if(text.length==0)
  1708. text=@"";
  1709. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1710. self.downloadlog = text;
  1711. [self.settingUI onLogUpdate];
  1712. });
  1713. }
  1714. -(int)unpack
  1715. {
  1716. //return;
  1717. //DebugLog(_fileName);
  1718. ///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
  1719. //文件路径
  1720. // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  1721. NSString* temp = NSTemporaryDirectory();
  1722. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1723. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
  1724. NSString * ver = self.download_task[@"ver"];
  1725. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
  1726. NSString *zipFile = [temp stringByAppendingPathComponent:location];
  1727. ZipArchive* zip = [[ZipArchive alloc] init];
  1728. // filename stringByDeletingPathExtension
  1729. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1730. // NSString *cachefolder = [paths objectAtIndex:0];
  1731. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1732. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1733. //
  1734. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1735. // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  1736. //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
  1737. // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
  1738. DebugLog(@"path: %@",unZipTo);
  1739. if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
  1740. BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
  1741. if( NO==result )
  1742. {
  1743. // int aaa=0;
  1744. //解压失败
  1745. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1746. if(freespace<=10)
  1747. {
  1748. return UNZIP_NO_SPACE;
  1749. }
  1750. [zip UnzipCloseFile];
  1751. //文件损坏,删除文件重试
  1752. NSFileManager* fileManager=[NSFileManager defaultManager];
  1753. //debug
  1754. // BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
  1755. [fileManager removeItemAtPath:zipFile error:nil];
  1756. [fileManager removeItemAtPath:unZipTo error:nil];
  1757. return UNZIP_FILE_DAMAGE;
  1758. }
  1759. else
  1760. {
  1761. [zip UnzipCloseFile];
  1762. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
  1763. NSFileManager *fileManager = [NSFileManager defaultManager];
  1764. [fileManager removeItemAtPath:zipFile error:nil];
  1765. return UNZIP_SUCCESS;
  1766. //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
  1767. }
  1768. //[zip UnzipCloseFile];
  1769. }
  1770. else
  1771. {
  1772. //打开文件失败,通常是文件路径有问题或密码错误。
  1773. return UNZIP_OPEN_FAILED;
  1774. // NSFileManager *fileManager = [NSFileManager defaultManager];
  1775. // [fileManager removeItemAtPath:zipFile error:nil];
  1776. }
  1777. // [zip release];
  1778. }
  1779. #pragma mark - NSURLConnectionDelegate
  1780. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  1781. DebugLog(@"%d error message:%@",self.current_task,error);
  1782. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1783. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  1784. currenttask[@"status"] = @"pause";
  1785. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1786. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1787. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1788. // self.currentLength = 0;
  1789. // self.fileLength = 0;
  1790. [self.fileHandle closeFile];
  1791. self.fileHandle = nil;
  1792. [self.connection cancel];
  1793. self.connection = nil;
  1794. [self download_offline:true checkdiskspace:false];
  1795. }
  1796. #pragma mark - NSURLConnectionDataDelegate
  1797. /**
  1798. *请求失败
  1799. */
  1800. /**
  1801. *接收到服务器的响应
  1802. */
  1803. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  1804. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  1805. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  1806. DebugLog(@"%d begin",self.current_task);
  1807. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1808. //获取下载文件大小
  1809. // self.fileLength = response.expectedContentLength;
  1810. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1811. //获取文件名
  1812. //self.fileName = response.suggestedFilename;
  1813. currenttask[@"fileName"] = response.suggestedFilename;
  1814. currenttask[@"response"] = @"true";
  1815. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  1816. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1817. //文件路径
  1818. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  1819. NSString * ver = self.download_task[@"ver"];
  1820. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  1821. NSString *filePath = [temp stringByAppendingPathComponent:location];
  1822. DebugLog(@"save to: %@",filePath);
  1823. if (position>0) {
  1824. //不需要创建文件;
  1825. //创建一个用来写数据的文件句柄
  1826. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1827. return;
  1828. }
  1829. // 第一次获取的才是文件正确大小
  1830. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  1831. //创建一个空的文件到沙盒
  1832. NSFileManager *fileManager = [NSFileManager defaultManager];
  1833. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  1834. //创建一个用来写数据的文件句柄
  1835. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1836. }else{
  1837. //debug 这里缺少文件的情况还没处理
  1838. [self.connection cancel];
  1839. self.connection = nil;
  1840. DebugLog(@"该文件不存在");
  1841. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
  1842. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  1843. [self add_downloadlog:str_status];
  1844. }
  1845. }
  1846. /**
  1847. *接收到服务器返回的数据(可能被调用多次)
  1848. */
  1849. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  1850. //移动到文件末尾
  1851. [self.fileHandle seekToEndOfFile];
  1852. //写入数据到文件
  1853. [self.fileHandle writeData:data];
  1854. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1855. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1856. position += data.length;
  1857. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  1858. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1859. //更新画面中的进度
  1860. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  1861. double progress = (double)position/fileLength;
  1862. self.file_progress = progress;
  1863. [self.settingUI onProgressUpdate];
  1864. }
  1865. /**
  1866. *服务器返回数据完了
  1867. */
  1868. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  1869. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1870. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  1871. DebugLog(@"%d finish",self.current_task);
  1872. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  1873. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1874. // self.currentLength = 0;
  1875. // self.fileLength = 0;
  1876. [self.fileHandle closeFile];
  1877. self.fileHandle = nil;
  1878. int result=[self unpack];
  1879. NSString* temp = NSTemporaryDirectory();
  1880. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1881. NSString * ver = self.download_task[@"ver"];
  1882. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1883. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1884. switch (result) {
  1885. case UNZIP_FILE_DAMAGE:
  1886. {
  1887. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1888. currenttask[@"status"] = @"pause";
  1889. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1890. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1891. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1892. // self.currentLength = 0;
  1893. // self.fileLength = 0;
  1894. [self.fileHandle closeFile];
  1895. self.fileHandle = nil;
  1896. [self.connection cancel];
  1897. self.connection = nil;
  1898. break;
  1899. }
  1900. case UNZIP_SUCCESS:
  1901. {
  1902. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  1903. if([type isEqualToString:@"img"])
  1904. {
  1905. NSString* parent_path = self.download_task[@"path"];
  1906. if(parent_path.length==0)
  1907. parent_path=@"";
  1908. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  1909. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  1910. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  1911. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1912. BOOL bdir=YES;
  1913. NSError *error = nil;
  1914. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  1915. {
  1916. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1917. if(!bsuccess)
  1918. DebugLog(@"Create temp folder failed");
  1919. }
  1920. error=nil;
  1921. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  1922. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  1923. // NSError *error = nil;
  1924. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  1925. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  1926. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  1927. // backupItemName:backup
  1928. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  1929. // resultingItemURL:nil error:&error])
  1930. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  1931. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  1932. {
  1933. DebugLog(@"move image folder failed");
  1934. }
  1935. else
  1936. {
  1937. currenttask[@"status"] = @"finish";
  1938. DebugLog(@"move image folder successful");
  1939. }
  1940. }
  1941. else if([type isEqualToString:@"sql"])
  1942. {
  1943. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  1944. NSString * ver = self.download_task[@"ver"];
  1945. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  1946. tempdb=[temp stringByAppendingPathComponent:tempdb];
  1947. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  1948. [self add_downloadlog:@"updating local database..."];
  1949. @try {
  1950. char *errmsg=NULL;
  1951. // [iSalesDB disable_trigger]
  1952. [iSalesDB disable_trigger];
  1953. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  1954. {
  1955. 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;drop trigger if exists offline_pdf;", NULL, NULL, &errmsg);
  1956. sqlite3_free(errmsg);
  1957. DebugLog(@"开启事务");
  1958. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  1959. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  1960. int count = [orderjson[@"count"] intValue];
  1961. for(int i=0;i<count;i++)
  1962. {
  1963. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  1964. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  1965. NSError *error = nil;
  1966. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  1967. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  1968. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  1969. {
  1970. //throw exception;
  1971. if(errmsg==nil)
  1972. errmsg="Unknown error.";
  1973. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  1974. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  1975. }
  1976. sqlite3_free(errmsg);
  1977. }
  1978. 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);
  1979. }
  1980. //提交事务
  1981. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  1982. DebugLog(@"提交事务");
  1983. sqlite3_free(errmsg);
  1984. }
  1985. [self add_downloadlog:@"updating local database successful"];
  1986. currenttask[@"status"] = @"finish";
  1987. }
  1988. @catch (NSException *exception) {
  1989. char *errmsg=NULL;
  1990. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  1991. [self add_downloadlog:@"updating local database failed rollback..."];
  1992. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  1993. DebugLog(@"回滚事务");
  1994. }
  1995. else
  1996. {
  1997. [self add_downloadlog:@"rollback failed."];
  1998. }
  1999. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  2000. currenttask[@"status"] = @"pause";
  2001. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  2002. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  2003. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  2004. // self.currentLength = 0;
  2005. // self.fileLength = 0;
  2006. [self.fileHandle closeFile];
  2007. self.fileHandle = nil;
  2008. [self.connection cancel];
  2009. self.connection = nil;
  2010. //break;
  2011. }
  2012. @finally {
  2013. // [iSalesDB enable_trigger]
  2014. [iSalesDB enable_trigger];
  2015. sqlite3_close(tdb);
  2016. // [iSalesDB close_db:tdb];
  2017. // [self SelectData];
  2018. }
  2019. }
  2020. else if([type isEqualToString:@"script"])
  2021. {
  2022. currenttask[@"status"] = @"finish";
  2023. }
  2024. else if([type isEqualToString:@"resource"])
  2025. {
  2026. currenttask[@"status"] = @"finish";
  2027. }
  2028. // debug
  2029. // int c=self.current_task+1;
  2030. // double t=[ self.download_task[@"count"] doubleValue];
  2031. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  2032. self.overall_progress = oprogress;
  2033. [self.settingUI onProgressUpdate];
  2034. break;
  2035. }
  2036. case UNZIP_NO_SPACE:
  2037. {
  2038. [self add_downloadlog:@"Disk space not enough."];
  2039. break;
  2040. }
  2041. case UNZIP_OPEN_FAILED:
  2042. {
  2043. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  2044. break;
  2045. }
  2046. default:
  2047. break;
  2048. }
  2049. [self download_offline:true checkdiskspace:false];
  2050. }
  2051. -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
  2052. {
  2053. RAPDFViewController *ViewController = [[UIStoryboard storyboardWithName:@"wkweb" bundle:nil] instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
  2054. ViewController.url = url;
  2055. ViewController.canSave = false;
  2056. ViewController.mail_content = content;
  2057. if(soid==nil)
  2058. soid =@"";
  2059. if(company==nil)
  2060. company =@"";
  2061. ViewController.save_name =soid;
  2062. NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
  2063. if(send_to.length>0)
  2064. {
  2065. arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2066. // customer_email compo
  2067. // [send_to addObject:customer_email];
  2068. }
  2069. ViewController.mail_to = arrsend_to;
  2070. #if defined(BUILD_NPD) || defined(BUILD_USAI)|| defined (BUILD_CONTRAST)
  2071. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];//[arr_subject componentsJoinedByString:@" : "];
  2072. if (self.user_type == USER_ROLE_CUSTOMER && ![RASingleton sharedInstance].currentOrderIsMerged) {
  2073. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  2074. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  2075. }
  2076. #else
  2077. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];
  2078. #endif
  2079. ViewController.mail_subject = subject;
  2080. // NSString* subject;
  2081. // if (company.length==0) {
  2082. // NSString* cur_time =[RAUtils current_date];
  2083. // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
  2084. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2085. // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
  2086. //
  2087. //
  2088. // NSMutableArray* send_to = [[NSMutableArray alloc]init];
  2089. // if(customer_email.length>0)
  2090. // {
  2091. // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2092. // // customer_email compo
  2093. // // [send_to addObject:customer_email];
  2094. // }
  2095. // ViewController.mail_to = send_to;
  2096. // }
  2097. // else
  2098. // {
  2099. // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
  2100. // }
  2101. // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
  2102. // ViewController.mail_subject = subject;
  2103. ViewController.autoPrint=true;
  2104. ViewController.hidenavi = false;
  2105. [self.main_vc.navigationController pushViewController:ViewController animated:YES];
  2106. // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
  2107. }
  2108. //-(void) addScannerReceiver:(NSString*)classname
  2109. //{
  2110. // [self.arr_scannerReceiver addObject:classname];
  2111. //}
  2112. -(void) setScannerDelegate:(id<ScanApiHelperDelegate>)delegate
  2113. {
  2114. [ScanApi setDelegate:delegate];
  2115. }
  2116. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2117. {
  2118. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2119. // 蓝牙扫描枪
  2120. #ifdef USE_BLE_SCANNER
  2121. self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  2122. _cbReady = false;
  2123. _nDevices = [[NSMutableArray alloc]init];
  2124. _nServices = [[NSMutableArray alloc]init];
  2125. _nCharacteristics = [[NSMutableArray alloc]init];
  2126. self.bAutoConnect=[defaults boolForKey:@"BLE_AutoReconnect"];
  2127. self.bAppBTOn=[defaults boolForKey:@"BLE_Enable"];
  2128. if(self.bAutoConnect)
  2129. {
  2130. self.strDeviceName = [defaults valueForKey:@"BLE_Name"];
  2131. self.strDeviceUUID = [defaults valueForKey:@"BLE_UUID"];
  2132. }
  2133. #endif
  2134. // [defaults removeObjectForKey:@"BLE_AutoReconnect"];
  2135. #ifdef SCANNER_ORDER
  2136. //审核时连接测试数据库
  2137. // NSDate *cdate= [NSDate date];
  2138. // NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
  2139. // [dateFormatter setDateFormat:@"yyyy-MM-dd"];
  2140. //
  2141. //NSDate * ddate =[dateFormatter dateFromString:@"2022-07-08"];
  2142. //
  2143. //// bool review=[cdate earlierDate:ddate];
  2144. // NSTimeInterval secondsInterval= [cdate timeIntervalSinceDate:ddate];
  2145. // int sec =secondsInterval;
  2146. bool rtime = [RADataProvider scanRtime];
  2147. NSDictionary *addressDic = [[NSUserDefaults standardUserDefaults] valueForKey:@"ScanAddress"];
  2148. if(rtime && !addressDic)
  2149. {
  2150. NSUInteger selectedIndex = 1;
  2151. // 保存信息
  2152. NSString *name = @"HMLG";
  2153. NSString *show_name = @"FREMONT, CA";
  2154. NSString *internalAddr =@"https://erp.homelegance.com/" ;
  2155. int price_index = 0;
  2156. // NSString *externalAddr = weakself.externalTextField.text;
  2157. NSMutableDictionary *addressDic = [NSMutableDictionary dictionary];
  2158. if (internalAddr.length) {
  2159. [addressDic setObject:internalAddr forKey:@"serverAddress"];
  2160. }
  2161. // if (externalAddr.length) {
  2162. // [addressDic setObject:externalAddr forKey:@"externalAddress"];
  2163. // }
  2164. if (name.length) {
  2165. [addressDic setObject:name forKey:@"name"];
  2166. }
  2167. if (show_name.length) {
  2168. [addressDic setObject:show_name forKey:@"show_name"];
  2169. }
  2170. addressDic[@"has_erp_site"] = @(true);
  2171. [addressDic setObject:@(price_index) forKey:@"price_index"];
  2172. [addressDic setObject:@(selectedIndex) forKey:@"selectedIndex"];
  2173. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  2174. [userDefaults setValue:addressDic forKey:@"ScanAddress"];
  2175. [userDefaults synchronize];
  2176. }
  2177. self.compressFile = [[RAUPloadManagerConfigure alloc] init].compressImage;
  2178. #endif
  2179. //#ifdef OFFLINE_ORDER
  2180. //
  2181. //#endif
  2182. self.window.backgroundColor = [UIColor whiteColor];
  2183. // [RAUtils expression_varable:nil regex:nil];
  2184. // self.disable_trigger = false;
  2185. [iSalesDB enable_trigger];
  2186. [self initialExceptionHandler];
  2187. [self becomeObserver];
  2188. #ifdef GOOGLE_ANALYTICS
  2189. [self setUpGoogleAnalytics];
  2190. #endif
  2191. [DefaultAppearance init_appearance];
  2192. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2193. NSString *cachefolder = [paths objectAtIndex:0];
  2194. NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
  2195. // upfolder = [upfolder stringByAppendingPathComponent:serial];
  2196. NSFileManager* fileManager = [NSFileManager defaultManager];
  2197. BOOL bdir=YES;
  2198. if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
  2199. {
  2200. NSError *error = nil;
  2201. bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
  2202. if(!bsuccess)
  2203. DebugLog(@"Create UPLOAD folder failed");
  2204. }
  2205. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  2206. if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
  2207. {
  2208. NSError *error = nil;
  2209. bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
  2210. if(!bsuccess)
  2211. DebugLog(@"Create PDF Cache folder failed");
  2212. }
  2213. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2214. //
  2215. // DebugLog(@"文件已经存在了");
  2216. //
  2217. // }
  2218. // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
  2219. // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
  2220. //
  2221. //
  2222. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2223. // NSString *documents = [paths objectAtIndex:0];
  2224. // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
  2225. //
  2226. //
  2227. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2228. //
  2229. // DebugLog(@"文件已经存在了");
  2230. //
  2231. // }
  2232. // else
  2233. // {
  2234. //
  2235. //
  2236. //
  2237. // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
  2238. //
  2239. // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
  2240. //
  2241. // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
  2242. //
  2243. // [[NSFileManager defaultManager] createFileAtPath:dist_path
  2244. //
  2245. // contents:mainBundleFile
  2246. //
  2247. // attributes:nil];
  2248. //
  2249. // }
  2250. self.recent_model = [[NSMutableDictionary alloc]init];
  2251. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2252. bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
  2253. self.offline_mode = offline;
  2254. // Override point for customization after application launch.
  2255. if ( [iSalesDB initializeDb]!=0)
  2256. DebugLog(@"init db failed");
  2257. // disable apn
  2258. // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
  2259. self.contact_id=nil;
  2260. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2261. NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
  2262. if([enable_cache isEqualToString:@"false"])
  2263. self.bEnable_Cache = false;
  2264. else
  2265. self.bEnable_Cache = true;
  2266. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  2267. self.build =[infoDict objectForKey:@"CFBundleVersion"];
  2268. //scanner
  2269. _feedbackStack=[[NSMutableArray alloc]init];
  2270. self.devices=[[NSMutableArray alloc]init];
  2271. // change this to YES if you want SingleEntry to
  2272. // confirm the decoded data
  2273. self.doAppDataConfirmation=NO;
  2274. if(ScanApi==nil){
  2275. #ifdef USE_SOFTSCAN
  2276. // this is useful for SoftScan to keep a handle
  2277. // that is used in the trigger button
  2278. _softScanDeviceInfo=nil;
  2279. #endif
  2280. ScanApi=[[ScanApiHelper alloc]init];
  2281. [ScanApi setDelegate:self];
  2282. self.enable_ScannerLog = true;
  2283. self.api_Status= API_STOP;
  2284. // UIApplication * app = [UIApplication sharedApplication];
  2285. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  2286. //
  2287. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2288. bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
  2289. if(autolaunch==true)
  2290. [self enableScanner:autolaunch];
  2291. }
  2292. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2293. [self handleErrorLog];
  2294. });
  2295. return YES;
  2296. }
  2297. #pragma mark - Feedback stack
  2298. -(void)pushFeedback:(id<ScannerEventsFeedback>)feedback{
  2299. long index =[_feedbackStack indexOfObject:feedback];
  2300. if(index!=NSNotFound)
  2301. {
  2302. // if(index!=_feedbackStack.count-1)
  2303. // {
  2304. // [_feedbackStack exchangeObjectAtIndex:index withObjectAtIndex:_feedbackStack.count-1];
  2305. // _eventsFeedback = feedback;
  2306. // }
  2307. }
  2308. else
  2309. {
  2310. [_feedbackStack addObject:feedback];
  2311. }
  2312. _eventsFeedback = feedback;
  2313. // if(_eventsFeedback != feedback){
  2314. // if(_eventsFeedback!=nil){
  2315. // [_feedbackStack addObject:_eventsFeedback];
  2316. // }
  2317. // _eventsFeedback=feedback;
  2318. //// [self generateDeviceArrivals];
  2319. // }
  2320. }
  2321. -(void)popFeedback:(id<ScannerEventsFeedback>)feedback{
  2322. [_feedbackStack removeObject:feedback];
  2323. if(_feedbackStack.count>0)
  2324. _eventsFeedback = _feedbackStack[_feedbackStack.count-1];
  2325. else
  2326. _eventsFeedback = nil;
  2327. // if(_eventsFeedback ==feedback){
  2328. // if(_feedbackStack.count>0){
  2329. // id<ScannerEventsFeedback> newDelegate=[_feedbackStack objectAtIndex:_feedbackStack.count-1];
  2330. // [_feedbackStack removeLastObject];
  2331. // _eventsFeedback = newDelegate;
  2332. // // generate a device Arrival for each scanner we've already receive
  2333. // // so that the new view can be aware of the connected scanners
  2334. //// [self generateDeviceArrivals];
  2335. // }
  2336. // else{
  2337. // _eventsFeedback=nil;
  2338. // }
  2339. // }
  2340. }
  2341. -(void)setFeedback:(id<ScannerEventsFeedback>)feedback
  2342. {
  2343. _eventsFeedback = feedback;
  2344. }
  2345. #pragma mark - ScanApiHelper complete delegates
  2346. // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
  2347. // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
  2348. // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
  2349. // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
  2350. // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
  2351. // callback received when the Get Symbology Status is completed
  2352. -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
  2353. [self addlog:@"onGetSymbologyDpm:"];
  2354. SKTRESULT result=[[scanObj Msg]Result];
  2355. if(SKTSUCCESS(result)){
  2356. DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
  2357. if(deviceInfo!=nil){
  2358. ISktScanSymbology* symbology=[[scanObj Property]Symbology];
  2359. if([symbology getStatus]==kSktScanSymbologyStatusDisable){
  2360. [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
  2361. }
  2362. }
  2363. }
  2364. else{
  2365. // an error message should be displayed here
  2366. // indicating that the DPM symbology status cannot be retrieved
  2367. }
  2368. }
  2369. // callback received when the Set Symbology Status is completed
  2370. -(void)onSetSymbology:(ISktScanObject*)scanObj{
  2371. [self addlog:@"onSetSymbology:"];
  2372. SKTRESULT result=[[scanObj Msg]Result];
  2373. if(!SKTSUCCESS(result)){
  2374. // display an error message saying a symbology cannot be set
  2375. }
  2376. }
  2377. /**
  2378. *
  2379. */
  2380. -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
  2381. [self addlog:@"onSetDataConfirmationMode:"];
  2382. SKTRESULT result=[[scanObj Msg]Result];
  2383. if(SKTSUCCESS(result)){
  2384. [self addlog:@"DataConfirmation Mode OK"];
  2385. }
  2386. else{
  2387. [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
  2388. }
  2389. }
  2390. /**
  2391. *
  2392. */
  2393. -(void) onDataConfirmation:(ISktScanObject*)scanObj{
  2394. [self addlog:@"onDataConfirmation:"];
  2395. SKTRESULT result=[[scanObj Msg]Result];
  2396. if(SKTSUCCESS(result)){
  2397. [self addlog:@"Data Confirmed OK"];
  2398. }
  2399. else{
  2400. [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
  2401. }
  2402. }
  2403. /**
  2404. *
  2405. */
  2406. -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
  2407. [self addlog:@"onSetLocalDecodeAction:"];
  2408. SKTRESULT result=[[scanObj Msg]Result];
  2409. if(SKTSUCCESS(result)){
  2410. [self addlog:@"Local Decode Action OK"];
  2411. }
  2412. else{
  2413. [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
  2414. }
  2415. }
  2416. /**
  2417. *
  2418. */
  2419. -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
  2420. SKTRESULT result=[[scanObj Msg]Result];
  2421. if(SKTSUCCESS(result)){
  2422. ISktScanProperty* property=[scanObj Property];
  2423. [self addlog:@"SoftScan status:"];
  2424. if([property getByte]==kSktScanEnableSoftScan){
  2425. [self addlog:@"SoftScan is ENABLED"];
  2426. _softScannerEnabled=TRUE;
  2427. }
  2428. else{
  2429. _softScannerEnabled=FALSE;
  2430. [self addlog:@"SoftScan is DISABLED"];
  2431. }
  2432. }
  2433. else{
  2434. [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
  2435. }
  2436. }
  2437. /**
  2438. *
  2439. */
  2440. -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
  2441. [self addlog:@"onSetSoftScanStatus:"];
  2442. SKTRESULT result=[[scanObj Msg]Result];
  2443. if(SKTSUCCESS(result)){
  2444. [self addlog:@"SoftScan set status success"];
  2445. }
  2446. else{
  2447. [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
  2448. }
  2449. }
  2450. /**
  2451. *
  2452. */
  2453. -(void) onSetTrigger:(ISktScanObject*)scanObj{
  2454. [self addlog:@"onSetTrigger:"];
  2455. SKTRESULT result=[[scanObj Msg]Result];
  2456. if(SKTSUCCESS(result)){
  2457. [self addlog:@"Trigger set success"];
  2458. }
  2459. else{
  2460. [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
  2461. }
  2462. }
  2463. /**
  2464. *
  2465. */
  2466. -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
  2467. [self addlog:@"onGetScanApiVersion:"];
  2468. SKTRESULT result=[[scanObj Msg]Result];
  2469. if(SKTSUCCESS(result))
  2470. {
  2471. ISktScanProperty*property=[scanObj Property];
  2472. if([property getType]==kSktScanPropTypeVersion)
  2473. {
  2474. scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
  2475. [[property Version]getMajor],
  2476. [[property Version]getMiddle],
  2477. [[property Version]getMinor],
  2478. [[property Version]getBuild]];
  2479. }
  2480. }
  2481. else{
  2482. scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
  2483. }
  2484. [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
  2485. }
  2486. /**
  2487. *
  2488. */
  2489. #ifdef USE_SOFTSCAN
  2490. -(void) onSetOverlayView:(ISktScanObject*)scanObj{
  2491. SKTRESULT result=[[scanObj Msg]Result];
  2492. if(SKTSUCCESS(result)){
  2493. [self addlog:@"Overlay view set success"];
  2494. }
  2495. else{
  2496. [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
  2497. }
  2498. }
  2499. #endif
  2500. /**
  2501. * called each time a device connects to the host
  2502. * @param result contains the result of the connection
  2503. * @param newDevice contains the device information
  2504. */
  2505. -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
  2506. [self addlog:@"onDeviceArrival:"];
  2507. [self updateDevicesList:deviceInfo Add:YES];
  2508. #ifdef USE_SOFTSCAN
  2509. // if the scanner is a SoftScan scanner
  2510. if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
  2511. // _softScannerTriggerBtn.hidden=NO;
  2512. _softScanDeviceInfo=deviceInfo;
  2513. if(_deviceInfoToTrigger==nil)
  2514. _deviceInfoToTrigger=deviceInfo;
  2515. NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
  2516. [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
  2517. [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
  2518. }
  2519. else
  2520. #endif
  2521. {
  2522. if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
  2523. // _softScannerTriggerBtn.hidden=NO;
  2524. _deviceInfoToTrigger=deviceInfo;
  2525. }
  2526. if(_doAppDataConfirmation==YES){
  2527. // switch the comment between the 2 following lines for handling the
  2528. // data confirmation beep from the scanner (local)
  2529. // if none is set, the scanner will beep only once when SingleEntry actually
  2530. // confirm the decoded data, otherwise the scanner will beep twice, one locally,
  2531. // and one when SingleEntry will confirm the decoded data
  2532. [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
  2533. // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
  2534. }
  2535. // for demonstration only, let's make sure the DPM is enabled
  2536. // first interrogate the scanner to see if it's already enabled
  2537. // and in the onGetSymbologyDpm callback, if the DPM is not already set
  2538. // then we send a Symbology property to enable it.
  2539. [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
  2540. }
  2541. }
  2542. /**
  2543. * called each time a device disconnect from the host
  2544. * @param deviceRemoved contains the device information
  2545. */
  2546. -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
  2547. [self addlog:@"onDeviceRemoval:"];
  2548. [self updateDevicesList:deviceRemoved Add:NO];
  2549. if(_deviceInfoToTrigger==deviceRemoved){
  2550. _deviceInfoToTrigger=nil;
  2551. }
  2552. #ifdef USE_SOFTSCAN
  2553. if(_softScanDeviceInfo==deviceRemoved){
  2554. _softScanDeviceInfo=nil;
  2555. }
  2556. if(_deviceInfoToTrigger==nil)
  2557. _deviceInfoToTrigger=_softScanDeviceInfo;
  2558. #endif
  2559. if(_deviceInfoToTrigger==nil){
  2560. // _softScannerTriggerBtn.hidden=YES;
  2561. }
  2562. }
  2563. /**
  2564. * called each time ScanAPI is reporting an error
  2565. * @param result contains the error code
  2566. */
  2567. -(void) onError:(SKTRESULT) result{
  2568. [self addlog:@"onError:"];
  2569. [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2570. #ifdef RA_NOTIFICATION
  2571. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2572. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2573. }
  2574. #else
  2575. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2576. [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2577. #endif
  2578. // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
  2579. }
  2580. /**
  2581. * called each time ScanAPI receives decoded data from scanner
  2582. * @param deviceInfo contains the device information from which
  2583. * the data has been decoded
  2584. * @param decodedData contains the decoded data information
  2585. */
  2586. -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2587. [self addlog:@"onDecodedDataResult:"];
  2588. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2589. if(SKTSUCCESS(result)){
  2590. NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  2591. #ifdef RA_NOTIFICATION
  2592. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2593. [_eventsFeedback onDecodedData:cleanString];
  2594. }
  2595. #else
  2596. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2597. [avc onDecodedData:cleanString];
  2598. #endif
  2599. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2600. [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
  2601. if(_doAppDataConfirmation==YES){
  2602. [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2603. }
  2604. }
  2605. }
  2606. -(void) test_onDecodedDataResult:(NSString*) value
  2607. {
  2608. [self addlog:@"onDecodedDataResult:"];
  2609. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2610. if(true){
  2611. #ifdef RA_NOTIFICATION
  2612. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2613. [_eventsFeedback onDecodedData:value];
  2614. }
  2615. #else
  2616. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2617. [avc onDecodedData:value];
  2618. #endif
  2619. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2620. [self addlog:value];
  2621. // if(_doAppDataConfirmation==YES){
  2622. // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2623. // }
  2624. }
  2625. }
  2626. //-(void) didRotated
  2627. //{
  2628. //
  2629. //}
  2630. /**
  2631. * called when ScanAPI initialization has been completed
  2632. * @param result contains the initialization result
  2633. */
  2634. -(void) onScanApiInitializeComplete:(SKTRESULT) result{
  2635. [self addlog:@"onScanApiInitializeComplete:"];
  2636. if(SKTSUCCESS(result))
  2637. {
  2638. self.api_Status = API_START;
  2639. NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
  2640. [self addlog:strlog];
  2641. #ifdef USE_SOFTSCAN
  2642. // make sure we support SoftScan
  2643. [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2644. // check if SoftScan is enabled
  2645. [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
  2646. #else
  2647. // disable support SoftScan (Default, not really needed if it was never activated)
  2648. [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2649. #endif
  2650. // ask for ScanAPI version (not a requirement but always nice to know)
  2651. [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
  2652. // configure ScanAPI for doing App Data confirmation,
  2653. // if TRUE then SingleEntry will confirm the decoded data
  2654. if(_doAppDataConfirmation==YES){
  2655. [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
  2656. }
  2657. #ifdef RA_NOTIFICATION
  2658. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2659. [_eventsFeedback onStatusChanged:@"Waiting for scanner..."];
  2660. }
  2661. #else
  2662. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2663. [avc onStatusChanged:@"Waiting for scanner..."];
  2664. #endif
  2665. self.Status_Text = @"Waiting for scanner...";
  2666. // _Status.text=@"Waiting for scanner...";
  2667. }
  2668. else{
  2669. #ifdef RA_NOTIFICATION
  2670. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2671. [_eventsFeedback onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2672. }
  2673. #else
  2674. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2675. [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2676. #endif
  2677. self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2678. // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2679. NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2680. [self addlog:strlog];
  2681. }
  2682. }
  2683. /**
  2684. * called when ScanAPI has been terminated. This will be
  2685. * the last message received from ScanAPI
  2686. */
  2687. -(void) onScanApiTerminated{
  2688. [self addlog:@"onScanApiTerminated:"];
  2689. [ScanApiConsumer invalidate];
  2690. ScanApiConsumer= nil;
  2691. [self addlog:@"ScanApiConsumer invalidate"];
  2692. self.api_Status = API_STOP;
  2693. #ifdef RA_NOTIFICATION
  2694. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2695. [_eventsFeedback onStatusChanged:@"Off"];
  2696. }
  2697. #else
  2698. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2699. [avc onStatusChanged:@"Off"];
  2700. #endif
  2701. self.Status_Text =@"Off";
  2702. // _Status.text = @"Off";
  2703. }
  2704. /**
  2705. * called when an error occurs during the retrieval
  2706. * of a ScanObject from ScanAPI.
  2707. * @param result contains the retrieval error code
  2708. */
  2709. -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
  2710. [self addlog:@"onErrorRetrievingScanObject:"];
  2711. [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2712. //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
  2713. #ifdef RA_NOTIFICATION
  2714. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2715. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2716. }
  2717. #else
  2718. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2719. [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2720. #endif
  2721. }
  2722. #pragma mark - Scaner
  2723. -(void)onTimer: (NSTimer*)theTimer{
  2724. if(theTimer==ScanApiConsumer){
  2725. // [self addlog:@"ScanApi::doScanApiReceive:"];
  2726. [ScanApi doScanApiReceive];
  2727. }
  2728. }
  2729. -(void) addlog:(NSString*) newtext
  2730. {
  2731. if(!self.enable_ScannerLog)
  2732. return;
  2733. dispatch_async(dispatch_get_main_queue(), ^{
  2734. NSString* date;
  2735. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  2736. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  2737. date = [formatter stringFromDate:[NSDate date]];
  2738. if(newtext.length<=0)
  2739. return;
  2740. NSString* text = self.log;
  2741. if(text.length==0)
  2742. text=@"";
  2743. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  2744. self.log = text;
  2745. #ifdef RA_NOTIFICATION
  2746. if((self->_eventsFeedback!=nil)&&([self->_eventsFeedback respondsToSelector:@selector(onLogUpdate)])){
  2747. [self->_eventsFeedback onLogUpdate];
  2748. }
  2749. #else
  2750. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2751. [avc onLogUpdate];
  2752. #endif
  2753. });
  2754. }
  2755. - (void)enableScanner:(bool)enable {
  2756. [self addlog:@"Enable scanner:"];
  2757. if(enable)
  2758. {
  2759. [self addlog:@"Enable"];
  2760. self.api_Status = API_INIT;
  2761. #ifdef RA_NOTIFICATION
  2762. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2763. [_eventsFeedback onStatusChanged:@"Initialize..."];
  2764. }
  2765. #else
  2766. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2767. [avc onStatusChanged:@"Initialize..."];
  2768. #endif
  2769. self.Status_Text = @"Initialize...";
  2770. [ScanApi open];
  2771. [self addlog:@"ScanApi open"];
  2772. ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
  2773. [self addlog:@"ScanApiConsumer init"];
  2774. // [ScanApi close];
  2775. // [self addlog:@"ScanApi opent"];
  2776. }
  2777. else
  2778. {
  2779. [self addlog:@"Disable"];
  2780. // [ScanApiConsumer invalidate];
  2781. // ScanApiConsumer= nil;
  2782. // [self addlog:@"ScanApiConsumer invalidate"];
  2783. self.api_Status = API_CLOSING;
  2784. #ifdef RA_NOTIFICATION
  2785. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2786. [_eventsFeedback onStatusChanged:@"Stoping..."];
  2787. }
  2788. #else
  2789. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2790. [avc onStatusChanged:@"Stoping..."];
  2791. #endif
  2792. self.Status_Text = @"Stoping...";
  2793. [ScanApi close];
  2794. [self addlog:@"ScanApi close"];
  2795. }
  2796. }
  2797. #pragma mark - Device Info List management
  2798. -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
  2799. [self addlog:@"updateDevicesList:"];
  2800. if(add==YES){
  2801. [self.devices addObject:deviceInfo];
  2802. }
  2803. else{
  2804. [self.devices removeObject:deviceInfo];
  2805. }
  2806. NSMutableString* temp=[[NSMutableString alloc]init];
  2807. for (DeviceInfo* info in self.devices) {
  2808. [temp appendString:[info getName]];
  2809. [temp appendString:@"\n"];
  2810. }
  2811. if(self.devices.count>0)
  2812. [temp appendString:@"ready to scan"];
  2813. else
  2814. [temp appendString:@"Waiting for Scanner..."];
  2815. // _Status.text=temp ;
  2816. [self addlog:temp];
  2817. #ifdef RA_NOTIFICATION
  2818. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2819. [_eventsFeedback onStatusChanged:temp];
  2820. }
  2821. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2822. [_eventsFeedback OnUpdateDevicesList];
  2823. }
  2824. #else
  2825. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2826. [avc onStatusChanged:temp];
  2827. [avc OnUpdateDevicesList];
  2828. #endif
  2829. self.Status_Text = temp;
  2830. // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
  2831. // [self.dev_table reloadData];
  2832. }
  2833. #pragma mark - offline order
  2834. -(void) backup_oc
  2835. {
  2836. }
  2837. -(void) restore_oc
  2838. {
  2839. }
  2840. #ifdef SCANNER_ORDER
  2841. #pragma mark - upload manager
  2842. - (void)saveUploadTasks {
  2843. if(true)
  2844. {
  2845. if(self.uploadManager.arr_queue!=nil)
  2846. {
  2847. [self.uploadManager stopAllTasks];
  2848. }
  2849. [self.uploadManager saveTasks];
  2850. return;
  2851. }
  2852. }
  2853. - (NSMutableArray *)cachedUploadTasks {
  2854. if (!self.user) {
  2855. return nil;
  2856. }
  2857. NSString *path = [[RAUtils appCacheDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_uploadTasks",self.user]];
  2858. NSFileManager *manager = [NSFileManager defaultManager];
  2859. if ([manager fileExistsAtPath:path]) {
  2860. NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
  2861. [manager removeItemAtPath:path error:nil];
  2862. return arr;
  2863. }
  2864. return nil;
  2865. }
  2866. #endif
  2867. #ifdef USE_BLE_SCANNER
  2868. #pragma mark - core bluetooth
  2869. -(void) disconnectDevice
  2870. {
  2871. if(self.peripheral)
  2872. { [self.manager cancelPeripheralConnection:self.peripheral];
  2873. self.peripheral = nil;
  2874. }
  2875. [self setBLEAutoReconnect:false];
  2876. if( self.bAppBTOn ==true)
  2877. [self scanBLE];
  2878. }
  2879. -(void)setBLEAutoReconnect:(bool) bAutoReconnect
  2880. {
  2881. self.bAutoConnect = true;
  2882. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2883. [defaults removeObjectForKey:@"BLE_Name"];
  2884. [defaults removeObjectForKey:@"BLE_UUID"];
  2885. [defaults removeObjectForKey:@"BLE_AutoReconnect"];
  2886. if(bAutoReconnect&&self.peripheral)
  2887. {
  2888. [defaults setValue:self.peripheral.name forKey: @"BLE_Name"];
  2889. [defaults setValue:self.peripheral.identifier.UUIDString forKey: @"BLE_UUID"];
  2890. }
  2891. else
  2892. {
  2893. self.strDeviceName = nil;
  2894. self.strDeviceUUID=nil;
  2895. }
  2896. [defaults setBool:bAutoReconnect forKey:@"BLE_AutoReconnect"];
  2897. [defaults synchronize];
  2898. }
  2899. -(void) enableBLE:(bool) bEnable
  2900. {
  2901. self.bAppBTOn =bEnable;
  2902. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2903. [defaults removeObjectForKey:@"BLE_Enable"];
  2904. [defaults setBool:self.bAppBTOn forKey:@"BLE_Enable"];
  2905. [defaults synchronize];
  2906. if(bEnable)
  2907. [self scanBLE];
  2908. else
  2909. [self stopScanBLE];
  2910. }
  2911. -(void) scanBLE
  2912. {
  2913. switch (self.manager.state) {
  2914. case CBManagerStatePoweredOn:
  2915. {
  2916. [self updateLog:@"Scanning..."];
  2917. [_manager scanForPeripheralsWithServices:/*@[[CBUUID UUIDWithString:@"FFF0"]]*/nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
  2918. // [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @true}];
  2919. }
  2920. break;
  2921. case CBManagerStatePoweredOff:
  2922. [self updateLog:@"Please turn on bluetooth。"];
  2923. break;
  2924. default:
  2925. break;
  2926. }
  2927. }
  2928. -(void) stopScanBLE
  2929. {
  2930. // self.bAppBTOn = false;
  2931. [self.manager stopScan];
  2932. if(self.self.peripheral)
  2933. [self.manager cancelPeripheralConnection:self.peripheral];
  2934. self.nDevices = [NSMutableArray new];
  2935. self.peripheral = nil;
  2936. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2937. [_eventsFeedback OnUpdateDevicesList];
  2938. }
  2939. }
  2940. //检查蓝牙状态
  2941. - (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
  2942. switch (central.state) {
  2943. case CBManagerStatePoweredOn:
  2944. {
  2945. [self updateLog:@"Bluetooth on."];
  2946. self.bBTAuthorize = true;
  2947. if(self.bAppBTOn)
  2948. {
  2949. [_manager scanForPeripheralsWithServices:/*@[[CBUUID UUIDWithString:@"FFF0"]]*/nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
  2950. }
  2951. // [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @true}];
  2952. }
  2953. break;
  2954. case CBManagerStatePoweredOff:
  2955. [self updateLog:@"Bluetooth off."];
  2956. self.bBTAuthorize = true;
  2957. break;
  2958. case CBManagerStateUnauthorized:
  2959. //蓝牙未授权
  2960. // app一定未授权,蓝牙是否开启不知
  2961. [self updateLog:@"Bluetooth Unauthorized."];
  2962. self.bBTAuthorize = false;
  2963. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2964. [_eventsFeedback onStatusChanged:@"Unauthorized"];
  2965. }
  2966. break;
  2967. default:
  2968. break;
  2969. }
  2970. }
  2971. -(void)updateLog:(NSString*) log
  2972. {
  2973. // DebugLog(log);
  2974. //
  2975. // self.strBTLog=[self.strBTLog stringByAppendingString:[log stringByAppendingString:@"\n"]];
  2976. [self addlog:log];
  2977. }
  2978. -(NSString *) NSDataToHex:(NSData *)data {
  2979. // NSUInteger i, len;
  2980. // unsigned char *buf, *bytes;
  2981. //
  2982. // len = data.length;
  2983. // bytes = (unsigned char*)data.bytes;
  2984. // buf = malloc(len*2);
  2985. //
  2986. // for (i=0; i<len; i++) {
  2987. // buf[i*2] = itoh((bytes[i] >> 4) & 0xF);
  2988. // buf[i*2+1] = itoh(bytes[i] & 0xF);
  2989. // }
  2990. //
  2991. // return [[NSString alloc] initWithBytesNoCopy:buf
  2992. // length:len*2
  2993. // encoding:NSASCIIStringEncoding
  2994. // freeWhenDone:YES];
  2995. NSUInteger dataLength = [data length];
  2996. NSMutableString *string = [NSMutableString stringWithCapacity:dataLength*2];
  2997. const unsigned char *dataBytes = [data bytes];
  2998. for (NSInteger idx = 0; idx < dataLength; ++idx) {
  2999. [string appendFormat:@"%02x", dataBytes[idx]];
  3000. }
  3001. return string;
  3002. }
  3003. //查到外设后,停止扫描,连接设备
  3004. -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
  3005. {
  3006. // DebugLog(@"didDiscoverPeripheral");
  3007. NSArray* pservice = advertisementData[@"kCBAdvDataServiceUUIDs"];
  3008. if(pservice.count<=0)
  3009. return;
  3010. if(peripheral.name.length<=0)
  3011. return;
  3012. // _peripheral = peripheral;
  3013. // [_manager connectPeripheral:_peripheral options:nil];
  3014. // [self.manager stopScan];
  3015. // [_activity stopAnimating];
  3016. BOOL replace = NO;
  3017. // Match if we have this device from before
  3018. for (int i=0; i < _nDevices.count; i++) {
  3019. CBPeripheral *p = [_nDevices objectAtIndex:i];
  3020. if ([p isEqual:peripheral]) {
  3021. [_nDevices replaceObjectAtIndex:i withObject:peripheral];
  3022. replace = YES;
  3023. }
  3024. }
  3025. if (!replace) {
  3026. [_nDevices addObject:peripheral];
  3027. [self updateLog:[NSString stringWithFormat:@"Found device: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.identifier, advertisementData]];
  3028. // advertisementData[@"kCBAdvDataManufacturerData"];
  3029. // NSString* a=[[NSString alloc] initWithData:advertisementData[@"kCBAdvDataManufacturerData"] encoding:NSASCIIStringEncoding];
  3030. // NSString* b=[[NSString alloc] initWithData:advertisementData[@"kCBAdvDataManufacturerData"] encoding:NSUTF8StringEncoding];
  3031. // NSString* d = [self NSDataToHex:advertisementData[@"kCBAdvDataManufacturerData"]];
  3032. // int c=0;
  3033. }
  3034. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  3035. [_eventsFeedback OnUpdateDevicesList];
  3036. }
  3037. if(self.bAutoConnect&& [self.strDeviceUUID isEqualToString:peripheral.identifier.UUIDString])
  3038. {
  3039. self.peripheral = peripheral;
  3040. NSString* log = [NSString stringWithFormat:@"Reconnect to device %@ ...", peripheral.name];
  3041. [self updateLog:log];
  3042. DebugLog(@"Retrying");
  3043. [self.manager connectPeripheral:peripheral options:nil];
  3044. }
  3045. // if(peripheral.identifier == self.peripheral.identifier)
  3046. // {
  3047. // //重新连接
  3048. // [_manager connectPeripheral:_peripheral options:nil];
  3049. // }
  3050. //[_bluetoothTable reloadData];
  3051. }
  3052. //连接外设成功,开始发现服务
  3053. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
  3054. DebugLog(@"%@", [NSString stringWithFormat:@"成功连接 peripheral: %@ with UUID: %@",peripheral,peripheral.identifier]);
  3055. [self updateLog:[NSString stringWithFormat:@"Connect peripheral: %@ with UUID: %@",peripheral,peripheral.identifier]];
  3056. [self.peripheral setDelegate:self];
  3057. [self.peripheral discoverServices:nil];
  3058. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  3059. [_eventsFeedback onStatusChanged:@"Connected"];
  3060. }
  3061. // [self updateLog:@"扫描服务"];
  3062. }
  3063. //连接外设失败
  3064. -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  3065. {
  3066. DebugLog(@"%@",error);
  3067. [self updateLog:@"Failed to connect device."];
  3068. }
  3069. - (void)peripheral:(CBPeripheral *)peripheral
  3070. didReadRSSI:(NSNumber *)RSSI
  3071. error:(NSError *)error
  3072. {
  3073. DebugLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral);
  3074. int rssi = abs([RSSI intValue]);
  3075. CGFloat ci = (rssi - 49) / (10 * 4.);
  3076. NSString *length = [NSString stringWithFormat:@"Found hotpoint:%@,distence:%.1fm",_peripheral,pow(10,ci)];
  3077. [self updateLog:[NSString stringWithFormat:@"Distence:%@", length]];
  3078. }
  3079. //
  3080. //
  3081. //-(void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
  3082. //{
  3083. // DebugLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral);
  3084. // int rssi = abs([peripheral.RSSI intValue]);
  3085. // CGFloat ci = (rssi - 49) / (10 * 4.);
  3086. // NSString *length = [NSString stringWithFormat:@"Found hotpoint:%@,distence:%.1fm",_peripheral,pow(10,ci)];
  3087. // [self updateLog:[NSString stringWithFormat:@"Distence:%@", length]];
  3088. //}
  3089. //已发现服务
  3090. -(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
  3091. [self updateLog:@"Found service."];
  3092. int i=0;
  3093. for (CBService *s in peripheral.services) {
  3094. [self.nServices addObject:s];
  3095. }
  3096. for (CBService *s in peripheral.services) {
  3097. [self updateLog:[NSString stringWithFormat:@"%d :service UUID: %@(%@)",i,s.UUID.data,s.UUID]];
  3098. i++;
  3099. [peripheral discoverCharacteristics:nil forService:s];
  3100. // if ([s.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]])
  3101. // {
  3102. // BOOL replace = NO;
  3103. // // Match if we have this device from before
  3104. // for (int i=0; i < _nDevices.count; i++) {
  3105. // CBPeripheral *p = [_nDevices objectAtIndex:i];
  3106. // if ([p isEqual:peripheral]) {
  3107. // [_nDevices replaceObjectAtIndex:i withObject:peripheral];
  3108. // replace = YES;
  3109. // }
  3110. // }
  3111. // if (!replace) {
  3112. // [_nDevices addObject:peripheral];
  3113. //// [_bluetoothTable reloadData];
  3114. // }
  3115. // }
  3116. }
  3117. }
  3118. //已搜索到Characteristics
  3119. -(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
  3120. [self updateLog:[NSString stringWithFormat:@"service:%@ (%@)",service.UUID.data ,service.UUID]];
  3121. for (CBCharacteristic *c in service.characteristics)
  3122. {
  3123. [self updateLog:[NSString stringWithFormat:@"Characteristic UUID: %@ (%@)",c.UUID.data,c.UUID]];
  3124. if(c.properties& CBCharacteristicPropertyWrite) //写
  3125. // if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]])
  3126. {
  3127. _writeCharacteristic = c;
  3128. }
  3129. if (c.properties&CBCharacteristicPropertyNotify) // 通知
  3130. // if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]])
  3131. {
  3132. [_peripheral readValueForCharacteristic:c];
  3133. [_peripheral setNotifyValue:YES forCharacteristic:c];
  3134. }
  3135. }
  3136. }
  3137. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
  3138. if(error)
  3139. DebugLog(@"!Disconnect %ld %@",error.code,[error localizedDescription]);
  3140. [self updateLog:[NSString stringWithFormat:@"Disconnect device:[%@]", peripheral.name]];
  3141. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  3142. [_eventsFeedback onStatusChanged:@"Disconnected"];
  3143. }
  3144. if ([self.peripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
  3145. [self updateLog:@"Retrying..."];
  3146. DebugLog(@"Retrying");
  3147. [self.manager connectPeripheral:peripheral options:nil];
  3148. }
  3149. }
  3150. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  3151. {
  3152. DebugLog(@"didUpdateValueForCharacteristic from Characteristic %@",characteristic.UUID);
  3153. NSData * data = characteristic.value;
  3154. if(data==nil)
  3155. {
  3156. DebugLog(@"Scan Data is empty");
  3157. return;
  3158. }
  3159. NSString *datastring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  3160. // NSString *datastring1 = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
  3161. // NSString *datastring2 = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
  3162. // NSString *datastring3 = [[NSString alloc] initWithData:data encoding:NSUTF32StringEncoding];
  3163. //
  3164. // = 1, /* 0..127 only */
  3165. // NSNEXTSTEPStringEncoding = 2,
  3166. // NSJapaneseEUCStringEncoding = 3,
  3167. //
  3168. // NSISOLatin1StringEncoding = 5,
  3169. // NSSymbolStringEncoding = 6,
  3170. // NSNonLossyASCIIStringEncoding = 7,
  3171. // NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
  3172. // NSISOLatin2StringEncoding = 9,
  3173. // NSUnicodeStringEncoding = 10,
  3174. // NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
  3175. // NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
  3176. // NSWindowsCP1253StringEncoding = 13, /* Greek */
  3177. // NSWindowsCP1254StringEncoding = 14, /* Turkish */
  3178. // NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
  3179. // NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
  3180. // NSMacOSRomanStringEncoding = 30,
  3181. //
  3182. // /* An alias for NSUnicodeStringEncoding */
  3183. //
  3184. // NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
  3185. // NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
  3186. //
  3187. // NSUTF32StringEncoding = 0x8c000100,
  3188. // NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
  3189. // NSUTF32LittleEndianStringEncoding = 0x9c000100
  3190. //
  3191. datastring = [datastring stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  3192. if(datastring.length==0)
  3193. {
  3194. DebugLog(@"Scan Data is empty");
  3195. return;
  3196. }
  3197. else
  3198. DebugLog(@"Scan value %@",datastring);
  3199. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  3200. [_eventsFeedback onDecodedData:datastring];
  3201. }
  3202. [self addlog:datastring];
  3203. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF02"]]) {
  3204. // NSData * data = characteristic.value;
  3205. // Byte * resultByte = (Byte *)[data bytes];
  3206. // for(int i=0;i<[data length];i++)
  3207. // printf("testByteFF02[%d] = %d\n",i,resultByte[i]);
  3208. // if (resultByte[1] == 0) {
  3209. // }else if (resultByte[1] == 1) {
  3210. // [self updateLog:@"未知错误"];
  3211. // }else if (resultByte[1] == 2) {
  3212. // [self updateLog:@"鉴权失败"];
  3213. // }
  3214. // }
  3215. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF04"]]) {
  3216. // NSData * data = characteristic.value;
  3217. // Byte * resultByte = (Byte *)[data bytes];
  3218. // for(int i=0;i<[data length];i++)
  3219. // printf("testByteFF04[%d] = %d\n",i,resultByte[i]);}
  3220. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF05"]]) {
  3221. // NSData * data = characteristic.value;
  3222. // Byte * resultByte = (Byte *)[data bytes];
  3223. // for(int i=0;i<[data length];i++)
  3224. // printf("testByteFF05[%d] = %d\n",i,resultByte[i]);
  3225. // if (resultByte[0] == 0) {
  3226. // // 设备加解锁状态 0 撤防 1 设防
  3227. // [self updateLog:@"当前车辆撤防状态"];
  3228. // }else if (resultByte[0] == 1) {
  3229. // // 设备加解锁状态 0 撤防 1 设防
  3230. // [self updateLog:@"当前车辆设防状态"];
  3231. // }
  3232. // }
  3233. }
  3234. //中心读取外设实时数据
  3235. - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
  3236. if (error) {
  3237. DebugLog(@"Error changing notification state: %@", error.localizedDescription);
  3238. [self updateLog:[NSString stringWithFormat:@"Error changing notification state: %@. Disconnect", error.localizedDescription]];
  3239. // [self.manager cancelPeripheralConnection:self.peripheral];
  3240. }
  3241. // Notification has started
  3242. if (characteristic.isNotifying) {
  3243. [peripheral readValueForCharacteristic:characteristic];
  3244. } else { // Notification has stopped
  3245. // so disconnect from the peripheral
  3246. DebugLog(@"Notification stopped on %@. Disconnecting", characteristic);
  3247. [self updateLog:[NSString stringWithFormat:@"Notification stopped on %@. Disconnecting", characteristic]];
  3248. // [self.manager cancelPeripheralConnection:self.peripheral];
  3249. [self disconnectDevice];
  3250. }
  3251. }
  3252. //用于检测中心向外设写数据是否成功
  3253. -(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  3254. {
  3255. if (error) {
  3256. DebugLog(@"=======%@",error.userInfo);
  3257. [self updateLog:[RAConvertor dict2string:error.userInfo]];
  3258. }else{
  3259. DebugLog(@"发送数据成功");
  3260. [self updateLog:@"Send data."];
  3261. }
  3262. /* When a write occurs, need to set off a re-read of the local CBCharacteristic to update its value */
  3263. [peripheral readValueForCharacteristic:characteristic];
  3264. }
  3265. #endif
  3266. //
  3267. ////#parammark tableview
  3268. //
  3269. //- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  3270. // return self.nDevices.count;
  3271. //}
  3272. //
  3273. //- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  3274. // static NSString *CellIdentifier = @"Cell";
  3275. // // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  3276. // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  3277. // if (!cell) {
  3278. // cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  3279. // }
  3280. //
  3281. // CBPeripheral *p=self.nDevices[indexPath.item];
  3282. // NSString* name = p.name;
  3283. // if(name.length==0)
  3284. // name=@"NO Name";
  3285. // cell.textLabel.text = name;
  3286. //
  3287. // return cell;
  3288. //}
  3289. //-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3290. //{
  3291. // CBPeripheral *p=self.nDevices[indexPath.item];
  3292. //
  3293. // _peripheral = p;
  3294. // [_manager connectPeripheral:_peripheral options:nil];
  3295. //}
  3296. #pragma mark new_download
  3297. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
  3298. if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
  3299. if(/*[challenge.protectionSpace.host isEqualToString:@"96.75.188.41"]*/ true){
  3300. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  3301. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  3302. }
  3303. }
  3304. }
  3305. -(void)handle_download1:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  3306. {
  3307. //操作有两种,start stop;
  3308. //结果有四种, wait , downloading, pause, finish
  3309. dispatch_async(dispatch_get_main_queue(), ^{
  3310. // debug;
  3311. // NSString* file_name=[url lastPathComponent];
  3312. //暂停<->开始转换
  3313. // bool isdownloading = [self isdownloading:file_name];
  3314. if (start)
  3315. {//开始下载
  3316. DebugLog(@"%d start",taskidx);
  3317. self.current_task=taskidx;
  3318. // NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  3319. //
  3320. // // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  3321. // //
  3322. // //
  3323. // // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  3324. // //
  3325. // // //设置请求头(GET)
  3326. // // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  3327. // // [request setValue:range forHTTPHeaderField:@"Range"];
  3328. // //
  3329. // // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  3330. //
  3331. //
  3332. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  3333. //
  3334. // //设置请求头(GET)
  3335. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  3336. // [request setValue:range forHTTPHeaderField:@"Range"];
  3337. //
  3338. // RANetworkTaskDelegate *delegate = [RANetworkTaskDelegate sharedInstance];
  3339. NSURLSession *session = nil;
  3340. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  3341. config.timeoutIntervalForRequest = JSON_TIMEOUT;
  3342. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  3343. session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:queue];
  3344. NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  3345. req.HTTPMethod = @"GET";
  3346. // long offset = [self getcurrentLength:taskidx];
  3347. // if (offset > 0) {
  3348. // [req addValue:[NSString stringWithFormat:@"bytes=%ld-",(unsigned long)offset] forHTTPHeaderField:@"Range"];
  3349. // }
  3350. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  3351. [req setValue:range forHTTPHeaderField:@"Range"];
  3352. NSURLSessionDataTask *downloadTask = [session dataTaskWithRequest:req];
  3353. [downloadTask resume];
  3354. self.session =session;
  3355. self.curr_task = downloadTask;
  3356. }else{ //暂停
  3357. DebugLog(@"%d pause",taskidx);
  3358. [self.curr_task cancel];
  3359. self.curr_task = nil;
  3360. // [self.connection cancel];
  3361. // self.connection = nil;
  3362. }
  3363. });
  3364. }
  3365. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
  3366. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  3367. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  3368. DebugLog(@"%d begin",self.current_task);
  3369. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  3370. //获取下载文件大小
  3371. // self.fileLength = response.expectedContentLength;
  3372. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  3373. //获取文件名
  3374. //self.fileName = response.suggestedFilename;
  3375. currenttask[@"fileName"] = response.suggestedFilename;
  3376. currenttask[@"response"] = @"true";
  3377. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  3378. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  3379. //文件路径
  3380. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  3381. NSString * ver = self.download_task[@"ver"];
  3382. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  3383. NSString *filePath = [temp stringByAppendingPathComponent:location];
  3384. DebugLog(@"save to: %@",filePath);
  3385. if (position>0) {
  3386. //不需要创建文件;
  3387. //创建一个用来写数据的文件句柄
  3388. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  3389. return;
  3390. }
  3391. // 第一次获取的才是文件正确大小
  3392. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  3393. //创建一个空的文件到沙盒
  3394. NSFileManager *fileManager = [NSFileManager defaultManager];
  3395. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  3396. //创建一个用来写数据的文件句柄
  3397. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  3398. }else{
  3399. //debug 这里缺少文件的情况还没处理
  3400. [self.connection cancel];
  3401. self.connection = nil;
  3402. DebugLog(@"该文件不存在");
  3403. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
  3404. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  3405. [self add_downloadlog:str_status];
  3406. }
  3407. completionHandler(NSURLSessionResponseAllow);
  3408. }
  3409. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
  3410. //移动到文件末尾
  3411. [self.fileHandle seekToEndOfFile];
  3412. //写入数据到文件
  3413. [self.fileHandle writeData:data];
  3414. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  3415. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  3416. position += data.length;
  3417. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  3418. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  3419. //更新画面中的进度
  3420. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  3421. double progress = (double)position/fileLength;
  3422. self.file_progress = progress;
  3423. [self.settingUI onProgressUpdate];
  3424. }
  3425. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
  3426. // double progress = (double)totalBytesSent / totalBytesExpectedToSend;
  3427. }
  3428. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
  3429. // if (self.decryptHandler) {
  3430. //
  3431. // self.result.decryptHandler = self.decryptHandler;
  3432. //
  3433. // }
  3434. //
  3435. // if (error) {
  3436. //
  3437. // self.result.error = error;
  3438. //
  3439. // DebugLog(@"Delegate recv Error: %@",error.localizedDescription);
  3440. //
  3441. // }
  3442. //
  3443. // self.result.data = self.recvData;
  3444. //
  3445. // DebugLog(@"Delegate recv data %@",self.recvData);
  3446. //
  3447. //
  3448. //
  3449. if (error) {
  3450. DebugLog(@"%d error message:%@",self.current_task,error);
  3451. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  3452. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  3453. currenttask[@"status"] = @"pause";
  3454. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  3455. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  3456. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  3457. // self.currentLength = 0;
  3458. // self.fileLength = 0;
  3459. [self.fileHandle closeFile];
  3460. self.fileHandle = nil;
  3461. [self.connection cancel];
  3462. self.connection = nil;
  3463. [self download_offline:true checkdiskspace:false];
  3464. } else {
  3465. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  3466. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  3467. DebugLog(@"%d finish",self.current_task);
  3468. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  3469. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  3470. // self.currentLength = 0;
  3471. // self.fileLength = 0;
  3472. [self.fileHandle closeFile];
  3473. self.fileHandle = nil;
  3474. int result=[self unpack];
  3475. NSString* temp = NSTemporaryDirectory();
  3476. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  3477. NSString * ver = self.download_task[@"ver"];
  3478. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  3479. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  3480. switch (result) {
  3481. case UNZIP_FILE_DAMAGE:
  3482. {
  3483. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  3484. currenttask[@"status"] = @"pause";
  3485. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  3486. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  3487. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  3488. // self.currentLength = 0;
  3489. // self.fileLength = 0;
  3490. [self.fileHandle closeFile];
  3491. self.fileHandle = nil;
  3492. [self.connection cancel];
  3493. self.connection = nil;
  3494. break;
  3495. }
  3496. case UNZIP_SUCCESS:
  3497. {
  3498. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  3499. if([type isEqualToString:@"img"])
  3500. {
  3501. NSString* parent_path = self.download_task[@"path"];
  3502. if(parent_path.length==0)
  3503. parent_path=@"";
  3504. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  3505. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  3506. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  3507. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  3508. BOOL bdir=YES;
  3509. NSError *error = nil;
  3510. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  3511. {
  3512. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  3513. if(!bsuccess)
  3514. DebugLog(@"Create temp folder failed");
  3515. }
  3516. error=nil;
  3517. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  3518. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  3519. // NSError *error = nil;
  3520. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  3521. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  3522. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  3523. // backupItemName:backup
  3524. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  3525. // resultingItemURL:nil error:&error])
  3526. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  3527. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  3528. {
  3529. DebugLog(@"move image folder failed");
  3530. }
  3531. else
  3532. {
  3533. currenttask[@"status"] = @"finish";
  3534. DebugLog(@"move image folder successful");
  3535. }
  3536. }
  3537. else if([type isEqualToString:@"sql"])
  3538. {
  3539. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  3540. NSString * ver = self.download_task[@"ver"];
  3541. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  3542. tempdb=[temp stringByAppendingPathComponent:tempdb];
  3543. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  3544. [self add_downloadlog:@"updating local database..."];
  3545. @try {
  3546. char *errmsg=NULL;
  3547. // [iSalesDB disable_trigger]
  3548. [iSalesDB disable_trigger];
  3549. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  3550. {
  3551. 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;drop trigger if exists offline_pdf;", NULL, NULL, &errmsg);
  3552. sqlite3_free(errmsg);
  3553. DebugLog(@"开启事务");
  3554. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  3555. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  3556. int count = [orderjson[@"count"] intValue];
  3557. for(int i=0;i<count;i++)
  3558. {
  3559. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  3560. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  3561. NSError *error = nil;
  3562. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  3563. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  3564. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  3565. {
  3566. //throw exception;
  3567. if(errmsg==nil)
  3568. errmsg="Unknown error.";
  3569. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  3570. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  3571. }
  3572. sqlite3_free(errmsg);
  3573. }
  3574. 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);
  3575. }
  3576. //提交事务
  3577. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  3578. DebugLog(@"提交事务");
  3579. sqlite3_free(errmsg);
  3580. }
  3581. [self add_downloadlog:@"updating local database successful"];
  3582. currenttask[@"status"] = @"finish";
  3583. }
  3584. @catch (NSException *exception) {
  3585. char *errmsg=NULL;
  3586. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  3587. [self add_downloadlog:@"updating local database failed rollback..."];
  3588. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  3589. DebugLog(@"回滚事务");
  3590. }
  3591. else
  3592. {
  3593. [self add_downloadlog:@"rollback failed."];
  3594. }
  3595. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  3596. currenttask[@"status"] = @"pause";
  3597. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  3598. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  3599. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  3600. // self.currentLength = 0;
  3601. // self.fileLength = 0;
  3602. [self.fileHandle closeFile];
  3603. self.fileHandle = nil;
  3604. [self.connection cancel];
  3605. self.connection = nil;
  3606. //break;
  3607. }
  3608. @finally {
  3609. // [iSalesDB enable_trigger]
  3610. [iSalesDB enable_trigger];
  3611. sqlite3_close(tdb);
  3612. // [iSalesDB close_db:tdb];
  3613. // [self SelectData];
  3614. }
  3615. }
  3616. else if([type isEqualToString:@"script"])
  3617. {
  3618. currenttask[@"status"] = @"finish";
  3619. }
  3620. else if([type isEqualToString:@"resource"])
  3621. {
  3622. currenttask[@"status"] = @"finish";
  3623. }
  3624. // debug
  3625. // int c=self.current_task+1;
  3626. // double t=[ self.download_task[@"count"] doubleValue];
  3627. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  3628. self.overall_progress = oprogress;
  3629. [self.settingUI onProgressUpdate];
  3630. break;
  3631. }
  3632. case UNZIP_NO_SPACE:
  3633. {
  3634. [self add_downloadlog:@"Disk space not enough."];
  3635. break;
  3636. }
  3637. case UNZIP_OPEN_FAILED:
  3638. {
  3639. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  3640. break;
  3641. }
  3642. default:
  3643. break;
  3644. }
  3645. [self download_offline:true checkdiskspace:false];
  3646. }
  3647. printf("net work complete\n");
  3648. //
  3649. [session invalidateAndCancel];
  3650. }
  3651. @end