CCMain.m 250 KB

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