CCMain.m 253 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import <OCCommunicationLib/OCActivity.h>
  29. #import <OCCommunicationLib/OCNotifications.h>
  30. #import <OCCommunicationLib/OCNotificationsAction.h>
  31. #import <OCCommunicationLib/OCFrameworkConstants.h>
  32. #import <OCCommunicationLib/OCCapabilities.h>
  33. #import "CTAssetCheckmark.h"
  34. #ifdef CUSTOM_BUILD
  35. #import "CustomSwift.h"
  36. #else
  37. #import "Nextcloud-Swift.h"
  38. #endif
  39. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  40. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  41. #define alertCreateFolder 1
  42. #define alertCreateFolderCrypto 2
  43. #define alertRename 3
  44. #define alertOfflineFolder 4
  45. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  46. {
  47. CCMetadata *_metadata;
  48. BOOL _isRoot;
  49. BOOL _isViewDidLoad;
  50. BOOL _isOfflineServerUrl;
  51. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  52. BOOL _isSelectedMode;
  53. NSMutableArray *_selectedMetadatas;
  54. NSMutableArray *_queueSelector;
  55. NSUInteger _numSelectedMetadatas;
  56. UIImageView *_ImageTitleHomeCryptoCloud;
  57. UIView *_reMenuBackgroundView;
  58. UITapGestureRecognizer *_singleFingerTap;
  59. NSString *_directoryGroupBy;
  60. NSString *_directoryOrder;
  61. NSUInteger _failedAttempts;
  62. NSDate *_lockUntilDate;
  63. NSString *_fatherPermission;
  64. UIRefreshControl *_refreshControl;
  65. UIDocumentInteractionController *_docController;
  66. CCHud *_hud;
  67. CCHud *_hudDeterminate;
  68. // Datasource
  69. CCSectionDataSourceMetadata *_sectionDataSource;
  70. NSDate *_dateReadDataSource;
  71. // Search
  72. BOOL _isSearchMode;
  73. NSString *_searchFileName;
  74. NSMutableArray *_searchResultMetadatas;
  75. NSString *_depth;
  76. NSString *_noFilesSearchTitle;
  77. NSString *_noFilesSearchDescription;
  78. // Login
  79. CCLoginWeb *_loginWeb;
  80. CCLogin *_loginVC;
  81. }
  82. @end
  83. @implementation CCMain
  84. #pragma --------------------------------------------------------------------------------------------
  85. #pragma mark ===== Init =====
  86. #pragma --------------------------------------------------------------------------------------------
  87. - (id)initWithCoder:(NSCoder *)aDecoder
  88. {
  89. if (self = [super initWithCoder:aDecoder]) {
  90. _directoryOrder = [CCUtility getOrderSettings];
  91. _directoryGroupBy = [CCUtility getGroupBySettings];
  92. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  93. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  94. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  95. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  96. }
  97. return self;
  98. }
  99. #pragma --------------------------------------------------------------------------------------------
  100. #pragma mark ===== View =====
  101. #pragma --------------------------------------------------------------------------------------------
  102. - (void)viewDidLoad
  103. {
  104. [super viewDidLoad];
  105. // init object
  106. _metadata = [CCMetadata new];
  107. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  108. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  109. _selectedMetadatas = [NSMutableArray new];
  110. _queueSelector = [NSMutableArray new];
  111. _isViewDidLoad = YES;
  112. _fatherPermission = @"";
  113. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  114. _searchResultMetadatas = [NSMutableArray new];
  115. _searchFileName = @"";
  116. _depth = @"0";
  117. _noFilesSearchTitle = @"";
  118. _noFilesSearchDescription = @"";
  119. // delegate
  120. self.tableView.delegate = self;
  121. self.tableView.tableFooterView = [UIView new];
  122. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  123. self.tableView.emptyDataSetDelegate = self;
  124. self.tableView.emptyDataSetSource = self;
  125. self.searchController.delegate = self;
  126. self.searchController.searchBar.delegate = self;
  127. [[CCNetworking sharedNetworking] settingDelegate:self];
  128. // Custom Cell
  129. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  130. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  131. // long press recognizer TableView
  132. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  133. [self.tableView addGestureRecognizer:longPressRecognizer];
  134. // Pull-to-Refresh
  135. [self createRefreshControl];
  136. // Register for 3D Touch Previewing if available
  137. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  138. {
  139. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  140. }
  141. // Back Button
  142. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  143. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogo] style:UIBarButtonItemStylePlain target:nil action:nil];
  144. // reMenu Background
  145. _reMenuBackgroundView = [[UIView alloc] init];
  146. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  147. // if this is not Main (the Main uses inizializeMain)
  148. if (_isRoot == NO && app.activeAccount.length > 0) {
  149. // Settings this folder & delegate & Loading datasource
  150. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  151. // Load Datasource
  152. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  153. // Read Folder
  154. [self readFolderWithForced:NO serverUrl:_serverUrl];
  155. }
  156. // Version Server
  157. app.serverVersion = [CCCoreData getServerVersionMajorActiveAccount:app.activeAccount];
  158. // Title
  159. [self setTitle];
  160. // Search
  161. self.definesPresentationContext = YES;
  162. self.searchController.searchResultsUpdater = self;
  163. self.searchController.dimsBackgroundDuringPresentation = NO;
  164. self.tableView.tableHeaderView = self.searchController.searchBar;
  165. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  166. [self.searchController.searchBar sizeToFit];
  167. self.searchController.searchBar.delegate = self;
  168. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  169. if (app.serverVersion >= 12) {
  170. if (_isRoot)
  171. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  172. else
  173. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  174. } else {
  175. self.searchController.searchBar.scopeButtonTitles = nil;
  176. }
  177. // Hide Search Filed on Load
  178. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  179. }
  180. // Apparirà
  181. - (void)viewWillAppear:(BOOL)animated
  182. {
  183. [super viewWillAppear:animated];
  184. // test
  185. if (app.activeAccount.length == 0)
  186. return;
  187. // Settings this folder & delegate & Loading datasource
  188. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  189. [[CCNetworking sharedNetworking] settingDelegate:self];
  190. // Color
  191. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  192. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  193. // Menu e Bar
  194. [self createReMainMenu];
  195. [self createReSelectMenu];
  196. if (_isSelectedMode)
  197. [self setUINavigationBarSelected];
  198. else
  199. [self setUINavigationBarDefault];
  200. // Plus Button
  201. [app plusButtonVisibile:true];
  202. }
  203. // E' arrivato
  204. - (void)viewDidAppear:(BOOL)animated
  205. {
  206. [super viewDidAppear:animated];
  207. // Active Main
  208. app.activeMain = self;
  209. // Test viewDidLoad
  210. if (_isViewDidLoad) {
  211. _isViewDidLoad = NO;
  212. } else {
  213. if (app.activeAccount.length > 0) {
  214. // Load Datasource
  215. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  216. // Read Folder
  217. [self readFolderWithForced:NO serverUrl:_serverUrl];
  218. }
  219. }
  220. // Title
  221. [self setTitle];
  222. }
  223. - (void)viewWillDisappear:(BOOL)animated
  224. {
  225. [super viewWillDisappear:animated];
  226. [self closeAllMenu];
  227. }
  228. - (void)didReceiveMemoryWarning
  229. {
  230. [super didReceiveMemoryWarning];
  231. // Dispose of any resources that can be recreated.
  232. }
  233. - (BOOL)prefersStatusBarHidden
  234. {
  235. return NO;
  236. }
  237. // detect scroll for remove keyboard in search mode
  238. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  239. {
  240. if (_isSearchMode && scrollView == self.tableView) {
  241. [self.searchController.searchBar endEditing:YES];
  242. }
  243. }
  244. #pragma --------------------------------------------------------------------------------------------
  245. #pragma mark ===== Initizlize Mail =====
  246. #pragma --------------------------------------------------------------------------------------------
  247. - (void)initializeMain:(NSNotification *)notification
  248. {
  249. _directoryGroupBy = nil;
  250. _directoryOrder = nil;
  251. _dateReadDataSource = nil;
  252. // test
  253. if (app.activeAccount.length == 0)
  254. return;
  255. if ([app.listMainVC count] == 0 || _isRoot) {
  256. // This is Root
  257. _isRoot = YES;
  258. // Crypto Mode
  259. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  260. app.isCryptoCloudMode = NO;
  261. } else {
  262. app.isCryptoCloudMode = YES;
  263. }
  264. // go Home
  265. [self.navigationController popToRootViewControllerAnimated:NO];
  266. // Remove search mode
  267. [self cancelSearchBar];
  268. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  269. _isFolderEncrypted = NO;
  270. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  271. // add list
  272. [app.listMainVC setObject:self forKey:_serverUrl];
  273. // setting Networking
  274. [[CCNetworking sharedNetworking] settingDelegate:self];
  275. [[CCNetworking sharedNetworking] settingAccount];
  276. // populate shared Link & User variable
  277. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  278. // Load Datasource
  279. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  280. // Load Folder
  281. [self readFolderWithForced:NO serverUrl:_serverUrl];
  282. // Load photo datasorce
  283. if (app.activePhotosCameraUpload)
  284. [app.activePhotosCameraUpload reloadDatasourceForced];
  285. // remove all of detail
  286. if (app.activeDetail)
  287. [app.activeDetail removeAllView];
  288. // remove all Notification Messages
  289. [app.listOfNotifications removeAllObjects];
  290. // home main
  291. app.homeMain = self;
  292. // Initializations
  293. [app applicationInitialized];
  294. } else {
  295. // reload datasource
  296. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  297. }
  298. }
  299. #pragma --------------------------------------------------------------------------------------------
  300. #pragma mark ==== DZNEmptyDataSetSource ====
  301. #pragma --------------------------------------------------------------------------------------------
  302. /*
  303. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  304. {
  305. if(_isSearchMode)
  306. return NO;
  307. else
  308. return YES;
  309. }
  310. */
  311. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  312. {
  313. return YES;
  314. }
  315. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  316. {
  317. return [UIColor whiteColor];
  318. }
  319. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. if (_isSearchMode)
  322. return [UIImage imageNamed:image_searchBig];
  323. else
  324. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_filesNoFiles] color:app.themingColor];
  325. }
  326. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. NSString *text;
  329. if (_isSearchMode)
  330. text = _noFilesSearchTitle;
  331. else
  332. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  333. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  334. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  335. }
  336. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  337. {
  338. NSString *text;
  339. if (_isSearchMode)
  340. text = _noFilesSearchDescription;
  341. else
  342. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  343. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  344. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  345. paragraph.alignment = NSTextAlignmentCenter;
  346. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  347. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  348. }
  349. #pragma --------------------------------------------------------------------------------------------
  350. #pragma mark ===== AlertView =====
  351. #pragma --------------------------------------------------------------------------------------------
  352. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  353. {
  354. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  355. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  356. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  357. if (alertView.tag == alertRename && buttonIndex == 1) {
  358. if ([_metadata.model isEqualToString:@"note"]) {
  359. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  360. } else {
  361. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  362. }
  363. }
  364. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  365. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  366. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  367. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  368. [self performSelector:@selector(reloadDatasource) withObject:nil];
  369. }
  370. }
  371. // accept only number char > 0
  372. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  373. {
  374. /* Retrieve a text field at an index -
  375. raises NSRangeException when textFieldIndex is out-of-bounds.
  376. The field at index 0 will be the first text field
  377. (the single field or the login field),
  378. The field at index 1 will be the password field. */
  379. /*
  380. 1> Get the Text Field in alertview
  381. 2> Get the text of that Text Field
  382. 3> Verify that text length
  383. 4> return YES or NO Based on the length
  384. */
  385. if (alertView.tag == alertOfflineFolder) return YES;
  386. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ===== Graphic Window =====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)createRefreshControl
  392. {
  393. _refreshControl = [UIRefreshControl new];
  394. _refreshControl.tintColor = [NCBrandColor sharedInstance].refreshControl;
  395. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  396. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  397. [self setRefreshControl:_refreshControl];
  398. }
  399. - (void)deleteRefreshControl
  400. {
  401. [_refreshControl endRefreshing];
  402. self.refreshControl = nil;
  403. }
  404. - (void)refreshControlTarget
  405. {
  406. [self readFolderWithForced:YES serverUrl:_serverUrl];
  407. // Actuate `Peek` feedback (weak boom)
  408. AudioServicesPlaySystemSound(1519);
  409. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  410. }
  411. - (void)setTitle
  412. {
  413. // Color text self.navigationItem.title
  414. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  415. if (_isSelectedMode) {
  416. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  417. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  418. self.navigationItem.titleView = nil;
  419. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  420. } else {
  421. // we are in home : LOGO BRAND
  422. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  423. self.navigationItem.title = nil;
  424. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogoOffline]];
  425. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogo]];
  426. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  427. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  428. [singleTap setNumberOfTapsRequired:1];
  429. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  430. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  431. } else {
  432. self.navigationItem.title = _titleMain;
  433. }
  434. }
  435. }
  436. - (void)setUINavigationBarDefault
  437. {
  438. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  439. UIBarButtonItem *buttonMore, *buttonNotification;
  440. // =
  441. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_navigationControllerMenu] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  442. buttonMore.enabled = true;
  443. // <
  444. self.navigationController.navigationBar.hidden = NO;
  445. // Notification
  446. if ([app.listOfNotifications count] > 0) {
  447. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  448. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  449. buttonNotification.enabled = true;
  450. }
  451. if (buttonNotification)
  452. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  453. else
  454. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  455. self.navigationItem.leftBarButtonItem = nil;
  456. }
  457. - (void)setUINavigationBarSelected
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  460. UIImage *icon = [UIImage imageNamed:image_navigationControllerMenu];
  461. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  462. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  463. self.navigationItem.leftBarButtonItem = leftButton;
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. }
  466. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  467. {
  468. [self closeAllMenu];
  469. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  470. }];
  471. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  472. }
  473. - (void)cancelSelect
  474. {
  475. [self tableViewSelect:NO];
  476. }
  477. - (void)closeAllMenu
  478. {
  479. // close Menu
  480. [app.reSelectMenu close];
  481. [app.reMainMenu close];
  482. // Close Menu Logo
  483. [CCMenuAccount dismissMenu];
  484. }
  485. #pragma --------------------------------------------------------------------------------------------
  486. #pragma mark ===== Document Picker =====
  487. #pragma --------------------------------------------------------------------------------------------
  488. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  489. {
  490. NSLog(@"Cancelled");
  491. }
  492. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  493. {
  494. NSLog(@"Cancelled");
  495. }
  496. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  497. {
  498. documentPicker.delegate = self;
  499. [self presentViewController:documentPicker animated:YES completion:nil];
  500. }
  501. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  502. {
  503. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  504. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  505. __block NSError *error;
  506. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  507. NSString *fileName = [url lastPathComponent];
  508. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  509. NSData *data = [NSData dataWithContentsOfURL:newURL];
  510. if (data && error == nil) {
  511. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  512. // Upload File
  513. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  514. } else {
  515. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  516. }
  517. } else {
  518. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  519. }
  520. }];
  521. }
  522. }
  523. - (void)openImportDocumentPicker
  524. {
  525. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  526. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  527. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  528. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  529. documentProviderMenu.delegate = self;
  530. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  531. }
  532. #pragma --------------------------------------------------------------------------------------------
  533. #pragma mark ===== Assets Picker =====
  534. #pragma --------------------------------------------------------------------------------------------
  535. - (void)openAssetsPickerController
  536. {
  537. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  538. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  539. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  540. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  541. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  542. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  543. dispatch_async(dispatch_get_main_queue(), ^{
  544. // init picker
  545. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  546. // set delegate
  547. picker.delegate = self;
  548. // to show selection order
  549. //picker.showsSelectionIndex = YES;
  550. // to present picker as a form sheet in iPad
  551. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  552. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  553. // present picker
  554. [self presentViewController:picker animated:YES completion:nil];
  555. });
  556. }];
  557. }
  558. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  559. {
  560. [picker dismissViewControllerAnimated:YES completion:^{
  561. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  562. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  563. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  564. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  565. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  566. [self presentViewController:navigationController animated:YES completion:nil];
  567. }];
  568. }
  569. #pragma --------------------------------------------------------------------------------------------
  570. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  571. #pragma --------------------------------------------------------------------------------------------
  572. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  573. {
  574. // evitiamo il rimando della eventuale photo e/o video
  575. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  576. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  577. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  578. }
  579. }
  580. #pragma --------------------------------------------------------------------------------------------
  581. #pragma mark ===== UnZipFile =====
  582. #pragma --------------------------------------------------------------------------------------------
  583. - (void)unZipFile:(NSString *)fileID
  584. {
  585. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  586. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  587. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  588. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  589. dispatch_async(dispatch_get_main_queue(), ^{
  590. float progress = (float) entryNumber / (float)total;
  591. [_hudDeterminate progress:progress];
  592. });
  593. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  594. dispatch_async(dispatch_get_main_queue(), ^{
  595. [_hudDeterminate hideHud];
  596. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  597. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  598. });
  599. }];
  600. });
  601. }
  602. #pragma --------------------------------------------------------------------------------------------
  603. #pragma mark ===== Create New (OpenModel) =====
  604. #pragma --------------------------------------------------------------------------------------------
  605. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  606. {
  607. UIViewController *viewController;
  608. NSString *fileName, *uuid, *fileID, *serverUrl;
  609. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  610. [self.tableView deselectRowAtIndexPath:index animated:NO];
  611. if (isnew) {
  612. fileName = nil;
  613. uuid = [CCUtility getUUID];
  614. fileID = nil;
  615. serverUrl = _serverUrl;
  616. } else {
  617. fileName = _metadata.fileName;
  618. uuid = _metadata.uuid;
  619. fileID = _metadata.fileID;
  620. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  621. }
  622. if ([tipo isEqualToString:@"cartadicredito"])
  623. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  624. if ([tipo isEqualToString:@"bancomat"])
  625. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  626. if ([tipo isEqualToString:@"contocorrente"])
  627. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  628. if ([tipo isEqualToString:@"accountweb"])
  629. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  630. if ([tipo isEqualToString:@"patenteguida"])
  631. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  632. if ([tipo isEqualToString:@"cartaidentita"])
  633. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"passaporto"])
  635. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  636. if ([tipo isEqualToString:@"note"]) {
  637. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  638. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  639. [self presentViewController:navigationController animated:YES completion:nil];
  640. } else {
  641. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  642. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  643. [self presentViewController:navigationController animated:YES completion:nil];
  644. }
  645. }
  646. // New folder or new photo or video
  647. - (void)returnCreate:(NSInteger)type
  648. {
  649. switch (type) {
  650. /* PLAIN */
  651. case k_returnCreateFolderPlain: {
  652. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  653. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  654. alertView.tag = alertCreateFolder;
  655. [alertView show];
  656. }
  657. break;
  658. case k_returnCreateFotoVideoPlain: {
  659. _isPickerCriptate = false;
  660. [self openAssetsPickerController];
  661. }
  662. break;
  663. case k_returnCreateFilePlain: {
  664. _isPickerCriptate = false;
  665. [self openImportDocumentPicker];
  666. }
  667. break;
  668. /* ENCRYPTED */
  669. case k_returnCreateFolderEncrypted: {
  670. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  671. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  672. alertView.tag = alertCreateFolderCrypto;
  673. [alertView show];
  674. }
  675. break;
  676. case k_returnCreateFotoVideoEncrypted: {
  677. _isPickerCriptate = true;
  678. [self openAssetsPickerController];
  679. }
  680. break;
  681. case k_returnCreateFileEncrypted: {
  682. _isPickerCriptate = true;
  683. [self openImportDocumentPicker];
  684. }
  685. break;
  686. /* UTILITY */
  687. case k_returnNote:
  688. [self openModel:@"note" isNew:true];
  689. break;
  690. case k_returnAccountWeb:
  691. [self openModel:@"accountweb" isNew:true];
  692. break;
  693. /* BANK */
  694. case k_returnCartaDiCredito:
  695. [self openModel:@"cartadicredito" isNew:true];
  696. break;
  697. case k_returnBancomat:
  698. [self openModel:@"bancomat" isNew:true];
  699. break;
  700. case k_returnContoCorrente:
  701. [self openModel:@"contocorrente" isNew:true];
  702. break;
  703. /* DOCUMENT */
  704. case k_returnPatenteGuida:
  705. [self openModel:@"patenteguida" isNew:true];
  706. break;
  707. case k_returnCartaIdentita:
  708. [self openModel:@"cartaidentita" isNew:true];
  709. break;
  710. case k_returnPassaporto:
  711. [self openModel:@"passaporto" isNew:true];
  712. break;
  713. }
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ===== Save selected File =====
  717. #pragma --------------------------------------------------------------------------------------------
  718. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  719. {
  720. if (error)
  721. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  722. else
  723. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  724. }
  725. - (void)saveSelectedFiles
  726. {
  727. NSLog(@"[LOG] Start download selected files ...");
  728. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  729. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  730. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  731. for (CCMetadata *metadata in metadatas) {
  732. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  733. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  734. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  735. }
  736. }
  737. [_hud hideHud];
  738. });
  739. [self tableViewSelect:NO];
  740. }
  741. #pragma --------------------------------------------------------------------------------------------
  742. #pragma mark ===== Change Password =====
  743. #pragma --------------------------------------------------------------------------------------------
  744. - (void) loginSuccess:(NSInteger)loginType
  745. {
  746. [self readFolderWithForced:YES serverUrl:_serverUrl];
  747. }
  748. - (void)changePasswordAccount
  749. {
  750. // Brand
  751. if (k_option_use_login_web) {
  752. _loginWeb = [CCLoginWeb new];
  753. _loginWeb.delegate = self;
  754. _loginWeb.loginType = loginModifyPasswordUser;
  755. dispatch_async(dispatch_get_main_queue(), ^ {
  756. [_loginWeb presentModalWithDefaultTheme:self];
  757. });
  758. } else {
  759. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  760. _loginVC.delegate = self;
  761. _loginVC.loginType = loginModifyPasswordUser;
  762. [self presentViewController:_loginVC animated:YES completion:nil];
  763. }
  764. }
  765. #pragma mark -
  766. #pragma --------------------------------------------------------------------------------------------
  767. #pragma mark ===== Peek & Pop =====
  768. #pragma --------------------------------------------------------------------------------------------
  769. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  770. {
  771. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  772. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  773. if (metadata.thumbnailExists && !metadata.cryptated) {
  774. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  775. if (cell) {
  776. previewingContext.sourceRect = cell.frame;
  777. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  778. vc.delegate = self;
  779. vc.metadata = metadata;
  780. return vc;
  781. }
  782. }
  783. return nil;
  784. }
  785. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  786. {
  787. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  788. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  789. }
  790. #pragma mark -
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ==== External Sites ====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  795. {
  796. [CCCoreData deleteAllExternalSitesForAccount:app.activeAccount];
  797. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  798. [CCCoreData addExternalSites:tableExternalSites account:app.activeAccount];
  799. }
  800. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  801. {
  802. NSLog(@"[LOG] No External Sites found");
  803. }
  804. #pragma --------------------------------------------------------------------------------------------
  805. #pragma mark ==== Activity ====
  806. #pragma --------------------------------------------------------------------------------------------
  807. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  808. {
  809. for (OCActivity *activity in listOfActivity)
  810. [CCCoreData addActivityServer:activity account:app.activeAccount];
  811. // Reload Activity Data Source
  812. [app.activeActivity reloadDatasource];
  813. }
  814. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  815. {
  816. NSLog(@"[LOG] No Activity found");
  817. }
  818. #pragma --------------------------------------------------------------------------------------------
  819. #pragma mark ==== Notification ====
  820. #pragma --------------------------------------------------------------------------------------------
  821. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  822. {
  823. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  824. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  825. // Order by date
  826. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  827. OCNotifications *notification1 = obj1, *notification2 = obj2;
  828. return [notification2.date compare: notification1.date];
  829. }];
  830. // verify if listOfNotifications is changed
  831. NSString *old = @"", *new = @"";
  832. for (OCNotifications *notification in listOfNotifications)
  833. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  834. for (OCNotifications *notification in appDelegate.listOfNotifications)
  835. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  836. if (![new isEqualToString:old]) {
  837. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  838. // reload Notification view
  839. dispatch_async(dispatch_get_main_queue(), ^{
  840. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  841. });
  842. }
  843. // Update NavigationBar
  844. if (!_isSelectedMode) {
  845. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  846. }
  847. });
  848. }
  849. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  850. {
  851. // Update NavigationBar
  852. if (!_isSelectedMode)
  853. [self setUINavigationBarDefault];
  854. }
  855. - (void)viewNotification
  856. {
  857. if ([app.listOfNotifications count] > 0) {
  858. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  859. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  860. [self presentViewController:notificationVC animated:YES completion:nil];
  861. }
  862. }
  863. #pragma --------------------------------------------------------------------------------------------
  864. #pragma mark ==== Request Server ====
  865. #pragma --------------------------------------------------------------------------------------------
  866. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  867. {
  868. [CCCoreData setUserProfileActiveAccount:metadataNet.account userProfile:userProfile];
  869. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  870. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  871. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  872. if (avatar)
  873. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  874. else
  875. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  876. });
  877. }
  878. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  879. {
  880. TableCapabilities *oldCapabilities = [CCCoreData getCapabilitesForAccount:app.activeAccount];
  881. [CCCoreData addCapabilities:capabilities account:app.activeAccount];
  882. // Change Theming color
  883. if (k_option_use_themingColor) {
  884. app.themingColor = [CCGraphics colorFromHexString:capabilities.themingColor];
  885. if (![oldCapabilities.themingColor isEqualToString:capabilities.themingColor]) {
  886. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTheming" object:nil];
  887. self.navigationController.navigationBar.barTintColor = app.themingColor;
  888. }
  889. }
  890. // Search bar if change version
  891. if (app.serverVersion != capabilities.versionMajor) {
  892. [self cancelSearchBar];
  893. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  894. if (capabilities.versionMajor >= 12) {
  895. if (_isRoot)
  896. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  897. else
  898. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  899. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  900. } else {
  901. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  902. self.searchController.searchBar.scopeButtonTitles = nil;
  903. }
  904. _depth = @"0";
  905. });
  906. }
  907. if (capabilities.isExternalSitesServerEnabled) {
  908. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  909. metadataNet.action = actionGetExternalSitesServer;
  910. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  911. }
  912. [CCCoreData setServerVersionActiveAccount:app.activeAccount versionMajor:capabilities.versionMajor versionMinor:capabilities.versionMinor versionMicro:capabilities.versionMicro];
  913. app.serverVersion = capabilities.versionMajor;
  914. }
  915. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  916. {
  917. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  918. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  919. app.hasServerShareSupport = hasShareSupport;
  920. app.hasServerShareeSupport = hasShareeSupport;
  921. if (hasShareSupport || hasShareeSupport)
  922. [self requestSharedByServer];
  923. }
  924. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  925. {
  926. if (errorCode == 401)
  927. [self changePasswordAccount];
  928. }
  929. - (void)requestServerInformation
  930. {
  931. // test
  932. if (app.activeAccount.length == 0)
  933. return;
  934. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  935. [app.sharesID removeAllObjects];
  936. app.hasServerForbiddenCharactersSupport = YES;
  937. app.hasServerShareSupport = YES;
  938. metadataNet.action = actionGetFeaturesSuppServer;
  939. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  940. metadataNet.action = actionGetCapabilities;
  941. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  942. metadataNet.action = actionGetNotificationServer;
  943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  944. metadataNet.action = actionGetUserProfile;
  945. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  946. metadataNet.action = actionGetActivityServer;
  947. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  948. }
  949. #pragma --------------------------------------------------------------------------------------------
  950. #pragma mark ==== Download Thumbnail Delegate ====
  951. #pragma --------------------------------------------------------------------------------------------
  952. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  953. {
  954. __block CCCellMain *cell;
  955. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  956. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  957. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  958. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  959. if (cell.fileImageView.image == nil) {
  960. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  961. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  962. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  963. });
  964. }
  965. }
  966. }
  967. #pragma --------------------------------------------------------------------------------------------
  968. #pragma mark ==== Download ====
  969. #pragma --------------------------------------------------------------------------------------------
  970. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  971. {
  972. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  973. // File do not exists on server, remove in local
  974. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  975. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  976. }
  977. if ([selector isEqualToString:selectorLoadViewImage]) {
  978. dispatch_async(dispatch_get_main_queue(), ^{
  979. // Updating Detail
  980. if (app.activeDetail)
  981. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  982. // Updating Photos
  983. if (app.activePhotosCameraUpload)
  984. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  985. });
  986. } else {
  987. if (errorCode != kCFURLErrorCancelled)
  988. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  989. }
  990. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  991. }
  992. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  993. {
  994. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  995. if (metadata == nil) return;
  996. // Download
  997. if ([selector isEqualToString:selectorDownloadFile]) {
  998. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  999. }
  1000. // Synchronized
  1001. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1002. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1003. }
  1004. // add Favorite
  1005. if ([selector isEqualToString:selectorAddFavorite]) {
  1006. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1007. }
  1008. // add Offline
  1009. if ([selector isEqualToString:selectorAddOffline]) {
  1010. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  1011. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1012. }
  1013. // encrypted file
  1014. if ([selector isEqualToString:selectorEncryptFile]) {
  1015. [self encryptedFile:metadata];
  1016. }
  1017. // decrypted file
  1018. if ([selector isEqualToString:selectorDecryptFile]) {
  1019. [self decryptedFile:metadata];
  1020. }
  1021. // open View File
  1022. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1023. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1024. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1025. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1026. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1027. selector = selectorOpenIn;
  1028. } else {
  1029. _metadata = metadata;
  1030. if ([self shouldPerformSegue])
  1031. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1032. }
  1033. }
  1034. // addLocal
  1035. if ([selector isEqualToString:selectorAddLocal]) {
  1036. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1037. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1038. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1039. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  1040. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1041. }
  1042. // Open with...
  1043. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1044. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1045. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1046. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1047. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1048. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1049. _docController.delegate = self;
  1050. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1051. }
  1052. // Save to Photo Album
  1053. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1054. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1055. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1056. // evitiamo il rimando photo
  1057. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  1058. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1059. if (image)
  1060. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1061. else
  1062. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1063. }
  1064. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1065. // we avoid the cross-reference video
  1066. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  1067. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1068. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1069. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1070. } else {
  1071. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1072. }
  1073. }
  1074. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1075. }
  1076. // Copy File
  1077. if ([selector isEqualToString:selectorLoadCopy]) {
  1078. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1079. [self copyFileToPasteboard:metadata];
  1080. }
  1081. // download and view a template
  1082. if ([selector isEqualToString:selectorLoadModelView]) {
  1083. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1084. [self openModel:metadata.model isNew:false];
  1085. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1086. }
  1087. //download file plist
  1088. if ([selector isEqualToString:selectorLoadPlist]) {
  1089. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1090. long countSelectorLoadPlist = 0;
  1091. for (NSOperation *operation in [app.netQueue operations]) {
  1092. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1093. countSelectorLoadPlist++;
  1094. }
  1095. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1096. dispatch_async(dispatch_get_main_queue(), ^{
  1097. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1098. });
  1099. }
  1100. }
  1101. //selectorLoadViewImage
  1102. if ([selector isEqualToString:selectorLoadViewImage]) {
  1103. dispatch_async(dispatch_get_main_queue(), ^{
  1104. // Detail
  1105. if (app.activeDetail)
  1106. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1107. // Photos
  1108. if (app.activePhotosCameraUpload)
  1109. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1110. });
  1111. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1112. }
  1113. // if exists postselector call self with selectorPost
  1114. if ([selectorPost length] > 0)
  1115. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1116. }
  1117. - (void)downloadSelectedFiles
  1118. {
  1119. NSLog(@"[LOG] Start download selected files ...");
  1120. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1121. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1122. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1123. for (CCMetadata *metadata in selectedMetadatas) {
  1124. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1125. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1126. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1127. }
  1128. }
  1129. [_hud hideHud];
  1130. });
  1131. [self tableViewSelect:NO];
  1132. }
  1133. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1134. {
  1135. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1136. for (TableMetadata *recordMetadata in records) {
  1137. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1138. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1139. metadataNet.action = actionDownloadFile;
  1140. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1141. metadataNet.downloadData = NO;
  1142. metadataNet.downloadPlist = YES;
  1143. metadataNet.selector = selectorLoadPlist;
  1144. metadataNet.serverUrl = serverUrl;
  1145. metadataNet.session = k_download_session_foreground;
  1146. metadataNet.taskStatus = k_taskStatusResume;
  1147. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1148. }
  1149. }
  1150. }
  1151. #pragma --------------------------------------------------------------------------------------------
  1152. #pragma mark ===== Upload new Photos/Videos =====
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1155. {
  1156. // Automatic upload All
  1157. if([selector isEqualToString:selectorUploadAutomaticAll])
  1158. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1159. // Read File test do not exists
  1160. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1161. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1162. // reUpload
  1163. if (metadata)
  1164. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1165. }
  1166. // Print error
  1167. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1168. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1169. }
  1170. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1171. }
  1172. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1173. {
  1174. // Automatic upload All
  1175. if([selector isEqualToString:selectorUploadAutomaticAll])
  1176. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1177. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1178. [self readFolderWithForced:YES serverUrl:serverUrl];
  1179. } else {
  1180. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1181. }
  1182. }
  1183. //
  1184. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1185. //
  1186. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1187. {
  1188. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1189. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1190. });
  1191. }
  1192. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1193. {
  1194. NSArray *assets = [arguments objectAtIndex:0];
  1195. NSString *serverUrl = [arguments objectAtIndex:1];
  1196. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1197. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1198. NSString *session = [arguments objectAtIndex:4];
  1199. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1200. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1201. // Create the folder for Photos & if request the subfolders
  1202. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1203. return;
  1204. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1205. for (PHAsset *asset in assets) {
  1206. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1207. NSDate *assetDate = asset.creationDate;
  1208. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1209. // Create serverUrl if use sub folder
  1210. if (useSubFolder) {
  1211. [formatter setDateFormat:@"yyyy"];
  1212. NSString *yearString = [formatter stringFromDate:assetDate];
  1213. [formatter setDateFormat:@"MM"];
  1214. NSString *monthString = [formatter stringFromDate:assetDate];
  1215. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1216. }
  1217. // Check if is in upload
  1218. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1219. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1220. if ([isRecordInSessions count] > 0) {
  1221. // next upload
  1222. continue;
  1223. } else {
  1224. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1225. metadataNet.action = actionReadFile;
  1226. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1227. metadataNet.cryptated = cryptated;
  1228. metadataNet.fileName = fileName;
  1229. metadataNet.priority = NSOperationQueuePriorityNormal;
  1230. metadataNet.session = session;
  1231. metadataNet.selector = selectorReadFileUploadFile;
  1232. metadataNet.serverUrl = serverUrl;
  1233. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1234. }
  1235. }
  1236. }
  1237. #pragma --------------------------------------------------------------------------------------------
  1238. #pragma mark ==== Read File ====
  1239. #pragma --------------------------------------------------------------------------------------------
  1240. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1241. {
  1242. // UploadFile
  1243. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1244. // File not exists
  1245. if (errorCode == 404) {
  1246. metadataNet.action = actionUploadAsset;
  1247. metadataNet.errorCode = 0;
  1248. metadataNet.selector = selectorUploadFile;
  1249. metadataNet.selectorPost = nil;
  1250. metadataNet.taskStatus = k_taskStatusResume;
  1251. if ([metadataNet.session containsString:@"wwan"])
  1252. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1253. else
  1254. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1255. } else {
  1256. // error ho many retry befor notification and go to on next asses
  1257. if (metadataNet.errorRetry < 3) {
  1258. // Retry read file
  1259. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1260. } else {
  1261. // STOP check file, view message error
  1262. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1263. }
  1264. }
  1265. }
  1266. }
  1267. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1268. {
  1269. // UploadFile
  1270. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1271. metadataNet.action = actionUploadAsset;
  1272. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1273. metadataNet.selector = selectorUploadFile;
  1274. metadataNet.selectorPost = nil;
  1275. metadataNet.taskStatus = k_taskStatusResume;
  1276. if ([metadataNet.session containsString:@"wwan"])
  1277. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1278. else
  1279. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1280. }
  1281. }
  1282. #pragma --------------------------------------------------------------------------------------------
  1283. #pragma mark ==== Read Folder ====
  1284. #pragma --------------------------------------------------------------------------------------------
  1285. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1286. {
  1287. // verify active user
  1288. TableAccount *record = [CCCoreData getActiveAccount];
  1289. [_hud hideHud];
  1290. [_refreshControl endRefreshing];
  1291. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1292. if (message && [record.account isEqualToString:metadataNet.account])
  1293. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1294. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1295. if (errorCode == 401)
  1296. [self changePasswordAccount];
  1297. }
  1298. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1299. {
  1300. // verify active user
  1301. TableAccount *record = [CCCoreData getActiveAccount];
  1302. if (![record.account isEqualToString:metadataNet.account])
  1303. return;
  1304. // save father e update permission
  1305. if(!_isSearchMode)
  1306. _fatherPermission = permissions;
  1307. NSArray *recordsInSessions;
  1308. if (_isSearchMode) {
  1309. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1310. } else {
  1311. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1312. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1313. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1314. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1315. }
  1316. for (CCMetadata *metadata in metadatas) {
  1317. // Delete Record only in Search Mode
  1318. if (_isSearchMode)
  1319. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1320. // type of file
  1321. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1322. // if crypto do not insert
  1323. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1324. // verify if the record encrypted has plist + crypto
  1325. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1326. BOOL isCryptoComplete = NO;
  1327. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1328. for (CCMetadata *completeMetadata in metadatas) {
  1329. if (completeMetadata.cryptated == NO) continue;
  1330. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1331. isCryptoComplete = YES;
  1332. break;
  1333. }
  1334. }
  1335. if (isCryptoComplete == NO) continue;
  1336. }
  1337. // verify if the record is in download/upload progress
  1338. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1339. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1340. // is in Upload
  1341. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1342. NSString *sessionID = metadataDB.sessionID;
  1343. // rename SessionID -> fileID
  1344. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1345. metadataDB.session = @"";
  1346. metadataDB.date = metadata.date;
  1347. metadataDB.fileID = metadata.fileID;
  1348. metadataDB.rev = metadata.fileID;
  1349. metadataDB.sessionError = @"";
  1350. metadataDB.sessionID = @"";
  1351. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1352. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1353. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1354. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1355. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1356. continue;
  1357. }
  1358. // download in progress
  1359. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1360. continue;
  1361. }
  1362. // end test, insert in CoreData
  1363. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1364. }
  1365. // read plist
  1366. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1367. // File is changed ??
  1368. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1369. if (!_isSearchMode)
  1370. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1371. });
  1372. // Search Mode
  1373. if (_isSearchMode)
  1374. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1375. // this is the same directory
  1376. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1377. // reload
  1378. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1379. // stoprefresh
  1380. [_refreshControl endRefreshing];
  1381. // Enable change user
  1382. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1383. [_hud hideHud];
  1384. }
  1385. }
  1386. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1387. {
  1388. // init control
  1389. if (!serverUrl || !app.activeAccount)
  1390. return;
  1391. // Search Mode
  1392. if (_isSearchMode) {
  1393. if (forced) {
  1394. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:serverUrl directoryID:nil];
  1395. _searchFileName = @""; // forced reload searchg
  1396. }
  1397. [self updateSearchResultsForSearchController:self.searchController];
  1398. return;
  1399. }
  1400. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1401. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1402. if (_refreshControl.isRefreshing == NO)
  1403. [_hud visibleIndeterminateHud];
  1404. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1405. metadataNet.action = actionReadFolder;
  1406. metadataNet.date = [NSDate date];
  1407. metadataNet.directoryID = directoryID;
  1408. metadataNet.priority = NSOperationQueuePriorityHigh;
  1409. metadataNet.selector = selectorReadFolder;
  1410. metadataNet.serverUrl = serverUrl;
  1411. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1412. }
  1413. }
  1414. #pragma mark -
  1415. #pragma --------------------------------------------------------------------------------------------
  1416. #pragma mark ===== Search =====
  1417. #pragma --------------------------------------------------------------------------------------------
  1418. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1419. {
  1420. _isSearchMode = YES;
  1421. [self deleteRefreshControl];
  1422. NSString *fileName = [CCUtility removeForbiddenCharacters:searchController.searchBar.text hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1423. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1424. _searchFileName = fileName;
  1425. if (app.serverVersion >= 12 && ![_depth isEqualToString:@"0"]) {
  1426. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1427. _noFilesSearchTitle = @"";
  1428. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1429. [self.tableView reloadEmptyDataSet];
  1430. } else {
  1431. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1432. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(directoryID == %@) AND (account == %@) AND (fileNamePrint CONTAINS[cd] %@)", directoryID, app.activeAccount, fileName];
  1433. NSArray *records = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1434. [_searchResultMetadatas removeAllObjects];
  1435. for (TableMetadata *record in records)
  1436. [_searchResultMetadatas addObject:[CCCoreData insertEntityInMetadata:record]];
  1437. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1438. metadataNet.account = app.activeAccount;
  1439. metadataNet.action = actionUploadTemplate;
  1440. metadataNet.directoryID = directoryID;
  1441. metadataNet.selector = selectorSearch;
  1442. metadataNet.serverUrl = _serverUrl;
  1443. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1444. }
  1445. }
  1446. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1447. [self reloadDatasource];
  1448. }
  1449. }
  1450. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1451. {
  1452. [self cancelSearchBar];
  1453. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1454. }
  1455. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1456. {
  1457. _searchFileName = @"";
  1458. if (message)
  1459. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1460. }
  1461. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1462. {
  1463. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1464. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1465. }
  1466. - (void)cancelSearchBar
  1467. {
  1468. if (self.searchController.active) {
  1469. [self.searchController setActive:NO];
  1470. [self createRefreshControl];
  1471. _isSearchMode = NO;
  1472. _searchFileName = @"";
  1473. _dateReadDataSource = nil;
  1474. _searchResultMetadatas = [NSMutableArray new];
  1475. [self reloadDatasource];
  1476. }
  1477. }
  1478. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1479. {
  1480. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1481. self.searchController.searchBar.placeholder = title;
  1482. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1483. _depth = @"0";
  1484. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1485. _depth = @"1";
  1486. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1487. _depth = @"infinity";
  1488. _searchFileName = @"";
  1489. [self updateSearchResultsForSearchController:self.searchController];
  1490. }
  1491. #pragma mark -
  1492. #pragma --------------------------------------------------------------------------------------------
  1493. #pragma mark ===== Delete File or Folder =====
  1494. #pragma --------------------------------------------------------------------------------------------
  1495. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1496. {
  1497. [self deleteFileOrFolderSuccess:metadataNet];
  1498. }
  1499. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1500. {
  1501. [_queueSelector removeObject:metadataNet.selector];
  1502. if ([_queueSelector count] == 0) {
  1503. [_hud hideHud];
  1504. if (_isSearchMode)
  1505. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1506. else
  1507. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1508. // next
  1509. if ([_selectedMetadatas count] > 0) {
  1510. [_selectedMetadatas removeObjectAtIndex:0];
  1511. if ([_selectedMetadatas count] > 0)
  1512. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1513. }
  1514. }
  1515. }
  1516. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1517. {
  1518. if (metadata.cryptated) {
  1519. [_queueSelector addObject:selectorDeleteCrypto];
  1520. [_queueSelector addObject:selectorDeletePlist];
  1521. } else {
  1522. [_queueSelector addObject:selectorDelete];
  1523. }
  1524. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1525. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1526. }
  1527. - (void)deleteSelectionFile
  1528. {
  1529. [_selectedMetadatas removeAllObjects];
  1530. [_queueSelector removeAllObjects];
  1531. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1532. _numSelectedMetadatas = [_selectedMetadatas count];
  1533. if ([_selectedMetadatas count] > 0)
  1534. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1535. [self tableViewSelect:NO];
  1536. }
  1537. - (void)deleteFile
  1538. {
  1539. [_selectedMetadatas removeAllObjects];
  1540. [_queueSelector removeAllObjects];
  1541. _numSelectedMetadatas = 1;
  1542. [_selectedMetadatas addObject:_metadata];
  1543. if ([_selectedMetadatas count] > 0)
  1544. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1545. [self tableViewSelect:NO];
  1546. }
  1547. #pragma --------------------------------------------------------------------------------------------
  1548. #pragma mark ===== Rename / Move =====
  1549. #pragma --------------------------------------------------------------------------------------------
  1550. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1551. {
  1552. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1553. }
  1554. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1555. {
  1556. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1557. }
  1558. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1559. {
  1560. CCTemplates *templates = [[CCTemplates alloc] init];
  1561. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1562. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1563. if (fileNameModel) {
  1564. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1565. metadataNet.action = actionUploadTemplate;
  1566. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1567. metadataNet.fileNamePrint = fileName;
  1568. metadataNet.rev = metadata.rev;
  1569. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1570. metadataNet.session = k_upload_session_foreground;
  1571. metadataNet.taskStatus = k_taskStatusResume;
  1572. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1573. metadataNet.selectorPost = selectorAddOffline;
  1574. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1575. }
  1576. }
  1577. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1578. {
  1579. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1580. [_hud hideHud];
  1581. if (message)
  1582. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1583. [_selectedMetadatas removeAllObjects];
  1584. [_queueSelector removeAllObjects];
  1585. }
  1586. }
  1587. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1588. {
  1589. [_queueSelector removeObject:metadataNet.selector];
  1590. if ([_queueSelector count] == 0) {
  1591. [_hud hideHud];
  1592. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1593. NSString *directoryID = metadataNet.directoryID;
  1594. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1595. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1596. // FILE -> Metadata
  1597. if (metadataNet.directory == NO) {
  1598. // move metadata
  1599. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1600. }
  1601. // DIRECTORY -> Directory - CCMetadata
  1602. if (metadataNet.directory == YES) {
  1603. // delete all dir / subdir
  1604. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1605. // delete all metadata and local file in dir / subdir
  1606. for (NSString *directoryIDDelete in directoryIDs)
  1607. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1608. // move metadata
  1609. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1610. // Add new directory
  1611. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1612. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1613. // Check Offline
  1614. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1615. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1616. }
  1617. // reload Datasource
  1618. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1619. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1620. else
  1621. [self reloadDatasource];
  1622. // Next file
  1623. [_selectedMetadatas removeObjectAtIndex:0];
  1624. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1625. }
  1626. }
  1627. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1628. {
  1629. if ([_selectedMetadatas count] > 0) {
  1630. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1631. // Plain
  1632. if (metadata.cryptated == NO) {
  1633. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1634. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1635. if(!error) {
  1636. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1637. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1638. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1639. }];
  1640. [alert addAction:ok];
  1641. [self presentViewController:alert animated:YES completion:nil];
  1642. });
  1643. return;
  1644. }
  1645. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1646. metadataNet.action = actionMoveFileOrFolder;
  1647. metadataNet.directory = metadata.directory;
  1648. metadataNet.fileID = metadata.fileID;
  1649. metadataNet.directoryID = metadata.directoryID;
  1650. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1651. metadataNet.fileName = metadata.fileName;
  1652. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1653. metadataNet.fileNameTo = metadata.fileName;
  1654. metadataNet.rev = metadata.rev;
  1655. metadataNet.selector = selectorMove;
  1656. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1657. metadataNet.serverUrlTo = serverUrlTo;
  1658. [_queueSelector addObject:metadataNet.selector];
  1659. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1660. }
  1661. // cyptated
  1662. if (metadata.cryptated == YES) {
  1663. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1664. metadataNet.action = actionMoveFileOrFolder;
  1665. metadataNet.directory = metadata.directory;
  1666. metadataNet.fileID = metadata.fileID;
  1667. metadataNet.directoryID = metadata.directoryID;
  1668. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1669. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1670. metadataNet.rev = metadata.rev;
  1671. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1672. metadataNet.serverUrlTo = serverUrlTo;
  1673. // data
  1674. metadataNet.fileName = metadata.fileNameData;
  1675. metadataNet.fileNameTo = metadata.fileNameData;
  1676. metadataNet.selector = selectorMoveCrypto;
  1677. [_queueSelector addObject:metadataNet.selector];
  1678. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1679. // plist
  1680. metadataNet.fileName = metadata.fileName;
  1681. metadataNet.fileNameTo = metadata.fileName;
  1682. metadataNet.selector = selectorMovePlist;
  1683. [_queueSelector addObject:metadataNet.selector];
  1684. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1685. }
  1686. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1687. }
  1688. }
  1689. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1690. {
  1691. [_selectedMetadatas removeAllObjects];
  1692. [_queueSelector removeAllObjects];
  1693. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1694. _numSelectedMetadatas = [_selectedMetadatas count];
  1695. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1696. [self tableViewSelect:NO];
  1697. }
  1698. - (void)moveOpenWindow:(NSArray *)indexPaths
  1699. {
  1700. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1701. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1702. viewController.delegate = self;
  1703. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1704. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1705. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1706. viewController.barTintColor = [NCBrandColor sharedInstance].navigationBar;
  1707. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1708. viewController.networkingOperationQueue = app.netQueue;
  1709. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1710. [self presentViewController:navigationController animated:YES completion:nil];
  1711. }
  1712. #pragma --------------------------------------------------------------------------------------------
  1713. #pragma mark ===== Create folder =====
  1714. #pragma --------------------------------------------------------------------------------------------
  1715. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1716. {
  1717. [_hud hideHud];
  1718. if (message)
  1719. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1720. }
  1721. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1722. {
  1723. [_hud hideHud];
  1724. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1725. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1726. // Check Offline
  1727. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1728. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1729. // Load Folder or the Datasource
  1730. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1731. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1732. } else {
  1733. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1734. }
  1735. }
  1736. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1737. {
  1738. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1739. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1740. if (![fileNameFolder length]) return;
  1741. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1742. else metadataNet.serverUrl = _serverUrl;
  1743. metadataNet.action = actionCreateFolder;
  1744. if (folderCameraUpload)
  1745. metadataNet.options = @"folderCameraUpload";
  1746. metadataNet.fileName = fileNameFolder;
  1747. metadataNet.selector = selectorCreateFolder;
  1748. metadataNet.selectorPost = selectorReadFolderForced;
  1749. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1750. if (!folderCameraUpload)
  1751. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1752. }
  1753. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1754. {
  1755. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1756. NSString *fileNamePlist;
  1757. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1758. if (![fileNameFolder length]) return;
  1759. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1760. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1761. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1762. // Create folder
  1763. metadataNet.action = actionCreateFolder;
  1764. metadataNet.fileName = fileNamePlist;
  1765. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1766. metadataNet.selector = selectorCreateFolder;
  1767. metadataNet.serverUrl = _serverUrl;
  1768. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1769. // upload plist file
  1770. metadataNet.action = actionUploadOnlyPlist;
  1771. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1772. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1773. metadataNet.selectorPost = selectorReadFolderForced;
  1774. metadataNet.serverUrl = _serverUrl;
  1775. metadataNet.session = k_upload_session_foreground;
  1776. metadataNet.taskStatus = k_taskStatusResume;
  1777. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1778. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1779. }
  1780. - (void)createFolderCameraUpload
  1781. {
  1782. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1783. }
  1784. #pragma --------------------------------------------------------------------------------------------
  1785. #pragma mark ===== Encrypted / Decrypted Folder =====
  1786. #pragma --------------------------------------------------------------------------------------------
  1787. - (void)encyptedDecryptedFolder
  1788. {
  1789. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1790. if (_metadata.cryptated) {
  1791. // DECRYPTED
  1792. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1793. //-------------------------- RENAME -------------------------------------------//
  1794. metadataNet.action = actionMoveFileOrFolder;
  1795. metadataNet.fileID = _metadata.fileID;
  1796. metadataNet.fileName = _metadata.fileNameData;
  1797. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1798. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1799. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1800. metadataNet.selector = selectorRename;
  1801. metadataNet.serverUrl = serverUrl;
  1802. metadataNet.serverUrlTo = serverUrl;
  1803. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1804. //-------------------------- DELETE -------------------------------------------//
  1805. metadataNet.action = actionDeleteFileDirectory;
  1806. metadataNet.fileID = _metadata.fileID;
  1807. metadataNet.fileName = _metadata.fileName;
  1808. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1809. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1810. metadataNet.selector = selectorDeletePlist;
  1811. metadataNet.selectorPost = selectorReadFolderForced;
  1812. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1813. } else {
  1814. // ENCRYPTED
  1815. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1816. // Create File Plist
  1817. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1818. //-------------------------- RENAME -------------------------------------------//
  1819. metadataNet.action = actionMoveFileOrFolder;
  1820. metadataNet.fileID = _metadata.fileID;
  1821. metadataNet.fileName = _metadata.fileName;
  1822. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1823. metadataNet.fileNameTo = fileNameCrypto;
  1824. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1825. metadataNet.selector = selectorRename;
  1826. metadataNet.serverUrl = serverUrl;
  1827. metadataNet.serverUrlTo = serverUrl;
  1828. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1829. //-------------------------- UPLOAD -------------------------------------------//
  1830. metadataNet.action = actionUploadOnlyPlist;
  1831. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1832. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1833. metadataNet.selectorPost = selectorReadFolderForced;
  1834. metadataNet.serverUrl = serverUrl;
  1835. metadataNet.session = k_upload_session_foreground;
  1836. metadataNet.taskStatus = k_taskStatusResume;
  1837. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1838. }
  1839. }
  1840. #pragma --------------------------------------------------------------------------------------------
  1841. #pragma mark ===== Encrypted/Decrypted File =====
  1842. #pragma --------------------------------------------------------------------------------------------
  1843. - (void)encryptedSelectedFiles
  1844. {
  1845. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1846. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1847. for (CCMetadata *metadata in selectedMetadatas) {
  1848. if (metadata.cryptated == NO && metadata.directory == NO)
  1849. [metadatas addObject:metadata];
  1850. }
  1851. if ([metadatas count] > 0) {
  1852. NSLog(@"[LOG] Start encrypted selected files ...");
  1853. for (CCMetadata* metadata in metadatas) {
  1854. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1855. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1856. }
  1857. }
  1858. [self tableViewSelect:NO];
  1859. }
  1860. - (void)decryptedSelectedFiles
  1861. {
  1862. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1863. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1864. for (CCMetadata *metadata in selectedMetadatas) {
  1865. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1866. [metadatas addObject:metadata];
  1867. }
  1868. if ([metadatas count] > 0) {
  1869. NSLog(@"[LOG] Start decrypted selected files ...");
  1870. for (CCMetadata* metadata in metadatas) {
  1871. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1872. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1873. }
  1874. }
  1875. [self tableViewSelect:NO];
  1876. }
  1877. - (void)cmdEncryptedDecryptedFile
  1878. {
  1879. NSString *selector;
  1880. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1881. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1882. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1883. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1884. }
  1885. - (void)encryptedFile:(CCMetadata *)metadata
  1886. {
  1887. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1888. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1889. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1890. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1891. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1892. dispatch_async(dispatch_get_main_queue(), ^{
  1893. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1894. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1895. });
  1896. } else {
  1897. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1898. }
  1899. }
  1900. - (void)decryptedFile:(CCMetadata *)metadata
  1901. {
  1902. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1903. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1904. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1905. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1906. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1907. dispatch_async(dispatch_get_main_queue(), ^{
  1908. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1909. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1910. });
  1911. } else {
  1912. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1913. }
  1914. }
  1915. #pragma --------------------------------------------------------------------------------------------
  1916. #pragma mark ===== Progress & Task Button =====
  1917. #pragma --------------------------------------------------------------------------------------------
  1918. - (void)triggerProgressTask:(NSNotification *)notification
  1919. {
  1920. NSDictionary *dict = notification.userInfo;
  1921. NSString *fileID = [dict valueForKey:@"fileID"];
  1922. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1923. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1924. float progress = [[dict valueForKey:@"progress"] floatValue];
  1925. // Check
  1926. if (!fileID)
  1927. return;
  1928. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1929. if (![serverUrl isEqualToString:_serverUrl])
  1930. return;
  1931. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1932. if (indexPath) {
  1933. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1934. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1935. else cell.progressView.progressTintColor = [UIColor blackColor];
  1936. cell.progressView.hidden = NO;
  1937. [cell.progressView setProgress:progress];
  1938. }
  1939. if (progress == 0)
  1940. [self.navigationController cancelCCProgress];
  1941. else
  1942. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1943. }
  1944. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1945. {
  1946. UITouch * touch = [[event allTouches] anyObject];
  1947. CGPoint location = [touch locationInView:self.tableView];
  1948. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1949. if (indexPath) {
  1950. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1951. if (metadata)
  1952. [self reloadTaskButton:metadata];
  1953. }
  1954. }
  1955. - (void)reloadTaskButton:(CCMetadata *)metadata
  1956. {
  1957. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1958. __block NSURLSessionTask *findTask;
  1959. // DOWNLOAD
  1960. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1961. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1962. for (NSURLSessionUploadTask *task in downloadTasks)
  1963. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1964. findTask = task;
  1965. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1966. [task cancel];
  1967. }
  1968. if (!findTask) {
  1969. dispatch_async(dispatch_get_main_queue(), ^{
  1970. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1971. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1972. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1973. });
  1974. }
  1975. }];
  1976. }
  1977. // UPLOAD
  1978. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1979. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1980. for (NSURLSessionUploadTask *task in uploadTasks)
  1981. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1982. findTask = task;
  1983. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1984. [task cancel];
  1985. }
  1986. if (!findTask) {
  1987. dispatch_async(dispatch_get_main_queue(), ^{
  1988. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1989. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1990. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1991. });
  1992. }
  1993. }];
  1994. }
  1995. }
  1996. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1997. {
  1998. UITouch * touch = [[event allTouches] anyObject];
  1999. CGPoint location = [touch locationInView:self.tableView];
  2000. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2001. if (indexPath) {
  2002. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2003. if (metadata)
  2004. [self cancelTaskButton:metadata reloadTable:YES];
  2005. }
  2006. }
  2007. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  2008. {
  2009. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2010. __block NSURLSessionTask *findTask;
  2011. // DOWNLOAD
  2012. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2013. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2014. for (NSURLSessionTask *task in downloadTasks)
  2015. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2016. findTask = task;
  2017. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2018. [task cancel];
  2019. }
  2020. if (!findTask) {
  2021. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2022. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2023. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2024. }
  2025. }];
  2026. }
  2027. // UPLOAD
  2028. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2029. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2030. for (NSURLSessionUploadTask *task in uploadTasks)
  2031. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2032. findTask = task;
  2033. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2034. [task cancel];
  2035. }
  2036. if (!findTask) {
  2037. dispatch_async(dispatch_get_main_queue(), ^{
  2038. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2039. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2040. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2041. });
  2042. }
  2043. }];
  2044. }
  2045. }
  2046. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2047. {
  2048. UITouch * touch = [[event allTouches] anyObject];
  2049. CGPoint location = [touch locationInView:self.tableView];
  2050. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2051. if (indexPath) {
  2052. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2053. if (metadata)
  2054. [self stopTaskButton:metadata];
  2055. }
  2056. }
  2057. - (void)stopTaskButton:(CCMetadata *)metadata
  2058. {
  2059. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2060. __block NSURLSessionTask *findTask;
  2061. // UPLOAD
  2062. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2063. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2064. for (NSURLSessionUploadTask *task in uploadTasks)
  2065. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2066. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2067. findTask = task;
  2068. [task cancel];
  2069. }
  2070. if (!findTask) {
  2071. dispatch_async(dispatch_get_main_queue(), ^{
  2072. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2073. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2074. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2075. });
  2076. }
  2077. }];
  2078. }
  2079. }
  2080. #pragma --------------------------------------------------------------------------------------------
  2081. #pragma mark ===== Shared =====
  2082. #pragma --------------------------------------------------------------------------------------------
  2083. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2084. {
  2085. [_hud hideHud];
  2086. // change account ?
  2087. TableAccount *record = [CCCoreData getActiveAccount];
  2088. if([record.account isEqualToString:metadataNet.account] == NO)
  2089. return;
  2090. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl];
  2091. if (openWindow) {
  2092. if (_shareOC) {
  2093. [_shareOC reloadData];
  2094. } else {
  2095. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2096. // Apriamo la view
  2097. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2098. _shareOC.delegate = self;
  2099. _shareOC.metadata = metadata;
  2100. _shareOC.serverUrl = metadataNet.serverUrl;
  2101. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2102. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2103. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2104. [self presentViewController:_shareOC animated:YES completion:nil];
  2105. }
  2106. }
  2107. [self tableViewReload];
  2108. }
  2109. - (void)requestSharedByServer
  2110. {
  2111. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2112. metadataNet.action = actionReadShareServer;
  2113. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2114. }
  2115. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2116. {
  2117. [_hud hideHud];
  2118. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2119. if (_shareOC)
  2120. [_shareOC reloadData];
  2121. [self tableViewReload];
  2122. if (errorCode == 401)
  2123. [self changePasswordAccount];
  2124. }
  2125. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2126. {
  2127. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2128. metadataNet.action = actionShare;
  2129. metadataNet.fileID = metadata.fileID;
  2130. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2131. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2132. metadataNet.password = password;
  2133. metadataNet.selector = selectorShare;
  2134. metadataNet.serverUrl = serverUrl;
  2135. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2136. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2137. }
  2138. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2139. {
  2140. [_hud hideHud];
  2141. // rimuoviamo la condivisione da db
  2142. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2143. if (_shareOC)
  2144. [_shareOC reloadData];
  2145. [self tableViewReload];
  2146. }
  2147. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2148. {
  2149. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2150. metadataNet.action = actionUnShare;
  2151. metadataNet.fileID = metadata.fileID;
  2152. metadataNet.fileName = metadata.fileName;
  2153. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2154. metadataNet.selector = selectorUnshare;
  2155. metadataNet.serverUrl = serverUrl;
  2156. metadataNet.share = share;
  2157. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2158. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2159. }
  2160. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2161. {
  2162. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2163. metadataNet.action = actionUpdateShare;
  2164. metadataNet.fileID = metadata.fileID;
  2165. metadataNet.expirationTime = expirationTime;
  2166. metadataNet.password = password;
  2167. metadataNet.selector = selectorUpdateShare;
  2168. metadataNet.serverUrl = serverUrl;
  2169. metadataNet.share = share;
  2170. metadataNet.sharePermission = permission;
  2171. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2172. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2173. }
  2174. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2175. {
  2176. [_hud hideHud];
  2177. if (_shareOC)
  2178. [_shareOC reloadUserAndGroup:items];
  2179. }
  2180. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2181. {
  2182. [_hud hideHud];
  2183. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2184. }
  2185. - (void)getUserAndGroup:(NSString *)find
  2186. {
  2187. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2188. metadataNet.action = actionGetUserAndGroup;
  2189. metadataNet.options = find;
  2190. metadataNet.selector = selectorGetUserAndGroup;
  2191. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2192. [_hud visibleIndeterminateHud];
  2193. }
  2194. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2195. {
  2196. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2197. metadataNet.action = actionShareWith;
  2198. metadataNet.fileID = metadata.fileID;
  2199. metadataNet.directoryID = directoryID;
  2200. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2201. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2202. metadataNet.serverUrl = serverUrl;
  2203. metadataNet.selector = selectorShare;
  2204. metadataNet.share = user;
  2205. metadataNet.shareeType = shareeType;
  2206. metadataNet.sharePermission = permission;
  2207. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2208. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2209. }
  2210. - (void)openWindowShare:(CCMetadata *)metadata
  2211. {
  2212. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2213. metadataNet.action = actionReadShareServer;
  2214. metadataNet.fileID = metadata.fileID;
  2215. metadataNet.fileName = metadata.fileName;
  2216. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2217. metadataNet.selector = selectorOpenWindowShare;
  2218. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2219. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2220. [_hud visibleIndeterminateHud];
  2221. }
  2222. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2223. {
  2224. CGPoint location = [tapGesture locationInView:self.tableView];
  2225. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2226. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2227. if (metadata)
  2228. [self openWindowShare:metadata];
  2229. }
  2230. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2231. {
  2232. CGPoint location = [tapGesture locationInView:self.tableView];
  2233. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2234. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2235. if (metadata) {
  2236. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2237. vc.metadata = metadata;
  2238. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2239. [self presentViewController:vc animated:YES completion:nil];
  2240. }
  2241. }
  2242. #pragma --------------------------------------------------------------------------------------------
  2243. #pragma mark ===== Favorite =====
  2244. #pragma --------------------------------------------------------------------------------------------
  2245. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2246. {
  2247. [CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2248. _dateReadDataSource = nil;
  2249. if (_isSearchMode)
  2250. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2251. else
  2252. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2253. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2254. if (metadata.directory && metadata.favorite) {
  2255. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2256. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2257. }
  2258. }
  2259. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2260. {
  2261. }
  2262. - (void)addFavorite:(CCMetadata *)metadata
  2263. {
  2264. if (metadata.directory) {
  2265. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2266. } else {
  2267. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2268. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2269. }
  2270. }
  2271. - (void)removeFavorite:(CCMetadata *)metadata
  2272. {
  2273. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2274. }
  2275. #pragma --------------------------------------------------------------------------------------------
  2276. #pragma mark ===== Offline =====
  2277. #pragma --------------------------------------------------------------------------------------------
  2278. - (void)addOffline:(CCMetadata *)metadata
  2279. {
  2280. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2281. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2282. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2283. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2284. }
  2285. - (void)removeOffline:(CCMetadata *)metadata
  2286. {
  2287. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2288. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2289. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2290. }
  2291. #pragma --------------------------------------------------------------------------------------------
  2292. #pragma mark ===== Local =====
  2293. #pragma --------------------------------------------------------------------------------------------
  2294. - (void)addLocal:(CCMetadata *)metadata
  2295. {
  2296. if (metadata.errorPasscode || !metadata.uuid) return;
  2297. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2298. if ([metadata.type isEqualToString: k_metadataType_file])
  2299. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2300. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2301. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2302. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2303. }
  2304. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2305. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2306. }
  2307. #pragma --------------------------------------------------------------------------------------------
  2308. #pragma mark ===== Open in... =====
  2309. #pragma --------------------------------------------------------------------------------------------
  2310. - (void)openIn:(CCMetadata *)metadata
  2311. {
  2312. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2313. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2314. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2315. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2316. }
  2317. #pragma --------------------------------------------------------------------------------------------
  2318. #pragma mark ===== Remove Local File =====
  2319. #pragma --------------------------------------------------------------------------------------------
  2320. - (void)removeLocalFile:(CCMetadata *)metadata
  2321. {
  2322. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2323. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2324. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2325. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2326. }
  2327. #pragma --------------------------------------------------------------------------------------------
  2328. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2329. #pragma --------------------------------------------------------------------------------------------
  2330. - (void)orderTable:(NSString *)order
  2331. {
  2332. [CCUtility setOrderSettings:order];
  2333. // Clear data-read of DataSource
  2334. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2335. // new menu
  2336. [self createReMainMenu];
  2337. }
  2338. - (void)ascendingTable:(BOOL)ascending
  2339. {
  2340. [CCUtility setAscendingSettings:ascending];
  2341. // Clear data-read of DataSource
  2342. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2343. // new menu
  2344. [self createReMainMenu];
  2345. }
  2346. - (void)directoryOnTop:(BOOL)directoryOnTop
  2347. {
  2348. [CCUtility setDirectoryOnTop:directoryOnTop];
  2349. // Clear data-read of DataSource
  2350. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2351. // new menu
  2352. [self createReMainMenu];
  2353. }
  2354. - (void)tableGroupBy:(NSString *)groupBy
  2355. {
  2356. [CCUtility setGroupBySettings:groupBy];
  2357. // Clear data-read of DataSource
  2358. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2359. // new menu
  2360. [self createReMainMenu];
  2361. }
  2362. #pragma --------------------------------------------------------------------------------------------
  2363. #pragma mark ==== Menu LOGO ====
  2364. #pragma --------------------------------------------------------------------------------------------
  2365. - (void)menuLogo
  2366. {
  2367. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2368. return;
  2369. // Brand
  2370. if (k_option_disable_multiaccount)
  2371. return;
  2372. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2373. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2374. return;
  2375. }
  2376. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2377. NSMutableArray *menuArray = [NSMutableArray new];
  2378. for (TableAccount *record in listTableAccount) {
  2379. if ([record.account isEqualToString:app.activeAccount]) continue;
  2380. CCMenuItem *item = [[CCMenuItem alloc] init];
  2381. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2382. item.argument = record.account;
  2383. item.image = [UIImage imageNamed:image_MenuLogoUser];
  2384. item.target = self;
  2385. item.action = @selector(changeDefaultAccount:);
  2386. [menuArray addObject:item];
  2387. }
  2388. if ([menuArray count] == 0)
  2389. return;
  2390. OptionalConfiguration options;
  2391. Color textColor, backgroundColor;
  2392. textColor.R = 0;
  2393. textColor.G = 0;
  2394. textColor.B = 0;
  2395. backgroundColor.R = 1;
  2396. backgroundColor.G = 1;
  2397. backgroundColor.B = 1;
  2398. NSInteger originY = 60;
  2399. options.arrowSize = 9;
  2400. options.marginXSpacing = 7;
  2401. options.marginYSpacing = 10;
  2402. options.intervalSpacing = 20;
  2403. options.menuCornerRadius = 6.5;
  2404. options.maskToBackground = NO;
  2405. options.shadowOfMenu = YES;
  2406. options.hasSeperatorLine = YES;
  2407. options.seperatorLineHasInsets = YES;
  2408. options.textColor = textColor;
  2409. options.menuBackgroundColor = backgroundColor;
  2410. CGRect rect = self.view.frame;
  2411. rect.origin.y = rect.origin.y + originY;
  2412. rect.size.height = rect.size.height - originY;
  2413. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2414. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2415. }
  2416. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2417. {
  2418. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2419. // STOP, erase all in queue networking
  2420. [app cancelAllOperations];
  2421. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2422. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2423. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2424. if (tableAccount)
  2425. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2426. // go to home sweet home
  2427. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2428. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2429. });
  2430. }
  2431. #pragma --------------------------------------------------------------------------------------------
  2432. #pragma mark ==== ReMenu ====
  2433. #pragma --------------------------------------------------------------------------------------------
  2434. - (void)createReMenuBackgroundView:(REMenu *)menu
  2435. {
  2436. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2437. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2438. [UIView animateWithDuration:0.2 animations:^{
  2439. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2440. if (height < self.tabBarController.tabBar.frame.size.height)
  2441. height = self.tabBarController.tabBar.frame.size.height;
  2442. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2443. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2444. }];
  2445. }
  2446. - (void)createReMainMenu
  2447. {
  2448. NSString *ordinamento;
  2449. NSString *groupBy = _directoryGroupBy;
  2450. __block NSString *nuovoOrdinamento;
  2451. NSString *titoloNuovo, *titoloAttuale;
  2452. BOOL ascendente;
  2453. __block BOOL nuovoAscendente;
  2454. UIImage *image;
  2455. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2456. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_seleziona] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2457. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2458. [self tableViewSelect:YES];
  2459. }
  2460. }];
  2461. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_seleziona] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2462. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2463. [self tableViewSelect:YES];
  2464. }];
  2465. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2466. ordinamento = _directoryOrder;
  2467. if ([ordinamento isEqualToString:@"fileName"]) {
  2468. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdeyByDate] color:app.themingColor];
  2469. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2470. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2471. nuovoOrdinamento = @"fileDate";
  2472. }
  2473. if ([ordinamento isEqualToString:@"fileDate"]) {
  2474. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrderByFileName] color:app.themingColor];
  2475. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2476. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2477. nuovoOrdinamento = @"fileName";
  2478. }
  2479. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2480. [self orderTable:nuovoOrdinamento];
  2481. }];
  2482. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2483. [self orderTable:nuovoOrdinamento];
  2484. }];
  2485. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2486. ascendente = [CCUtility getAscendingSettings];
  2487. if (ascendente) {
  2488. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdinamentoDiscendente] color:app.themingColor];
  2489. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2490. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2491. nuovoAscendente = false;
  2492. }
  2493. if (!ascendente) {
  2494. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdinamentoAscendente] color:app.themingColor];
  2495. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2496. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2497. nuovoAscendente = true;
  2498. }
  2499. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2500. [self ascendingTable:nuovoAscendente];
  2501. }];
  2502. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2503. [self ascendingTable:nuovoAscendente];
  2504. }];
  2505. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2506. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2507. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2508. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByAlphabetic] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2509. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2510. else [self tableGroupBy:@"alphabetic"];
  2511. }];
  2512. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByAlphabetic] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2513. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2514. else [self tableGroupBy:@"alphabetic"];
  2515. }];
  2516. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2517. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2518. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2519. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByTypeFile] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2520. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2521. else [self tableGroupBy:@"typefile"];
  2522. }];
  2523. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByTypeFile] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2524. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2525. else [self tableGroupBy:@"typefile"];
  2526. }];
  2527. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2528. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2529. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2530. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByDate] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2531. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2532. else [self tableGroupBy:@"date"];
  2533. }];
  2534. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByDate] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2535. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2536. else [self tableGroupBy:@"date"];
  2537. }];
  2538. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2539. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2540. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2541. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuDirectoryOnTop] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2542. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2543. else [self directoryOnTop:YES];
  2544. }];
  2545. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuDirectoryOnTop] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2546. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2547. else [self directoryOnTop:YES];
  2548. }];
  2549. // REMENU --------------------------------------------------------------------------------------------------------------
  2550. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2551. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2552. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2553. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2554. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2555. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2556. app.reMainMenu.separatorHeight = 0.5;
  2557. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2558. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2559. app.reMainMenu.textColor = [UIColor blackColor];
  2560. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2561. app.reMainMenu.textShadowColor = nil;
  2562. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2563. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2564. app.reMainMenu.highlightedBackgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  2565. app.reMainMenu.highlightedSeparatorColor = nil;
  2566. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2567. app.reMainMenu.highlightedTextShadowColor = nil;
  2568. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2569. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2570. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2571. app.reMainMenu.subtitleTextShadowColor = nil;
  2572. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2573. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2574. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2575. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2576. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2577. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2578. app.reMainMenu.borderWidth = 0.3;
  2579. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2580. app.reMainMenu.animationDuration = 0.2;
  2581. app.reMainMenu.closeAnimationDuration = 0.2;
  2582. app.reMainMenu.bounce = NO;
  2583. [app.reMainMenu setClosePreparationBlock:^{
  2584. // Backgroun reMenu (Gesture)
  2585. [_reMenuBackgroundView removeFromSuperview];
  2586. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2587. }];
  2588. }
  2589. - (void)toggleReMainMenu
  2590. {
  2591. if (app.reMainMenu.isOpen) {
  2592. [app.reMainMenu close];
  2593. } else {
  2594. [app.reMainMenu showFromNavigationController:self.navigationController];
  2595. // Backgroun reMenu & (Gesture)
  2596. [self createReMenuBackgroundView:app.reMainMenu];
  2597. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2598. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2599. }
  2600. }
  2601. - (void)createReSelectMenu
  2602. {
  2603. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2604. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_deleteSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2605. [self deleteSelectionFile];
  2606. }];
  2607. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_deleteSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2608. [self deleteSelectionFile];
  2609. }];
  2610. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2611. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_moveSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2612. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2613. }];
  2614. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_moveSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2615. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2616. }];
  2617. if (app.isCryptoCloudMode) {
  2618. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2619. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_encryptedSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2620. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2621. }];
  2622. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_encryptedSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2623. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2624. }];
  2625. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2626. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_decryptedSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2627. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2628. }];
  2629. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_decryptedSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2630. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2631. }];
  2632. }
  2633. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2634. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_downloadSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2635. [self downloadSelectedFiles];
  2636. }];
  2637. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_downloadSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2638. [self downloadSelectedFiles];
  2639. }];
  2640. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2641. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_saveSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2642. [self saveSelectedFiles];
  2643. }];
  2644. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_saveSelectedFiles] color:app.themingColor] highlightedImage:nil action:^(REMenuItem *item) {
  2645. [self saveSelectedFiles];
  2646. }];
  2647. // REMENU --------------------------------------------------------------------------------------------------------------
  2648. if (app.isCryptoCloudMode) {
  2649. if (app.reSelectMenu == nil)
  2650. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2651. else
  2652. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2653. } else {
  2654. if (app.reSelectMenu == nil)
  2655. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2656. else
  2657. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2658. }
  2659. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2660. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2661. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2662. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2663. app.reSelectMenu.separatorHeight = 0.5;
  2664. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2665. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2666. app.reSelectMenu.textColor = [UIColor blackColor];
  2667. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2668. app.reSelectMenu.textShadowColor = nil;
  2669. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2670. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2671. app.reSelectMenu.highlightedBackgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  2672. app.reSelectMenu.highlightedSeparatorColor = nil;
  2673. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2674. app.reSelectMenu.highlightedTextShadowColor = nil;
  2675. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2676. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2677. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2678. app.reSelectMenu.subtitleTextShadowColor = nil;
  2679. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2680. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2681. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2682. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2683. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2684. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2685. app.reSelectMenu.borderWidth = 0.3;
  2686. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2687. app.reSelectMenu.closeAnimationDuration = 0.2;
  2688. app.reSelectMenu.animationDuration = 0.2;
  2689. app.reSelectMenu.bounce = NO;
  2690. [app.reSelectMenu setClosePreparationBlock:^{
  2691. // Backgroun reMenu (Gesture)
  2692. [_reMenuBackgroundView removeFromSuperview];
  2693. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2694. }];
  2695. }
  2696. - (void)toggleReSelectMenu
  2697. {
  2698. if (app.reSelectMenu.isOpen) {
  2699. [app.reSelectMenu close];
  2700. } else {
  2701. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2702. // Backgroun reMenu & (Gesture)
  2703. [self createReMenuBackgroundView:app.reSelectMenu];
  2704. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2705. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2706. }
  2707. }
  2708. #pragma --------------------------------------------------------------------------------------------
  2709. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2710. #pragma --------------------------------------------------------------------------------------------
  2711. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2712. {
  2713. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2714. UITableView *tableView = (UITableView*)self.view;
  2715. CGPoint touchPoint = [recognizer locationInView:self.view];
  2716. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2717. if (indexPath)
  2718. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2719. else
  2720. _metadata = nil;
  2721. [self becomeFirstResponder];
  2722. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2723. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2724. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2725. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2726. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2727. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2728. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2729. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2730. if (app.isCryptoCloudMode)
  2731. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2732. else
  2733. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2734. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2735. [menuController setMenuVisible:YES animated:YES];
  2736. }
  2737. }
  2738. - (BOOL)canBecomeFirstResponder
  2739. {
  2740. return YES;
  2741. }
  2742. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2743. {
  2744. // For copy file, copy files, Open in ... :
  2745. //
  2746. // NO Directory
  2747. // NO Error Passcode
  2748. // NO In Session mode (download/upload)
  2749. // NO Template
  2750. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2751. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2752. // NO Cryptated with Title lenght = 0
  2753. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2754. return YES;
  2755. }
  2756. return NO;
  2757. }
  2758. if (@selector(copyFiles:) == action) {
  2759. if (_isSelectedMode) {
  2760. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2761. for (CCMetadata *metadata in selectedMetadatas) {
  2762. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2763. // NO Cryptated with Title lenght = 0
  2764. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2765. return YES;
  2766. }
  2767. }
  2768. }
  2769. return NO;
  2770. }
  2771. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2772. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2773. NSArray *items = [pasteboard items];
  2774. if ([items count] == 1) {
  2775. // Value : (NSData) metadata
  2776. NSDictionary *dic = [items objectAtIndex:0];
  2777. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2778. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2779. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2780. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2781. if (directoryUser) {
  2782. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2783. return YES;
  2784. }
  2785. return NO;
  2786. } else return NO;
  2787. }
  2788. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2789. BOOL isValid = NO;
  2790. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2791. NSArray *items = [pasteboard items];
  2792. if ([items count] <= 1) return NO;
  2793. for (NSDictionary *dic in items) {
  2794. // Value : (NSData) metadata
  2795. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2796. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2797. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2798. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2799. if (directoryUser) {
  2800. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2801. isValid = YES;
  2802. }
  2803. }
  2804. return isValid;
  2805. }
  2806. return NO;
  2807. }
  2808. /************************************ COPY ************************************/
  2809. - (void)copyFile:(id)sender
  2810. {
  2811. // Remove all item
  2812. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2813. pasteboard.items = [[NSArray alloc] init];
  2814. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2815. [self copyFileToPasteboard:_metadata];
  2816. } else {
  2817. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2818. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2819. }
  2820. }
  2821. - (void)copyFiles:(id)sender
  2822. {
  2823. // Remove all item
  2824. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2825. pasteboard.items = [[NSArray alloc] init];
  2826. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2827. for (CCMetadata *metadata in selectedMetadatas) {
  2828. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2829. [self copyFileToPasteboard:metadata];
  2830. } else {
  2831. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2832. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2833. }
  2834. }
  2835. [self tableViewSelect:NO];
  2836. }
  2837. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2838. {
  2839. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2840. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2841. // Value : (NSData) metadata
  2842. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2843. [items addObject:item];
  2844. [pasteboard setItems:items];
  2845. }
  2846. /************************************ OPEN IN ... ************************************/
  2847. - (void)openinFile:(id)sender
  2848. {
  2849. [self openIn:_metadata];
  2850. }
  2851. /************************************ PASTE ************************************/
  2852. - (void)pasteFile:(id)sender
  2853. {
  2854. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2855. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2856. }
  2857. - (void)pasteFileEncrypted:(id)sender
  2858. {
  2859. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2860. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2861. }
  2862. - (void)pasteFiles:(id)sender
  2863. {
  2864. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2865. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2866. }
  2867. - (void)pasteFilesEncrypted:(id)sender
  2868. {
  2869. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2870. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2871. }
  2872. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2873. {
  2874. for (NSDictionary *dic in items) {
  2875. // Value : (NSData) metadata
  2876. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2877. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2878. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2879. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2880. if (directoryUser) {
  2881. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2882. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2883. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2884. }
  2885. }
  2886. }
  2887. }
  2888. #pragma --------------------------------------------------------------------------------------------
  2889. #pragma mark ===== Lock Passcode =====
  2890. #pragma --------------------------------------------------------------------------------------------
  2891. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2892. {
  2893. return _failedAttempts;
  2894. }
  2895. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2896. {
  2897. return _lockUntilDate;
  2898. }
  2899. - (void)passcodeViewCloseButtonPressed:(id)sender
  2900. {
  2901. [self dismissViewControllerAnimated:YES completion:nil];
  2902. }
  2903. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2904. {
  2905. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2906. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2907. _lockUntilDate = nil;
  2908. _failedAttempts = 0;
  2909. aResultHandler(YES);
  2910. } else aResultHandler(NO);
  2911. } else aResultHandler(YES);
  2912. }
  2913. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2914. {
  2915. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2916. switch (aViewController.type) {
  2917. case BKPasscodeViewControllerCheckPasscodeType: {
  2918. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2919. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2920. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2921. // scriviamo il passcode
  2922. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2923. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2924. } else {
  2925. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2926. [alertView show];
  2927. }
  2928. }
  2929. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2930. // possiamo procedere alla prossima directory
  2931. [self performSegueDirectoryWithControlPasscode:false];
  2932. // avviamo la sessione Passcode Lock con now
  2933. app.sessionePasscodeLock = [NSDate date];
  2934. }
  2935. // disattivazione lock cartella
  2936. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2937. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2938. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2939. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2940. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2941. }
  2942. [self.tableView reloadData];
  2943. }
  2944. }
  2945. break;
  2946. default:
  2947. break;
  2948. }
  2949. }
  2950. - (void)comandoLockPassword
  2951. {
  2952. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2953. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2954. // se non è abilitato il Lock Passcode esci
  2955. if ([[CCUtility getBlockCode] length] == 0) {
  2956. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2957. [alertView show];
  2958. return;
  2959. }
  2960. // se è richiesta la disattivazione si chiede la password
  2961. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2962. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2963. viewController.delegate = self;
  2964. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2965. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2966. viewController.inputViewTitlePassword = YES;
  2967. if ([CCUtility getSimplyBlockCode]) {
  2968. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2969. viewController.passcodeInputView.maximumLength = 6;
  2970. } else {
  2971. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2972. viewController.passcodeInputView.maximumLength = 64;
  2973. }
  2974. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2975. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2976. viewController.touchIDManager = touchIDManager;
  2977. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2978. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2979. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2980. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2981. [self presentViewController:navigationController animated:YES completion:nil];
  2982. return;
  2983. }
  2984. // ---------------- ACTIVATE PASSWORD
  2985. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2986. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2987. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2988. } else {
  2989. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2990. }
  2991. }
  2992. #pragma mark -
  2993. #pragma --------------------------------------------------------------------------------------------
  2994. #pragma mark ===== Swipe Tablet -> menu =====
  2995. #pragma --------------------------------------------------------------------------------------------
  2996. // more
  2997. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2998. return NSLocalizedString(@"_more_", nil);
  2999. }
  3000. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3001. {
  3002. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3003. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3004. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  3005. BOOL offlineFolder = NO;
  3006. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3007. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3008. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3009. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3010. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3011. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3012. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3013. offlineFolder = YES;
  3014. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3015. if (_metadata.favorite) {
  3016. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3017. } else {
  3018. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3019. }
  3020. if (_metadata.directory) {
  3021. // calcolo lockServerUrl
  3022. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3023. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3024. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3025. }
  3026. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  3027. /******************************************* AHKActionSheet *******************************************/
  3028. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3029. actionSheet.animationDuration = 0.2;
  3030. actionSheet.blurRadius = 0.0f;
  3031. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3032. actionSheet.buttonHeight = 50.0;
  3033. actionSheet.cancelButtonHeight = 50.0f;
  3034. actionSheet.separatorHeight = 5.0f;
  3035. actionSheet.automaticallyTintButtonImages = @(NO);
  3036. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3037. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3038. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3039. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3040. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3041. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3042. /******************************************* DIRECTORY *******************************************/
  3043. if (_metadata.directory) {
  3044. BOOL lockDirectory = NO;
  3045. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3046. // Directory bloccata ?
  3047. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3048. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3049. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3050. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3051. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:app.themingColor]
  3052. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3053. height: 50.0
  3054. type: AHKActionSheetButtonTypeDisabled
  3055. handler: nil
  3056. ];
  3057. if (!lockDirectory && !_metadata.cryptated) {
  3058. [actionSheet addButtonWithTitle:titleFavorite
  3059. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetFavorite] color:app.themingColor]
  3060. backgroundColor:[UIColor whiteColor]
  3061. height: 50.0
  3062. type:AHKActionSheetButtonTypeDefault
  3063. handler:^(AHKActionSheet *as) {
  3064. // close swipe
  3065. [self setEditing:NO animated:YES];
  3066. if (_metadata.favorite)
  3067. [self removeFavorite:_metadata];
  3068. else
  3069. [self addFavorite:_metadata];
  3070. }];
  3071. }
  3072. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3073. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3074. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:app.themingColor]
  3075. backgroundColor:[UIColor whiteColor]
  3076. height: 50.0
  3077. type:AHKActionSheetButtonTypeDefault
  3078. handler:^(AHKActionSheet *as) {
  3079. // close swipe
  3080. [self setEditing:NO animated:YES];
  3081. [self openWindowShare:_metadata];
  3082. }];
  3083. }
  3084. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3085. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3086. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRename] color:app.themingColor]
  3087. backgroundColor:[UIColor whiteColor]
  3088. height: 50.0
  3089. type:AHKActionSheetButtonTypeDefault
  3090. handler:^(AHKActionSheet *as) {
  3091. // close swipe
  3092. [self setEditing:NO animated:YES];
  3093. //chiediamo il nome del file
  3094. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3095. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3096. alertView.tag = alertRename;
  3097. UITextField *textField = [alertView textFieldAtIndex:0];
  3098. textField.text = _metadata.fileNamePrint;
  3099. [alertView show];
  3100. }];
  3101. }
  3102. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3103. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3104. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetMove] color:app.themingColor]
  3105. backgroundColor:[UIColor whiteColor]
  3106. height: 50.0
  3107. type:AHKActionSheetButtonTypeDefault
  3108. handler:^(AHKActionSheet *as) {
  3109. // close swipe
  3110. [self setEditing:NO animated:YES];
  3111. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3112. }];
  3113. }
  3114. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3115. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3116. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folderphotocamera] color:app.themingColor]
  3117. backgroundColor:[UIColor whiteColor]
  3118. height: 50.0
  3119. type:AHKActionSheetButtonTypeDefault
  3120. handler:^(AHKActionSheet *as) {
  3121. // close swipe
  3122. [self setEditing:NO animated:YES];
  3123. // Settings new folder Automatatic upload
  3124. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3125. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3126. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3127. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3128. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3129. [app.activePhotosCameraUpload reloadDatasourceForced];
  3130. [self readFolderWithForced:YES serverUrl:serverUrl];
  3131. NSLog(@"[LOG] Update Folder Photo");
  3132. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3133. if ([folderCameraUpload length] > 0)
  3134. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3135. }];
  3136. }
  3137. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3138. [actionSheet addButtonWithTitle:titoloLock
  3139. image:[UIImage imageNamed:image_actionSheetLock]
  3140. backgroundColor:[UIColor whiteColor]
  3141. height: 50.0
  3142. type:AHKActionSheetButtonTypeEncrypted
  3143. handler:^(AHKActionSheet *as) {
  3144. // close swipe
  3145. [self setEditing:NO animated:YES];
  3146. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3147. }];
  3148. }
  3149. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3150. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3151. image:[UIImage imageNamed:image_actionSheetCrypto]
  3152. backgroundColor:[UIColor whiteColor]
  3153. height: 50.0
  3154. type:AHKActionSheetButtonTypeEncrypted
  3155. handler:^(AHKActionSheet *as) {
  3156. // close swipe
  3157. [self setEditing:NO animated:YES];
  3158. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3159. }];
  3160. }
  3161. [actionSheet show];
  3162. }
  3163. /******************************************* FILE *******************************************/
  3164. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3165. UIImage *iconHeader;
  3166. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3167. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3168. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3169. else
  3170. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3171. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3172. image: iconHeader
  3173. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3174. height: 50.0
  3175. type: AHKActionSheetButtonTypeDisabled
  3176. handler: nil
  3177. ];
  3178. if (!_metadata.cryptated) {
  3179. [actionSheet addButtonWithTitle:titleFavorite
  3180. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetFavorite] color:app.themingColor]
  3181. backgroundColor:[UIColor whiteColor]
  3182. height: 50.0
  3183. type:AHKActionSheetButtonTypeDefault
  3184. handler:^(AHKActionSheet *as) {
  3185. // close swipe
  3186. [self setEditing:NO animated:YES];
  3187. if (_metadata.favorite)
  3188. [self removeFavorite:_metadata];
  3189. else
  3190. [self addFavorite:_metadata];
  3191. }];
  3192. }
  3193. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3194. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3195. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:app.themingColor]
  3196. backgroundColor:[UIColor whiteColor]
  3197. height: 50.0
  3198. type:AHKActionSheetButtonTypeDefault
  3199. handler:^(AHKActionSheet *as) {
  3200. // close swipe
  3201. [self setEditing:NO animated:YES];
  3202. [self openWindowShare:_metadata];
  3203. }];
  3204. }
  3205. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3206. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetOpenIn] color:app.themingColor]
  3207. backgroundColor:[UIColor whiteColor]
  3208. height: 50.0
  3209. type:AHKActionSheetButtonTypeDefault
  3210. handler:^(AHKActionSheet *as) {
  3211. // close swipe
  3212. [self setEditing:NO animated:YES];
  3213. [self performSelector:@selector(openIn:) withObject:_metadata];
  3214. }];
  3215. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3216. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRename] color:app.themingColor]
  3217. backgroundColor:[UIColor whiteColor]
  3218. height: 50.0
  3219. type:AHKActionSheetButtonTypeDefault
  3220. handler:^(AHKActionSheet *as) {
  3221. // close swipe
  3222. [self setEditing:NO animated:YES];
  3223. //chiediamo il nome del file
  3224. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3225. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3226. alertView.tag = alertRename;
  3227. UITextField *textField = [alertView textFieldAtIndex:0];
  3228. textField.text = _metadata.fileNamePrint;
  3229. [alertView show];
  3230. }];
  3231. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3232. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetMove] color:app.themingColor]
  3233. backgroundColor:[UIColor whiteColor]
  3234. height: 50.0
  3235. type:AHKActionSheetButtonTypeDefault
  3236. handler:^(AHKActionSheet *as) {
  3237. // close swipe
  3238. [self setEditing:NO animated:YES];
  3239. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3240. }];
  3241. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3242. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3243. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRemoveLocal] color:app.themingColor]
  3244. backgroundColor:[UIColor whiteColor]
  3245. height: 50.0
  3246. type:AHKActionSheetButtonTypeDefault
  3247. handler:^(AHKActionSheet *as) {
  3248. // close swipe
  3249. [self setEditing:NO animated:YES];
  3250. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3251. }];
  3252. }
  3253. if (app.isCryptoCloudMode) {
  3254. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3255. image:[UIImage imageNamed:image_actionSheetCrypto]
  3256. backgroundColor:[UIColor whiteColor]
  3257. height: 50.0
  3258. type:AHKActionSheetButtonTypeEncrypted
  3259. handler:^(AHKActionSheet *as) {
  3260. // close swipe
  3261. [self setEditing:NO animated:YES];
  3262. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3263. }];
  3264. }
  3265. [actionSheet show];
  3266. }
  3267. /******************************************* TEMPLATE *******************************************/
  3268. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3269. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3270. image: [UIImage imageNamed:_metadata.iconName]
  3271. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3272. height: 50.0
  3273. type: AHKActionSheetButtonTypeDisabled
  3274. handler: nil
  3275. ];
  3276. if ([_metadata.model isEqualToString:@"note"]) {
  3277. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3278. image:[UIImage imageNamed:image_actionSheetRename]
  3279. backgroundColor:[UIColor whiteColor]
  3280. height: 50.0
  3281. type:AHKActionSheetButtonTypeDefault
  3282. handler:^(AHKActionSheet *as) {
  3283. // close swipe
  3284. [self setEditing:NO animated:YES];
  3285. //chiediamo il nome del file
  3286. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3287. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3288. alertView.tag = alertRename;
  3289. UITextField *textField = [alertView textFieldAtIndex:0];
  3290. textField.text = _metadata.fileNamePrint;
  3291. [alertView show];
  3292. }];
  3293. }
  3294. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3295. image:[UIImage imageNamed:image_actionSheetMove]
  3296. backgroundColor:[UIColor whiteColor]
  3297. height: 50.0
  3298. type:AHKActionSheetButtonTypeDefault
  3299. handler:^(AHKActionSheet *as) {
  3300. // close swipe
  3301. [self setEditing:NO animated:YES];
  3302. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3303. }];
  3304. [actionSheet show];
  3305. }
  3306. }
  3307. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3308. {
  3309. return NSLocalizedString(@"_delete_", nil);
  3310. }
  3311. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3312. {
  3313. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3314. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3315. else return YES;
  3316. }
  3317. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3318. {
  3319. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3320. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3321. else return UITableViewCellEditingStyleDelete;
  3322. }
  3323. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3324. {
  3325. BOOL lockDirectory = NO;
  3326. // Directory locked ?
  3327. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3328. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3329. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3330. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3331. return;
  3332. }
  3333. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3334. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3335. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3336. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3337. style:UIAlertActionStyleDestructive
  3338. handler:^(UIAlertAction *action) {
  3339. [self performSelector:@selector(deleteFile) withObject:nil];
  3340. }]];
  3341. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3342. style:UIAlertActionStyleCancel
  3343. handler:^(UIAlertAction *action) {
  3344. [alertController dismissViewControllerAnimated:YES completion:nil];
  3345. }]];
  3346. alertController.popoverPresentationController.sourceView = self.view;
  3347. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3348. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3349. [alertController.view layoutIfNeeded];
  3350. [self presentViewController:alertController animated:YES completion:nil];
  3351. }
  3352. }
  3353. #pragma --------------------------------------------------------------------------------------------
  3354. #pragma mark - ==== Datasource ====
  3355. #pragma --------------------------------------------------------------------------------------------
  3356. - (void)clearDateReadDataSource:(NSNotification *)notification
  3357. {
  3358. _dateReadDataSource = Nil;
  3359. [self reloadDatasource];
  3360. }
  3361. - (void)reloadDatasource
  3362. {
  3363. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3364. }
  3365. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3366. {
  3367. // test
  3368. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3369. return;
  3370. // Search Mode
  3371. if(_isSearchMode) {
  3372. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3373. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3374. } else {
  3375. [self readFolderWithForced:NO serverUrl:serverUrl];
  3376. }
  3377. [self tableViewReload];
  3378. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3379. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3380. _noFilesSearchDescription = @"";
  3381. }
  3382. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3383. _noFilesSearchTitle = @"";
  3384. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3385. }
  3386. [self.tableView reloadEmptyDataSet];
  3387. return;
  3388. }
  3389. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3390. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3391. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3392. [app.activeTransfers reloadDatasource];
  3393. } else {
  3394. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3395. if (main) {
  3396. [main reloadDatasource];
  3397. } else {
  3398. [self tableViewReload];
  3399. [app.activeTransfers reloadDatasource];
  3400. }
  3401. }
  3402. return;
  3403. }
  3404. // Offline folder ?
  3405. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3406. [app.activeTransfers reloadDatasource];
  3407. // Settaggio variabili per le ottimizzazioni
  3408. _directoryGroupBy = [CCUtility getGroupBySettings];
  3409. _directoryOrder = [CCUtility getOrderSettings];
  3410. // Controllo data lettura Data Source
  3411. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3412. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3413. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3414. _dateReadDataSource = [NSDate date];
  3415. // Data Source
  3416. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3417. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3418. } else {
  3419. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3420. }
  3421. [self tableViewReload];
  3422. }
  3423. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3424. {
  3425. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3426. if (selectedRows.count > 0) {
  3427. for (NSIndexPath *selectionIndex in selectedRows) {
  3428. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3429. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3430. [metadatas addObject:metadata];
  3431. }
  3432. }
  3433. return metadatas;
  3434. }
  3435. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3436. {
  3437. NSInteger section = indexPath.section + 1;
  3438. NSInteger row = indexPath.row + 1;
  3439. NSInteger totSections =[_sectionDataSource.sections count] ;
  3440. if ((totSections < section) || (section > totSections)) {
  3441. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3442. return nil;
  3443. }
  3444. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3445. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3446. if (fileIDs) {
  3447. NSInteger totRows =[fileIDs count] ;
  3448. if ((totRows < row) || (row > totRows)) {
  3449. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3450. return nil;
  3451. }
  3452. } else {
  3453. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3454. return nil;
  3455. }
  3456. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3457. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3458. }
  3459. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3460. {
  3461. NSInteger totSections =[_sectionDataSource.sections count] ;
  3462. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3463. #if DEBUG
  3464. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3465. [alertView show];
  3466. #endif
  3467. return nil;
  3468. }
  3469. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3470. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3471. }
  3472. #pragma --------------------------------------------------------------------------------------------
  3473. #pragma mark - ==== Table ====
  3474. #pragma --------------------------------------------------------------------------------------------
  3475. - (void)tableViewSelect:(BOOL)edit
  3476. {
  3477. // chiudiamo eventuali swipe aperti
  3478. if (edit) [self.tableView setEditing:NO animated:NO];
  3479. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3480. [self.tableView setEditing:edit animated:YES];
  3481. _isSelectedMode = edit;
  3482. if (edit)
  3483. [self setUINavigationBarSelected];
  3484. else
  3485. [self setUINavigationBarDefault];
  3486. [self setTitle];
  3487. }
  3488. - (void)tableViewReload
  3489. {
  3490. // ricordiamoci le row selezionate
  3491. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3492. [self.tableView reloadData];
  3493. for (NSIndexPath *path in indexPaths)
  3494. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3495. [self setTableViewFooter];
  3496. if (self.tableView.editing)
  3497. [self setTitle];
  3498. }
  3499. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3500. {
  3501. return 60;
  3502. }
  3503. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3504. {
  3505. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3506. }
  3507. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3508. {
  3509. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3510. }
  3511. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3512. {
  3513. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3514. NSString *sectionTitle = [sections objectAtIndex:section];
  3515. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3516. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3517. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3518. return 20.f;
  3519. }
  3520. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3521. {
  3522. float shift;
  3523. UIVisualEffectView *visualEffectView;
  3524. // Titolo
  3525. NSString *titleSection;
  3526. // Controllo
  3527. if ([_sectionDataSource.sections count] == 0)
  3528. return nil;
  3529. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3530. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3531. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3532. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3533. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3534. else titleSection = NSLocalizedString(titleSection,nil);
  3535. // Formato titolo
  3536. NSString *currentDevice = [CCUtility currentDevice];
  3537. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3538. visualEffectView = [[UIVisualEffectView alloc] init];
  3539. visualEffectView.backgroundColor = [NCBrandColor sharedInstance].groupByBarNoBlur;
  3540. } else {
  3541. UIVisualEffect *blurEffect;
  3542. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3543. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3544. visualEffectView.backgroundColor = [NCBrandColor sharedInstance].groupByBar;
  3545. }
  3546. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3547. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3548. else shift = - 20;
  3549. } else shift = - 10;
  3550. // Title
  3551. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3552. titleLabel.backgroundColor = [UIColor clearColor];
  3553. titleLabel.textColor = [UIColor blackColor];
  3554. titleLabel.font = [UIFont systemFontOfSize:12];
  3555. titleLabel.textAlignment = NSTextAlignmentLeft;
  3556. titleLabel.text = titleSection;
  3557. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3558. [visualEffectView addSubview:titleLabel];
  3559. // Elements
  3560. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3561. elementLabel.backgroundColor = [UIColor clearColor];
  3562. elementLabel.textColor = [UIColor blackColor];;
  3563. elementLabel.font = [UIFont systemFontOfSize:12];
  3564. elementLabel.textAlignment = NSTextAlignmentRight;
  3565. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3566. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3567. NSUInteger rowsCount = [metadatas count];
  3568. if (rowsCount == 0) return nil;
  3569. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3570. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3571. [visualEffectView addSubview:elementLabel];
  3572. return visualEffectView;
  3573. }
  3574. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3575. {
  3576. return [_sectionDataSource.sections indexOfObject:title];
  3577. }
  3578. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3579. {
  3580. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3581. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3582. else
  3583. return nil;
  3584. }
  3585. /*
  3586. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3587. {
  3588. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3589. }
  3590. }
  3591. */
  3592. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3593. {
  3594. NSString *typeCell;
  3595. NSString *dataFile;
  3596. NSString *lunghezzaFile;
  3597. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3598. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3599. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3600. else typeCell = @"CellMainTransfer";
  3601. if (!metadata)
  3602. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3603. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3604. // separator
  3605. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3606. // change color selection
  3607. UIView *selectionColor = [[UIView alloc] init];
  3608. selectionColor.backgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  3609. cell.selectedBackgroundView = selectionColor;
  3610. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3611. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3612. // ----------------------------------------------------------------------------------------------------------
  3613. // DEFAULT
  3614. // ----------------------------------------------------------------------------------------------------------
  3615. cell.fileImageView.image = nil;
  3616. cell.statusImageView.image = nil;
  3617. cell.offlineImageView.image = nil;
  3618. cell.synchronizedImageView.image = nil;
  3619. cell.sharedImageView.image = nil;
  3620. cell.labelTitle.enabled = YES;
  3621. cell.labelTitle.text = @"";
  3622. cell.labelInfoFile.enabled = YES;
  3623. cell.labelInfoFile.text = @"";
  3624. cell.progressView.progress = 0.0;
  3625. cell.progressView.hidden = YES;
  3626. cell.cancelTaskButton.hidden = YES;
  3627. cell.reloadTaskButton.hidden = YES;
  3628. cell.stopTaskButton.hidden = YES;
  3629. // Encrypted color
  3630. if (metadata.cryptated) {
  3631. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3632. } else {
  3633. cell.labelTitle.textColor = [UIColor blackColor];
  3634. }
  3635. // ----------------------------------------------------------------------------------------------------------
  3636. // File Name & Folder
  3637. // ----------------------------------------------------------------------------------------------------------
  3638. // nome del file
  3639. cell.labelTitle.text = metadata.fileNamePrint;
  3640. // è una directory
  3641. if (metadata.directory) {
  3642. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3643. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3644. lunghezzaFile = @" ";
  3645. // ----------------------------------------------------------------------------------------------------------
  3646. // Favorite Folder
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. if (metadata.favorite) {
  3649. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3650. }
  3651. } else {
  3652. // File
  3653. dataFile = [CCUtility dateDiff:metadata.date];
  3654. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3655. // Plist ancora da scaricare
  3656. if (metadata.cryptated && [metadata.title length] == 0) {
  3657. dataFile = @" ";
  3658. lunghezzaFile = @" ";
  3659. }
  3660. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3661. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3662. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3663. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3664. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3665. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3666. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3667. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3668. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3669. else
  3670. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3671. }
  3672. // Plist ancora da scaricare
  3673. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3674. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3675. cell.accessoryType = UITableViewCellAccessoryNone;
  3676. }
  3677. // ----------------------------------------------------------------------------------------------------------
  3678. // File Image View
  3679. // ----------------------------------------------------------------------------------------------------------
  3680. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3681. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3682. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3683. if (cell.fileImageView.image == nil) {
  3684. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3685. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3686. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3687. dispatch_async(dispatch_get_main_queue(), ^{
  3688. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3689. if (cell)
  3690. cell.fileImageView.image = image;
  3691. });
  3692. });
  3693. }
  3694. } else {
  3695. if (metadata.directory)
  3696. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:app.themingColor];
  3697. else
  3698. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3699. if (metadata.thumbnailExists)
  3700. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3701. }
  3702. // ----------------------------------------------------------------------------------------------------------
  3703. // Image Status cyptated & Lock Passcode
  3704. // ----------------------------------------------------------------------------------------------------------
  3705. // File Cyptated
  3706. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3707. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3708. }
  3709. // Directory con passcode lock attivato
  3710. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3711. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3712. cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3713. // ----------------------------------------------------------------------------------------------------------
  3714. // Offline
  3715. // ----------------------------------------------------------------------------------------------------------
  3716. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3717. if (isOfflineFile) {
  3718. cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3719. }
  3720. // ----------------------------------------------------------------------------------------------------------
  3721. // Favorite
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. if (metadata.favorite) {
  3724. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3725. }
  3726. // ----------------------------------------------------------------------------------------------------------
  3727. // Share
  3728. // ----------------------------------------------------------------------------------------------------------
  3729. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3730. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3731. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3732. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3733. // Aggiungiamo il Tap per le shared
  3734. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3735. if (isShare) {
  3736. if (metadata.directory) {
  3737. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_shared_with_me] color:app.themingColor];
  3738. cell.sharedImageView.userInteractionEnabled = NO;
  3739. } else {
  3740. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:app.themingColor];
  3741. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3742. [tap setNumberOfTapsRequired:1];
  3743. cell.sharedImageView.userInteractionEnabled = YES;
  3744. [cell.sharedImageView addGestureRecognizer:tap];
  3745. }
  3746. }
  3747. if (isMounted) {
  3748. if (metadata.directory) {
  3749. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_external] color:app.themingColor];
  3750. cell.sharedImageView.userInteractionEnabled = NO;
  3751. } else {
  3752. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_shareMounted] color:app.themingColor];
  3753. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3754. [tap setNumberOfTapsRequired:1];
  3755. cell.sharedImageView.userInteractionEnabled = YES;
  3756. [cell.sharedImageView addGestureRecognizer:tap];
  3757. }
  3758. }
  3759. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3760. if (metadata.directory) {
  3761. if ([shareLink length] > 0)
  3762. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_public] color:app.themingColor];
  3763. if ([shareUserAndGroup length] > 0)
  3764. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_shared_with_me] color:app.themingColor];
  3765. cell.sharedImageView.userInteractionEnabled = NO;
  3766. } else {
  3767. if ([shareLink length] > 0)
  3768. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_shareLink] color:app.themingColor];
  3769. if ([shareUserAndGroup length] > 0)
  3770. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:app.themingColor];
  3771. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3772. [tap setNumberOfTapsRequired:1];
  3773. cell.sharedImageView.userInteractionEnabled = YES;
  3774. [cell.sharedImageView addGestureRecognizer:tap];
  3775. }
  3776. }
  3777. } else {
  3778. cell.sharedImageView.userInteractionEnabled = NO;
  3779. }
  3780. // ----------------------------------------------------------------------------------------------------------
  3781. // downloadFile
  3782. // ----------------------------------------------------------------------------------------------------------
  3783. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3784. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3785. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3786. // sessionTaskIdentifier : RELOAD + STOP
  3787. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3788. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3789. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3790. cell.cancelTaskButton.hidden = NO;
  3791. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3792. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3793. cell.reloadTaskButton.hidden = NO;
  3794. }
  3795. // sessionTaskIdentifierPlist : RELOAD
  3796. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3797. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3798. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3799. cell.reloadTaskButton.hidden = NO;
  3800. }
  3801. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3802. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3803. if (progress > 0) {
  3804. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3805. else cell.progressView.progressTintColor = [UIColor blackColor];
  3806. cell.progressView.progress = progress;
  3807. cell.progressView.hidden = NO;
  3808. }
  3809. // ----------------------------------------------------------------------------------------------------------
  3810. // downloadFile Error
  3811. // ----------------------------------------------------------------------------------------------------------
  3812. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3813. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3814. if ([metadata.sessionError length] == 0)
  3815. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3816. else
  3817. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3818. }
  3819. }
  3820. // ----------------------------------------------------------------------------------------------------------
  3821. // uploadFile
  3822. // ----------------------------------------------------------------------------------------------------------
  3823. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3824. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3825. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3826. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3827. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3828. cell.cancelTaskButton.hidden = NO;
  3829. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3830. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3831. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3832. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3833. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3834. cell.reloadTaskButton.hidden = NO;
  3835. cell.stopTaskButton.hidden = YES;
  3836. } else {
  3837. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3838. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3839. cell.stopTaskButton.hidden = NO;
  3840. cell.reloadTaskButton.hidden = YES;
  3841. }
  3842. // se non c'è una preview in bianconero metti l'immagine di default
  3843. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3844. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_uploaddisable] color:app.themingColor];
  3845. cell.labelTitle.enabled = NO;
  3846. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3847. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3848. if (progress > 0) {
  3849. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3850. else cell.progressView.progressTintColor = [UIColor blackColor];
  3851. cell.progressView.progress = progress;
  3852. cell.progressView.hidden = NO;
  3853. }
  3854. // ----------------------------------------------------------------------------------------------------------
  3855. // uploadFileError
  3856. // ----------------------------------------------------------------------------------------------------------
  3857. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3858. cell.labelTitle.enabled = NO;
  3859. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3860. if ([metadata.sessionError length] == 0)
  3861. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3862. else
  3863. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3864. }
  3865. }
  3866. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3867. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3868. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3869. return cell;
  3870. }
  3871. - (void)setTableViewFooter
  3872. {
  3873. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3874. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3875. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3876. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3877. UIFont *appFont = [UIFont systemFontOfSize:12];
  3878. footerLabel.font = appFont;
  3879. footerLabel.textColor = [UIColor grayColor];
  3880. footerLabel.backgroundColor = [UIColor clearColor];
  3881. footerLabel.textAlignment = NSTextAlignmentCenter;
  3882. NSString *folders;
  3883. NSString *files;
  3884. NSString *footerText;
  3885. if (_sectionDataSource.directories > 1) {
  3886. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3887. } else if (_sectionDataSource.directories == 1){
  3888. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3889. } else {
  3890. folders = @"";
  3891. }
  3892. if (_sectionDataSource.files > 1) {
  3893. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3894. } else if (_sectionDataSource.files == 1){
  3895. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3896. } else {
  3897. files = @"";
  3898. }
  3899. if ([folders isEqualToString:@""]) {
  3900. footerText = files;
  3901. } else if ([files isEqualToString:@""]) {
  3902. footerText = folders;
  3903. } else {
  3904. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3905. }
  3906. footerLabel.text = footerText;
  3907. [footerView addSubview:footerLabel];
  3908. [self.tableView setTableFooterView:footerView];
  3909. }
  3910. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3911. {
  3912. NSString *textMessage;
  3913. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3914. // se non può essere selezionata deseleziona
  3915. if ([cell isEditing] == NO)
  3916. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3917. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3918. if (self.tableView.editing) {
  3919. [self setTitle];
  3920. return;
  3921. }
  3922. // test crash
  3923. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3924. if (indexPath.row >= [metadatas count]) return;
  3925. // settiamo il record file.
  3926. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3927. //
  3928. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3929. // se è in corso una sessione
  3930. if ([_metadata.session length] > 0) return;
  3931. if (_metadata.errorPasscode) {
  3932. // se UUID è nil lo sta ancora caricando quindi esci
  3933. if (!_metadata.uuid) return;
  3934. // esiste un hint ??
  3935. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3936. // qui !! la richiesta della nuova passcode
  3937. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3938. // stesso UUID ... la password è stata modificata !!!!!!
  3939. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3940. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3941. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3942. [alertView show];
  3943. } else {
  3944. // UUID diverso.
  3945. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3946. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3947. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3948. [alertView show];
  3949. }
  3950. // chiediamo la passcode e ricarichiamo tutto.
  3951. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3952. viewController.delegate = self;
  3953. viewController.fromType = CCBKPasscodeFromPasscode;
  3954. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3955. viewController.passcodeInputView.maximumLength = 64;
  3956. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3957. viewController.inputViewTitlePassword = NO;
  3958. viewController.title = k_brand;
  3959. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3960. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3961. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3962. [self presentViewController:navigationController animated:YES completion:nil];
  3963. }
  3964. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3965. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3966. NSString* selector;
  3967. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3968. else selector = selectorLoadPlist;
  3969. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3970. return;
  3971. }
  3972. // se il plist è caricato ed è un modello aprilo
  3973. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3974. // file
  3975. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3976. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3977. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3978. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3979. } else {
  3980. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3981. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3982. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3983. }
  3984. }
  3985. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3986. }
  3987. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3988. {
  3989. [self setTitle];
  3990. }
  3991. #pragma --------------------------------------------------------------------------------------------
  3992. #pragma mark ===== Synchronize Folder Cell =====
  3993. #pragma --------------------------------------------------------------------------------------------
  3994. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3995. {
  3996. BOOL cryptated = NO;
  3997. CCCellMain *cell;
  3998. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3999. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4000. if (recordMetadata.directory == NO)
  4001. continue;
  4002. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  4003. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  4004. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4005. cryptated = recordMetadata.cryptated;
  4006. break;
  4007. }
  4008. }
  4009. if (!cell)
  4010. return;
  4011. if (animation) {
  4012. NSURL *myURL;
  4013. if (cryptated)
  4014. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4015. else
  4016. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4017. } else {
  4018. cell.synchronizedImageView.image = nil;
  4019. }
  4020. }
  4021. #pragma --------------------------------------------------------------------------------------------
  4022. #pragma mark ===== Navigation ====
  4023. #pragma --------------------------------------------------------------------------------------------
  4024. - (BOOL)shouldPerformSegue
  4025. {
  4026. // if background return
  4027. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4028. if (self.view.window == NO)
  4029. return NO;
  4030. // Collapsed ma siamo già in detail esci
  4031. if (self.splitViewController.isCollapsed)
  4032. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4033. // Video in esecuzione esci
  4034. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4035. return YES;
  4036. }
  4037. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4038. {
  4039. id viewController = segue.destinationViewController;
  4040. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4041. CCMetadata *metadata;
  4042. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4043. UINavigationController *nav = viewController;
  4044. _detailViewController = (CCDetail *)nav.topViewController;
  4045. } else {
  4046. _detailViewController = segue.destinationViewController;
  4047. }
  4048. if ([sender isKindOfClass:[CCMetadata class]]) {
  4049. metadata = sender;
  4050. [allRecordsDataSourceImagesVideos addObject:sender];
  4051. } else {
  4052. metadata = _metadata;
  4053. for (NSString *fileID in _sectionDataSource.allFileID) {
  4054. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4055. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4056. [allRecordsDataSourceImagesVideos addObject:metadata];
  4057. }
  4058. }
  4059. _detailViewController.metadataDetail = metadata;
  4060. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4061. _detailViewController.dateFilterQuery = nil;
  4062. _detailViewController.isCameraUpload = NO;
  4063. [_detailViewController setTitle:metadata.fileNamePrint];
  4064. }
  4065. // can i go to next viewcontroller
  4066. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4067. {
  4068. NSString *nomeDir;
  4069. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4070. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4071. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4072. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4073. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4074. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4075. viewController.delegate = self;
  4076. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4077. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4078. viewController.inputViewTitlePassword = YES;
  4079. if ([CCUtility getSimplyBlockCode]) {
  4080. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4081. viewController.passcodeInputView.maximumLength = 6;
  4082. } else {
  4083. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4084. viewController.passcodeInputView.maximumLength = 64;
  4085. }
  4086. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4087. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4088. viewController.touchIDManager = touchIDManager;
  4089. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4090. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4091. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4092. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4093. [self presentViewController:navController animated:YES completion:nil];
  4094. return;
  4095. }
  4096. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4097. else nomeDir = _metadata.fileName;
  4098. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4099. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4100. if (viewController.isViewLoaded == false) {
  4101. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4102. viewController.isFolderEncrypted = _metadata.cryptated;
  4103. viewController.serverUrl = serverUrlPush;
  4104. viewController.titleMain = _metadata.fileNamePrint;
  4105. viewController.textBackButton = _titleMain;
  4106. // save self
  4107. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4108. }
  4109. // OFF SearchBar
  4110. [viewController cancelSearchBar];
  4111. [self.navigationController pushViewController:viewController animated:YES];
  4112. }
  4113. }
  4114. @end