CCMain.m 252 KB

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