CCMain.m 250 KB

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