CCMain.m 250 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 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 "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCBridgeSwift.h"
  35. #define alertCreateFolder 1
  36. #define alertCreateFolderCrypto 2
  37. #define alertRename 3
  38. #define alertOfflineFolder 4
  39. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  40. {
  41. CCMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isOfflineServerUrl;
  45. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  46. BOOL _isSelectedMode;
  47. NSMutableArray *_selectedMetadatas;
  48. NSMutableArray *_queueSelector;
  49. NSUInteger _numSelectedMetadatas;
  50. UIImageView *_ImageTitleHomeCryptoCloud;
  51. UIView *_reMenuBackgroundView;
  52. UITapGestureRecognizer *_singleFingerTap;
  53. NSString *_directoryGroupBy;
  54. NSString *_directoryOrder;
  55. NSUInteger _failedAttempts;
  56. NSDate *_lockUntilDate;
  57. NSString *_fatherPermission;
  58. UIRefreshControl *_refreshControl;
  59. UIDocumentInteractionController *_docController;
  60. CCHud *_hud;
  61. CCHud *_hudDeterminate;
  62. // Datasource
  63. CCSectionDataSourceMetadata *_sectionDataSource;
  64. NSDate *_dateReadDataSource;
  65. // Search
  66. BOOL _isSearchMode;
  67. NSString *_searchFileName;
  68. NSMutableArray *_searchResultMetadatas;
  69. NSString *_depth;
  70. NSString *_noFilesSearchTitle;
  71. NSString *_noFilesSearchDescription;
  72. // Login
  73. CCLoginWeb *_loginWeb;
  74. CCLogin *_loginVC;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [CCMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedMetadatas = [NSMutableArray new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _depth = @"0";
  112. _noFilesSearchTitle = @"";
  113. _noFilesSearchDescription = @"";
  114. // delegate
  115. self.tableView.delegate = self;
  116. self.tableView.tableFooterView = [UIView new];
  117. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  118. self.tableView.emptyDataSetDelegate = self;
  119. self.tableView.emptyDataSetSource = self;
  120. self.searchController.delegate = self;
  121. self.searchController.searchBar.delegate = self;
  122. [[CCNetworking sharedNetworking] settingDelegate:self];
  123. // Custom Cell
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  126. // long press recognizer TableView
  127. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  128. [self.tableView addGestureRecognizer:longPressRecognizer];
  129. // Pull-to-Refresh
  130. [self createRefreshControl];
  131. // Register for 3D Touch Previewing if available
  132. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  133. {
  134. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  135. }
  136. // Back Button
  137. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  138. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  139. // reMenu Background
  140. _reMenuBackgroundView = [[UIView alloc] init];
  141. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  142. // if this is not Main (the Main uses inizializeMain)
  143. if (_isRoot == NO && app.activeAccount.length > 0) {
  144. // Settings this folder & delegate & Loading datasource
  145. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  146. // Load Datasource
  147. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  148. // Read Folder
  149. [self readFolderWithForced:NO serverUrl:_serverUrl];
  150. }
  151. // Title
  152. [self setTitle];
  153. // Search
  154. self.definesPresentationContext = YES;
  155. self.searchController.searchResultsUpdater = self;
  156. self.searchController.dimsBackgroundDuringPresentation = NO;
  157. self.tableView.tableHeaderView = self.searchController.searchBar;
  158. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  159. [self.searchController.searchBar sizeToFit];
  160. self.searchController.searchBar.delegate = self;
  161. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  162. if ([[NCManageDatabase sharedInstance] getServerVersionAccount:app.activeAccount] >= 12) {
  163. if (_isRoot)
  164. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  165. else
  166. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  167. } else {
  168. self.searchController.searchBar.scopeButtonTitles = nil;
  169. }
  170. // Hide Search Filed on Load
  171. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  172. }
  173. // Apparirà
  174. - (void)viewWillAppear:(BOOL)animated
  175. {
  176. [super viewWillAppear:animated];
  177. // test
  178. if (app.activeAccount.length == 0)
  179. return;
  180. // Settings this folder & delegate & Loading datasource
  181. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  182. [[CCNetworking sharedNetworking] settingDelegate:self];
  183. // Color
  184. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  185. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  186. if (_isSelectedMode)
  187. [self setUINavigationBarSelected];
  188. else
  189. [self setUINavigationBarDefault];
  190. // Plus Button
  191. [app plusButtonVisibile:true];
  192. }
  193. // E' arrivato
  194. - (void)viewDidAppear:(BOOL)animated
  195. {
  196. [super viewDidAppear:animated];
  197. // Active Main
  198. app.activeMain = self;
  199. // Test viewDidLoad
  200. if (_isViewDidLoad) {
  201. _isViewDidLoad = NO;
  202. } else {
  203. if (app.activeAccount.length > 0) {
  204. // Load Datasource
  205. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  206. // Read Folder
  207. [self readFolderWithForced:NO serverUrl:_serverUrl];
  208. }
  209. }
  210. // Title
  211. [self setTitle];
  212. }
  213. - (void)viewWillDisappear:(BOOL)animated
  214. {
  215. [super viewWillDisappear:animated];
  216. [self closeAllMenu];
  217. }
  218. - (void)didReceiveMemoryWarning
  219. {
  220. [super didReceiveMemoryWarning];
  221. // Dispose of any resources that can be recreated.
  222. }
  223. - (BOOL)prefersStatusBarHidden
  224. {
  225. return NO;
  226. }
  227. // detect scroll for remove keyboard in search mode
  228. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  229. {
  230. if (_isSearchMode && scrollView == self.tableView) {
  231. [self.searchController.searchBar endEditing:YES];
  232. }
  233. }
  234. - (void)changeTheming
  235. {
  236. if (self.isViewLoaded && self.view.window)
  237. [app changeTheming:self];
  238. // Refresh control
  239. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  240. // Reload Table View
  241. [self.tableView reloadData];
  242. }
  243. #pragma --------------------------------------------------------------------------------------------
  244. #pragma mark ===== Initizlize Mail =====
  245. #pragma --------------------------------------------------------------------------------------------
  246. - (void)initializeMain:(NSNotification *)notification
  247. {
  248. _directoryGroupBy = nil;
  249. _directoryOrder = nil;
  250. _dateReadDataSource = nil;
  251. // test
  252. if (app.activeAccount.length == 0)
  253. return;
  254. if ([app.listMainVC count] == 0 || _isRoot) {
  255. // This is Root
  256. _isRoot = YES;
  257. // Crypto Mode
  258. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  259. app.isCryptoCloudMode = NO;
  260. } else {
  261. app.isCryptoCloudMode = YES;
  262. }
  263. // go Home
  264. [self.navigationController popToRootViewControllerAnimated:NO];
  265. // Remove search mode
  266. [self cancelSearchBar];
  267. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  268. _isFolderEncrypted = NO;
  269. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  270. // add list
  271. [app.listMainVC setObject:self forKey:_serverUrl];
  272. // setting Networking
  273. [[CCNetworking sharedNetworking] settingDelegate:self];
  274. [[CCNetworking sharedNetworking] settingAccount];
  275. // populate shared Link & User variable
  276. NSArray *results = [[NCManageDatabase sharedInstance] getSharesAccount:app.activeAccount];
  277. app.sharesLink = results[0];
  278. app.sharesUserAndGroup = results[1];
  279. // Setting Theming
  280. [app settingThemingColorBrand];
  281. // Load Datasource
  282. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  283. // Load Folder
  284. [self readFolderWithForced:NO serverUrl:_serverUrl];
  285. // Load photo datasorce
  286. if (app.activePhotosCameraUpload)
  287. [app.activePhotosCameraUpload reloadDatasourceForced];
  288. // remove all of detail
  289. if (app.activeDetail)
  290. [app.activeDetail removeAllView];
  291. // remove all Notification Messages
  292. [app.listOfNotifications removeAllObjects];
  293. // home main
  294. app.homeMain = self;
  295. // Initializations
  296. [app applicationInitialized];
  297. } else {
  298. // reload datasource
  299. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  300. }
  301. }
  302. #pragma --------------------------------------------------------------------------------------------
  303. #pragma mark ==== DZNEmptyDataSetSource ====
  304. #pragma --------------------------------------------------------------------------------------------
  305. /*
  306. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  307. {
  308. if(_isSearchMode)
  309. return NO;
  310. else
  311. return YES;
  312. }
  313. */
  314. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  315. {
  316. return YES;
  317. }
  318. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  319. {
  320. return [UIColor whiteColor];
  321. }
  322. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  323. {
  324. if (_isSearchMode)
  325. return [UIImage imageNamed:@"searchBig"];
  326. else
  327. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  328. }
  329. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  330. {
  331. NSString *text;
  332. if (_isSearchMode)
  333. text = _noFilesSearchTitle;
  334. else
  335. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  336. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  337. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  338. }
  339. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  340. {
  341. NSString *text;
  342. if (_isSearchMode)
  343. text = _noFilesSearchDescription;
  344. else
  345. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  346. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  347. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  348. paragraph.alignment = NSTextAlignmentCenter;
  349. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  350. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  351. }
  352. #pragma --------------------------------------------------------------------------------------------
  353. #pragma mark ===== AlertView =====
  354. #pragma --------------------------------------------------------------------------------------------
  355. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  356. {
  357. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  358. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  359. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  360. if (alertView.tag == alertRename && buttonIndex == 1) {
  361. if ([_metadata.model isEqualToString:@"note"]) {
  362. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  363. } else {
  364. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  365. }
  366. }
  367. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  368. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  369. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  370. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  371. [self performSelector:@selector(reloadDatasource) withObject:nil];
  372. }
  373. }
  374. // accept only number char > 0
  375. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  376. {
  377. /* Retrieve a text field at an index -
  378. raises NSRangeException when textFieldIndex is out-of-bounds.
  379. The field at index 0 will be the first text field
  380. (the single field or the login field),
  381. The field at index 1 will be the password field. */
  382. /*
  383. 1> Get the Text Field in alertview
  384. 2> Get the text of that Text Field
  385. 3> Verify that text length
  386. 4> return YES or NO Based on the length
  387. */
  388. if (alertView.tag == alertOfflineFolder) return YES;
  389. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  390. }
  391. #pragma --------------------------------------------------------------------------------------------
  392. #pragma mark ===== Graphic Window =====
  393. #pragma --------------------------------------------------------------------------------------------
  394. - (void)createRefreshControl
  395. {
  396. _refreshControl = [UIRefreshControl new];
  397. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  398. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  399. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  400. [self setRefreshControl:_refreshControl];
  401. }
  402. - (void)deleteRefreshControl
  403. {
  404. [_refreshControl endRefreshing];
  405. self.refreshControl = nil;
  406. }
  407. - (void)refreshControlTarget
  408. {
  409. [self readFolderWithForced:YES serverUrl:_serverUrl];
  410. // Actuate `Peek` feedback (weak boom)
  411. AudioServicesPlaySystemSound(1519);
  412. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  413. }
  414. - (void)setTitle
  415. {
  416. // Color text self.navigationItem.title
  417. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  418. if (_isSelectedMode) {
  419. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  420. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  421. self.navigationItem.titleView = nil;
  422. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  423. } else {
  424. // we are in home : LOGO BRAND
  425. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  426. self.navigationItem.title = nil;
  427. if ([app.reachability isReachable] == NO)
  428. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  429. else
  430. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"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:@"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:@"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:@"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 ([NCBrandOptions sharedInstance].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. [[NCManageDatabase sharedInstance] deleteExternalSitesForAccount:app.activeAccount];
  803. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  804. [[NCManageDatabase sharedInstance] 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 ([NCBrandOptions sharedInstance].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. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2112. // change account ?
  2113. TableAccount *record = [CCCoreData getActiveAccount];
  2114. if([record.account isEqualToString:metadataNet.account] == NO)
  2115. return;
  2116. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items account:appDelegate.activeAccount activeUrl:appDelegate.activeUrl];
  2117. appDelegate.sharesLink = result[0];
  2118. appDelegate.sharesUserAndGroup = result[1];
  2119. if (openWindow) {
  2120. if (_shareOC) {
  2121. [_shareOC reloadData];
  2122. } else {
  2123. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2124. // Apriamo la view
  2125. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2126. _shareOC.delegate = self;
  2127. _shareOC.metadata = metadata;
  2128. _shareOC.serverUrl = metadataNet.serverUrl;
  2129. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2130. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2131. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2132. [self presentViewController:_shareOC animated:YES completion:nil];
  2133. }
  2134. }
  2135. [self tableViewReload];
  2136. }
  2137. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2138. {
  2139. [_hud hideHud];
  2140. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2141. if (_shareOC)
  2142. [_shareOC reloadData];
  2143. [self tableViewReload];
  2144. if (errorCode == 401)
  2145. [self changePasswordAccount];
  2146. }
  2147. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2148. {
  2149. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2150. metadataNet.action = actionShare;
  2151. metadataNet.fileID = metadata.fileID;
  2152. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2153. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2154. metadataNet.password = password;
  2155. metadataNet.selector = selectorShare;
  2156. metadataNet.serverUrl = serverUrl;
  2157. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2158. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2159. }
  2160. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2161. {
  2162. [_hud hideHud];
  2163. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2164. // rimuoviamo la condivisione da db
  2165. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup account:appDelegate.activeAccount];
  2166. appDelegate.sharesLink = result[0];
  2167. appDelegate.sharesUserAndGroup = result[1];
  2168. if (_shareOC)
  2169. [_shareOC reloadData];
  2170. [self tableViewReload];
  2171. }
  2172. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2173. {
  2174. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2175. metadataNet.action = actionUnShare;
  2176. metadataNet.fileID = metadata.fileID;
  2177. metadataNet.fileName = metadata.fileName;
  2178. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2179. metadataNet.selector = selectorUnshare;
  2180. metadataNet.serverUrl = serverUrl;
  2181. metadataNet.share = share;
  2182. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2183. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2184. }
  2185. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2186. {
  2187. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2188. metadataNet.action = actionUpdateShare;
  2189. metadataNet.fileID = metadata.fileID;
  2190. metadataNet.expirationTime = expirationTime;
  2191. metadataNet.password = password;
  2192. metadataNet.selector = selectorUpdateShare;
  2193. metadataNet.serverUrl = serverUrl;
  2194. metadataNet.share = share;
  2195. metadataNet.sharePermission = permission;
  2196. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2197. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2198. }
  2199. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2200. {
  2201. [_hud hideHud];
  2202. if (_shareOC)
  2203. [_shareOC reloadUserAndGroup:items];
  2204. }
  2205. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2206. {
  2207. [_hud hideHud];
  2208. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2209. }
  2210. - (void)getUserAndGroup:(NSString *)find
  2211. {
  2212. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2213. metadataNet.action = actionGetUserAndGroup;
  2214. metadataNet.options = find;
  2215. metadataNet.selector = selectorGetUserAndGroup;
  2216. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2217. [_hud visibleIndeterminateHud];
  2218. }
  2219. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2220. {
  2221. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2222. metadataNet.action = actionShareWith;
  2223. metadataNet.fileID = metadata.fileID;
  2224. metadataNet.directoryID = directoryID;
  2225. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2226. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2227. metadataNet.serverUrl = serverUrl;
  2228. metadataNet.selector = selectorShare;
  2229. metadataNet.share = user;
  2230. metadataNet.shareeType = shareeType;
  2231. metadataNet.sharePermission = permission;
  2232. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2233. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2234. }
  2235. - (void)openWindowShare:(CCMetadata *)metadata
  2236. {
  2237. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2238. metadataNet.action = actionReadShareServer;
  2239. metadataNet.fileID = metadata.fileID;
  2240. metadataNet.fileName = metadata.fileName;
  2241. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2242. metadataNet.selector = selectorOpenWindowShare;
  2243. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2244. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2245. [_hud visibleIndeterminateHud];
  2246. }
  2247. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2248. {
  2249. CGPoint location = [tapGesture locationInView:self.tableView];
  2250. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2251. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2252. if (metadata)
  2253. [self openWindowShare:metadata];
  2254. }
  2255. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2256. {
  2257. CGPoint location = [tapGesture locationInView:self.tableView];
  2258. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2259. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2260. if (metadata) {
  2261. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2262. vc.metadata = metadata;
  2263. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2264. [self presentViewController:vc animated:YES completion:nil];
  2265. }
  2266. }
  2267. #pragma --------------------------------------------------------------------------------------------
  2268. #pragma mark ===== Favorite =====
  2269. #pragma --------------------------------------------------------------------------------------------
  2270. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2271. {
  2272. [CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2273. _dateReadDataSource = nil;
  2274. if (_isSearchMode)
  2275. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2276. else
  2277. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2278. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2279. if (metadata.directory && metadata.favorite) {
  2280. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2281. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2282. }
  2283. }
  2284. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2285. {
  2286. }
  2287. - (void)addFavorite:(CCMetadata *)metadata
  2288. {
  2289. if (metadata.directory) {
  2290. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2291. } else {
  2292. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2293. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2294. }
  2295. }
  2296. - (void)removeFavorite:(CCMetadata *)metadata
  2297. {
  2298. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2299. }
  2300. #pragma --------------------------------------------------------------------------------------------
  2301. #pragma mark ===== Offline =====
  2302. #pragma --------------------------------------------------------------------------------------------
  2303. - (void)addOffline:(CCMetadata *)metadata
  2304. {
  2305. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2306. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2307. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2308. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2309. }
  2310. - (void)removeOffline:(CCMetadata *)metadata
  2311. {
  2312. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2313. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2314. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2315. }
  2316. #pragma --------------------------------------------------------------------------------------------
  2317. #pragma mark ===== Local =====
  2318. #pragma --------------------------------------------------------------------------------------------
  2319. - (void)addLocal:(CCMetadata *)metadata
  2320. {
  2321. if (metadata.errorPasscode || !metadata.uuid) return;
  2322. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2323. if ([metadata.type isEqualToString: k_metadataType_file])
  2324. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2325. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2326. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2327. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2328. }
  2329. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2330. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2331. }
  2332. #pragma --------------------------------------------------------------------------------------------
  2333. #pragma mark ===== Open in... =====
  2334. #pragma --------------------------------------------------------------------------------------------
  2335. - (void)openIn:(CCMetadata *)metadata
  2336. {
  2337. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2338. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2339. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2340. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2341. }
  2342. #pragma --------------------------------------------------------------------------------------------
  2343. #pragma mark ===== Remove Local File =====
  2344. #pragma --------------------------------------------------------------------------------------------
  2345. - (void)removeLocalFile:(CCMetadata *)metadata
  2346. {
  2347. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2348. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2349. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2350. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2351. }
  2352. #pragma --------------------------------------------------------------------------------------------
  2353. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2354. #pragma --------------------------------------------------------------------------------------------
  2355. - (void)orderTable:(NSString *)order
  2356. {
  2357. [CCUtility setOrderSettings:order];
  2358. // Clear data-read of DataSource
  2359. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2360. }
  2361. - (void)ascendingTable:(BOOL)ascending
  2362. {
  2363. [CCUtility setAscendingSettings:ascending];
  2364. // Clear data-read of DataSource
  2365. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2366. }
  2367. - (void)directoryOnTop:(BOOL)directoryOnTop
  2368. {
  2369. [CCUtility setDirectoryOnTop:directoryOnTop];
  2370. // Clear data-read of DataSource
  2371. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2372. }
  2373. - (void)tableGroupBy:(NSString *)groupBy
  2374. {
  2375. [CCUtility setGroupBySettings:groupBy];
  2376. // Clear data-read of DataSource
  2377. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2378. }
  2379. #pragma --------------------------------------------------------------------------------------------
  2380. #pragma mark ==== Menu LOGO ====
  2381. #pragma --------------------------------------------------------------------------------------------
  2382. - (void)menuLogo
  2383. {
  2384. // Test crash
  2385. //[[Crashlytics sharedInstance] crash];
  2386. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2387. return;
  2388. // Brand
  2389. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2390. return;
  2391. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2392. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2393. return;
  2394. }
  2395. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2396. NSMutableArray *menuArray = [NSMutableArray new];
  2397. for (TableAccount *record in listTableAccount) {
  2398. if ([record.account isEqualToString:app.activeAccount]) continue;
  2399. CCMenuItem *item = [[CCMenuItem alloc] init];
  2400. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2401. item.argument = record.account;
  2402. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2403. item.target = self;
  2404. item.action = @selector(changeDefaultAccount:);
  2405. [menuArray addObject:item];
  2406. }
  2407. if ([menuArray count] == 0)
  2408. return;
  2409. OptionalConfiguration options;
  2410. Color textColor, backgroundColor;
  2411. textColor.R = 0;
  2412. textColor.G = 0;
  2413. textColor.B = 0;
  2414. backgroundColor.R = 1;
  2415. backgroundColor.G = 1;
  2416. backgroundColor.B = 1;
  2417. NSInteger originY = 60;
  2418. options.arrowSize = 9;
  2419. options.marginXSpacing = 7;
  2420. options.marginYSpacing = 10;
  2421. options.intervalSpacing = 20;
  2422. options.menuCornerRadius = 6.5;
  2423. options.maskToBackground = NO;
  2424. options.shadowOfMenu = YES;
  2425. options.hasSeperatorLine = YES;
  2426. options.seperatorLineHasInsets = YES;
  2427. options.textColor = textColor;
  2428. options.menuBackgroundColor = backgroundColor;
  2429. CGRect rect = self.view.frame;
  2430. rect.origin.y = rect.origin.y + originY;
  2431. rect.size.height = rect.size.height - originY;
  2432. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2433. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2434. }
  2435. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2436. {
  2437. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2438. // STOP, erase all in queue networking
  2439. [app cancelAllOperations];
  2440. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2441. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2442. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2443. if (tableAccount)
  2444. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2445. // go to home sweet home
  2446. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2447. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2448. });
  2449. }
  2450. #pragma --------------------------------------------------------------------------------------------
  2451. #pragma mark ==== ReMenu ====
  2452. #pragma --------------------------------------------------------------------------------------------
  2453. - (void)createReMenuBackgroundView:(REMenu *)menu
  2454. {
  2455. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2456. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2457. [UIView animateWithDuration:0.2 animations:^{
  2458. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2459. if (height < self.tabBarController.tabBar.frame.size.height)
  2460. height = self.tabBarController.tabBar.frame.size.height;
  2461. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2462. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2463. }];
  2464. }
  2465. - (void)createReMainMenu
  2466. {
  2467. NSString *ordinamento;
  2468. NSString *groupBy = _directoryGroupBy;
  2469. __block NSString *nuovoOrdinamento;
  2470. NSString *titoloNuovo, *titoloAttuale;
  2471. BOOL ascendente;
  2472. __block BOOL nuovoAscendente;
  2473. UIImage *image;
  2474. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2475. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2476. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2477. [self tableViewSelect:YES];
  2478. }
  2479. }];
  2480. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2481. ordinamento = _directoryOrder;
  2482. if ([ordinamento isEqualToString:@"fileName"]) {
  2483. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2484. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2485. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2486. nuovoOrdinamento = @"fileDate";
  2487. }
  2488. if ([ordinamento isEqualToString:@"fileDate"]) {
  2489. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2490. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2491. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2492. nuovoOrdinamento = @"fileName";
  2493. }
  2494. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2495. [self orderTable:nuovoOrdinamento];
  2496. }];
  2497. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2498. ascendente = [CCUtility getAscendingSettings];
  2499. if (ascendente) {
  2500. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2501. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2502. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2503. nuovoAscendente = false;
  2504. }
  2505. if (!ascendente) {
  2506. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2507. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2508. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2509. nuovoAscendente = true;
  2510. }
  2511. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2512. [self ascendingTable:nuovoAscendente];
  2513. }];
  2514. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2515. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2516. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2517. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2518. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2519. else [self tableGroupBy:@"alphabetic"];
  2520. }];
  2521. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2522. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2523. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2524. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2525. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2526. else [self tableGroupBy:@"typefile"];
  2527. }];
  2528. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2529. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2530. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2531. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2532. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2533. else [self tableGroupBy:@"date"];
  2534. }];
  2535. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2536. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2537. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2538. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2539. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2540. else [self directoryOnTop:YES];
  2541. }];
  2542. // REMENU --------------------------------------------------------------------------------------------------------------
  2543. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2544. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2545. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2546. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2547. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2548. app.reMainMenu.separatorHeight = 0.5;
  2549. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2550. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2551. app.reMainMenu.textColor = [UIColor blackColor];
  2552. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2553. app.reMainMenu.textShadowColor = nil;
  2554. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2555. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2556. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2557. app.reMainMenu.highlightedSeparatorColor = nil;
  2558. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2559. app.reMainMenu.highlightedTextShadowColor = nil;
  2560. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2561. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2562. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2563. app.reMainMenu.subtitleTextShadowColor = nil;
  2564. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2565. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2566. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2567. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2568. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2569. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2570. app.reMainMenu.borderWidth = 0.3;
  2571. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2572. app.reMainMenu.animationDuration = 0.2;
  2573. app.reMainMenu.closeAnimationDuration = 0.2;
  2574. app.reMainMenu.bounce = NO;
  2575. [app.reMainMenu setClosePreparationBlock:^{
  2576. // Backgroun reMenu (Gesture)
  2577. [_reMenuBackgroundView removeFromSuperview];
  2578. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2579. }];
  2580. }
  2581. - (void)toggleReMainMenu
  2582. {
  2583. if (app.reMainMenu.isOpen) {
  2584. [app.reMainMenu close];
  2585. } else {
  2586. [self createReMainMenu];
  2587. [app.reMainMenu showFromNavigationController:self.navigationController];
  2588. // Backgroun reMenu & (Gesture)
  2589. [self createReMenuBackgroundView:app.reMainMenu];
  2590. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2591. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2592. }
  2593. }
  2594. - (void)createReSelectMenu
  2595. {
  2596. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2597. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2598. [self deleteSelectionFile];
  2599. }];
  2600. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2601. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2602. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2603. }];
  2604. if (app.isCryptoCloudMode) {
  2605. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2606. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2607. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2608. }];
  2609. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2610. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2611. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2612. }];
  2613. }
  2614. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2615. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2616. [self downloadSelectedFiles];
  2617. }];
  2618. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2619. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2620. [self saveSelectedFiles];
  2621. }];
  2622. // REMENU --------------------------------------------------------------------------------------------------------------
  2623. if (app.isCryptoCloudMode) {
  2624. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2625. } else {
  2626. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2627. }
  2628. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2629. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2630. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2631. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2632. app.reSelectMenu.separatorHeight = 0.5;
  2633. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2634. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2635. app.reSelectMenu.textColor = [UIColor blackColor];
  2636. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2637. app.reSelectMenu.textShadowColor = nil;
  2638. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2639. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2640. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2641. app.reSelectMenu.highlightedSeparatorColor = nil;
  2642. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2643. app.reSelectMenu.highlightedTextShadowColor = nil;
  2644. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2645. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2646. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2647. app.reSelectMenu.subtitleTextShadowColor = nil;
  2648. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2649. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2650. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2651. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2652. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2653. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2654. app.reSelectMenu.borderWidth = 0.3;
  2655. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2656. app.reSelectMenu.closeAnimationDuration = 0.2;
  2657. app.reSelectMenu.animationDuration = 0.2;
  2658. app.reSelectMenu.bounce = NO;
  2659. [app.reSelectMenu setClosePreparationBlock:^{
  2660. // Backgroun reMenu (Gesture)
  2661. [_reMenuBackgroundView removeFromSuperview];
  2662. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2663. }];
  2664. }
  2665. - (void)toggleReSelectMenu
  2666. {
  2667. if (app.reSelectMenu.isOpen) {
  2668. [app.reSelectMenu close];
  2669. } else {
  2670. [self createReSelectMenu];
  2671. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2672. // Backgroun reMenu & (Gesture)
  2673. [self createReMenuBackgroundView:app.reSelectMenu];
  2674. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2675. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2676. }
  2677. }
  2678. #pragma --------------------------------------------------------------------------------------------
  2679. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2680. #pragma --------------------------------------------------------------------------------------------
  2681. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2682. {
  2683. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2684. UITableView *tableView = (UITableView*)self.view;
  2685. CGPoint touchPoint = [recognizer locationInView:self.view];
  2686. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2687. if (indexPath)
  2688. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2689. else
  2690. _metadata = nil;
  2691. [self becomeFirstResponder];
  2692. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2693. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2694. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2695. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2696. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2697. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2698. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2699. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2700. if (app.isCryptoCloudMode)
  2701. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2702. else
  2703. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2704. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2705. [menuController setMenuVisible:YES animated:YES];
  2706. }
  2707. }
  2708. - (BOOL)canBecomeFirstResponder
  2709. {
  2710. return YES;
  2711. }
  2712. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2713. {
  2714. // For copy file, copy files, Open in ... :
  2715. //
  2716. // NO Directory
  2717. // NO Error Passcode
  2718. // NO In Session mode (download/upload)
  2719. // NO Template
  2720. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2721. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2722. // NO Cryptated with Title lenght = 0
  2723. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2724. return YES;
  2725. }
  2726. return NO;
  2727. }
  2728. if (@selector(copyFiles:) == action) {
  2729. if (_isSelectedMode) {
  2730. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2731. for (CCMetadata *metadata in selectedMetadatas) {
  2732. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2733. // NO Cryptated with Title lenght = 0
  2734. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2735. return YES;
  2736. }
  2737. }
  2738. }
  2739. return NO;
  2740. }
  2741. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2742. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2743. NSArray *items = [pasteboard items];
  2744. if ([items count] == 1) {
  2745. // Value : (NSData) metadata
  2746. NSDictionary *dic = [items objectAtIndex:0];
  2747. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2748. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2749. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2750. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2751. if (directoryUser) {
  2752. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2753. return YES;
  2754. }
  2755. return NO;
  2756. } else return NO;
  2757. }
  2758. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2759. BOOL isValid = NO;
  2760. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2761. NSArray *items = [pasteboard items];
  2762. if ([items count] <= 1) return NO;
  2763. for (NSDictionary *dic in items) {
  2764. // Value : (NSData) metadata
  2765. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2766. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2767. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2768. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2769. if (directoryUser) {
  2770. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2771. isValid = YES;
  2772. }
  2773. }
  2774. return isValid;
  2775. }
  2776. return NO;
  2777. }
  2778. /************************************ COPY ************************************/
  2779. - (void)copyFile:(id)sender
  2780. {
  2781. // Remove all item
  2782. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2783. pasteboard.items = [[NSArray alloc] init];
  2784. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2785. [self copyFileToPasteboard:_metadata];
  2786. } else {
  2787. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2788. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2789. }
  2790. }
  2791. - (void)copyFiles:(id)sender
  2792. {
  2793. // Remove all item
  2794. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2795. pasteboard.items = [[NSArray alloc] init];
  2796. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2797. for (CCMetadata *metadata in selectedMetadatas) {
  2798. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2799. [self copyFileToPasteboard:metadata];
  2800. } else {
  2801. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2802. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2803. }
  2804. }
  2805. [self tableViewSelect:NO];
  2806. }
  2807. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2808. {
  2809. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2810. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2811. // Value : (NSData) metadata
  2812. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2813. [items addObject:item];
  2814. [pasteboard setItems:items];
  2815. }
  2816. /************************************ OPEN IN ... ************************************/
  2817. - (void)openinFile:(id)sender
  2818. {
  2819. [self openIn:_metadata];
  2820. }
  2821. /************************************ PASTE ************************************/
  2822. - (void)pasteFile:(id)sender
  2823. {
  2824. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2825. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2826. }
  2827. - (void)pasteFileEncrypted:(id)sender
  2828. {
  2829. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2830. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2831. }
  2832. - (void)pasteFiles:(id)sender
  2833. {
  2834. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2835. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2836. }
  2837. - (void)pasteFilesEncrypted:(id)sender
  2838. {
  2839. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2840. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2841. }
  2842. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2843. {
  2844. for (NSDictionary *dic in items) {
  2845. // Value : (NSData) metadata
  2846. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2847. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2848. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2849. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2850. if (directoryUser) {
  2851. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2852. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2853. [[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];
  2854. }
  2855. }
  2856. }
  2857. }
  2858. #pragma --------------------------------------------------------------------------------------------
  2859. #pragma mark ===== Lock Passcode =====
  2860. #pragma --------------------------------------------------------------------------------------------
  2861. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2862. {
  2863. return _failedAttempts;
  2864. }
  2865. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2866. {
  2867. return _lockUntilDate;
  2868. }
  2869. - (void)passcodeViewCloseButtonPressed:(id)sender
  2870. {
  2871. [self dismissViewControllerAnimated:YES completion:nil];
  2872. }
  2873. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2874. {
  2875. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2876. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2877. _lockUntilDate = nil;
  2878. _failedAttempts = 0;
  2879. aResultHandler(YES);
  2880. } else aResultHandler(NO);
  2881. } else aResultHandler(YES);
  2882. }
  2883. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2884. {
  2885. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2886. switch (aViewController.type) {
  2887. case BKPasscodeViewControllerCheckPasscodeType: {
  2888. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2889. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2890. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2891. // scriviamo il passcode
  2892. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2893. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2894. } else {
  2895. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2896. [alertView show];
  2897. }
  2898. }
  2899. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2900. // possiamo procedere alla prossima directory
  2901. [self performSegueDirectoryWithControlPasscode:false];
  2902. // avviamo la sessione Passcode Lock con now
  2903. app.sessionePasscodeLock = [NSDate date];
  2904. }
  2905. // disattivazione lock cartella
  2906. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2907. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2908. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2909. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2910. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2911. }
  2912. [self.tableView reloadData];
  2913. }
  2914. }
  2915. break;
  2916. default:
  2917. break;
  2918. }
  2919. }
  2920. - (void)comandoLockPassword
  2921. {
  2922. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2923. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2924. // se non è abilitato il Lock Passcode esci
  2925. if ([[CCUtility getBlockCode] length] == 0) {
  2926. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2927. [alertView show];
  2928. return;
  2929. }
  2930. // se è richiesta la disattivazione si chiede la password
  2931. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2932. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2933. viewController.delegate = self;
  2934. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2935. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2936. viewController.inputViewTitlePassword = YES;
  2937. if ([CCUtility getSimplyBlockCode]) {
  2938. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2939. viewController.passcodeInputView.maximumLength = 6;
  2940. } else {
  2941. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2942. viewController.passcodeInputView.maximumLength = 64;
  2943. }
  2944. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2945. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2946. viewController.touchIDManager = touchIDManager;
  2947. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2948. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2949. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2950. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2951. [self presentViewController:navigationController animated:YES completion:nil];
  2952. return;
  2953. }
  2954. // ---------------- ACTIVATE PASSWORD
  2955. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2956. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2957. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2958. } else {
  2959. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2960. }
  2961. }
  2962. #pragma mark -
  2963. #pragma --------------------------------------------------------------------------------------------
  2964. #pragma mark ===== Swipe Tablet -> menu =====
  2965. #pragma --------------------------------------------------------------------------------------------
  2966. // more
  2967. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2968. return NSLocalizedString(@"_more_", nil);
  2969. }
  2970. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2971. {
  2972. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2973. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2974. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  2975. BOOL offlineFolder = NO;
  2976. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2977. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2978. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2979. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2980. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2981. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  2982. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2983. offlineFolder = YES;
  2984. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2985. if (_metadata.favorite) {
  2986. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2987. } else {
  2988. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2989. }
  2990. if (_metadata.directory) {
  2991. // calcolo lockServerUrl
  2992. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2993. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2994. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2995. }
  2996. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  2997. /******************************************* AHKActionSheet *******************************************/
  2998. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  2999. actionSheet.animationDuration = 0.2;
  3000. actionSheet.blurRadius = 0.0f;
  3001. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3002. actionSheet.buttonHeight = 50.0;
  3003. actionSheet.cancelButtonHeight = 50.0f;
  3004. actionSheet.separatorHeight = 5.0f;
  3005. actionSheet.automaticallyTintButtonImages = @(NO);
  3006. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3007. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3008. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3009. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3010. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3011. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3012. /******************************************* DIRECTORY *******************************************/
  3013. if (_metadata.directory) {
  3014. BOOL lockDirectory = NO;
  3015. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3016. // Directory bloccata ?
  3017. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3018. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3019. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3020. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3021. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3022. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3023. height: 50.0
  3024. type: AHKActionSheetButtonTypeDisabled
  3025. handler: nil
  3026. ];
  3027. if (!lockDirectory && !_metadata.cryptated) {
  3028. [actionSheet addButtonWithTitle:titleFavorite
  3029. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3030. backgroundColor:[UIColor whiteColor]
  3031. height: 50.0
  3032. type:AHKActionSheetButtonTypeDefault
  3033. handler:^(AHKActionSheet *as) {
  3034. // close swipe
  3035. [self setEditing:NO animated:YES];
  3036. if (_metadata.favorite)
  3037. [self removeFavorite:_metadata];
  3038. else
  3039. [self addFavorite:_metadata];
  3040. }];
  3041. }
  3042. if (_metadata.cryptated == NO && !lockDirectory) {
  3043. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3044. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3045. backgroundColor:[UIColor whiteColor]
  3046. height: 50.0
  3047. type:AHKActionSheetButtonTypeDefault
  3048. handler:^(AHKActionSheet *as) {
  3049. // close swipe
  3050. [self setEditing:NO animated:YES];
  3051. [self openWindowShare:_metadata];
  3052. }];
  3053. }
  3054. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3055. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3056. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3057. backgroundColor:[UIColor whiteColor]
  3058. height: 50.0
  3059. type:AHKActionSheetButtonTypeDefault
  3060. handler:^(AHKActionSheet *as) {
  3061. // close swipe
  3062. [self setEditing:NO animated:YES];
  3063. //chiediamo il nome del file
  3064. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3065. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3066. alertView.tag = alertRename;
  3067. UITextField *textField = [alertView textFieldAtIndex:0];
  3068. textField.text = _metadata.fileNamePrint;
  3069. [alertView show];
  3070. }];
  3071. }
  3072. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3073. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3074. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3075. backgroundColor:[UIColor whiteColor]
  3076. height: 50.0
  3077. type:AHKActionSheetButtonTypeDefault
  3078. handler:^(AHKActionSheet *as) {
  3079. // close swipe
  3080. [self setEditing:NO animated:YES];
  3081. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3082. }];
  3083. }
  3084. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3085. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3086. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3087. backgroundColor:[UIColor whiteColor]
  3088. height: 50.0
  3089. type:AHKActionSheetButtonTypeDefault
  3090. handler:^(AHKActionSheet *as) {
  3091. // close swipe
  3092. [self setEditing:NO animated:YES];
  3093. // Settings new folder Automatatic upload
  3094. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3095. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3096. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3097. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3098. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3099. [app.activePhotosCameraUpload reloadDatasourceForced];
  3100. [self readFolderWithForced:YES serverUrl:serverUrl];
  3101. NSLog(@"[LOG] Update Folder Photo");
  3102. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3103. if ([folderCameraUpload length] > 0)
  3104. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3105. }];
  3106. }
  3107. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3108. [actionSheet addButtonWithTitle:titoloLock
  3109. image:[UIImage imageNamed:@"actionSheetLock"]
  3110. backgroundColor:[UIColor whiteColor]
  3111. height: 50.0
  3112. type:AHKActionSheetButtonTypeEncrypted
  3113. handler:^(AHKActionSheet *as) {
  3114. // close swipe
  3115. [self setEditing:NO animated:YES];
  3116. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3117. }];
  3118. }
  3119. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3120. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3121. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3122. backgroundColor:[UIColor whiteColor]
  3123. height: 50.0
  3124. type:AHKActionSheetButtonTypeEncrypted
  3125. handler:^(AHKActionSheet *as) {
  3126. // close swipe
  3127. [self setEditing:NO animated:YES];
  3128. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3129. }];
  3130. }
  3131. [actionSheet show];
  3132. }
  3133. /******************************************* FILE *******************************************/
  3134. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3135. UIImage *iconHeader;
  3136. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3137. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3138. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3139. else
  3140. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3141. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3142. image: iconHeader
  3143. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3144. height: 50.0
  3145. type: AHKActionSheetButtonTypeDisabled
  3146. handler: nil
  3147. ];
  3148. if (!_metadata.cryptated) {
  3149. [actionSheet addButtonWithTitle:titleFavorite
  3150. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3151. backgroundColor:[UIColor whiteColor]
  3152. height: 50.0
  3153. type:AHKActionSheetButtonTypeDefault
  3154. handler:^(AHKActionSheet *as) {
  3155. // close swipe
  3156. [self setEditing:NO animated:YES];
  3157. if (_metadata.favorite)
  3158. [self removeFavorite:_metadata];
  3159. else
  3160. [self addFavorite:_metadata];
  3161. }];
  3162. }
  3163. if (_metadata.cryptated == NO) {
  3164. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3165. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3166. backgroundColor:[UIColor whiteColor]
  3167. height: 50.0
  3168. type:AHKActionSheetButtonTypeDefault
  3169. handler:^(AHKActionSheet *as) {
  3170. // close swipe
  3171. [self setEditing:NO animated:YES];
  3172. [self openWindowShare:_metadata];
  3173. }];
  3174. }
  3175. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3176. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3177. backgroundColor:[UIColor whiteColor]
  3178. height: 50.0
  3179. type:AHKActionSheetButtonTypeDefault
  3180. handler:^(AHKActionSheet *as) {
  3181. // close swipe
  3182. [self setEditing:NO animated:YES];
  3183. [self performSelector:@selector(openIn:) withObject:_metadata];
  3184. }];
  3185. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3186. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3187. backgroundColor:[UIColor whiteColor]
  3188. height: 50.0
  3189. type:AHKActionSheetButtonTypeDefault
  3190. handler:^(AHKActionSheet *as) {
  3191. // close swipe
  3192. [self setEditing:NO animated:YES];
  3193. //chiediamo il nome del file
  3194. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3195. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3196. alertView.tag = alertRename;
  3197. UITextField *textField = [alertView textFieldAtIndex:0];
  3198. textField.text = _metadata.fileNamePrint;
  3199. [alertView show];
  3200. }];
  3201. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3202. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3203. backgroundColor:[UIColor whiteColor]
  3204. height: 50.0
  3205. type:AHKActionSheetButtonTypeDefault
  3206. handler:^(AHKActionSheet *as) {
  3207. // close swipe
  3208. [self setEditing:NO animated:YES];
  3209. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3210. }];
  3211. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3212. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3213. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3214. backgroundColor:[UIColor whiteColor]
  3215. height: 50.0
  3216. type:AHKActionSheetButtonTypeDefault
  3217. handler:^(AHKActionSheet *as) {
  3218. // close swipe
  3219. [self setEditing:NO animated:YES];
  3220. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3221. }];
  3222. }
  3223. if (app.isCryptoCloudMode) {
  3224. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3225. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3226. backgroundColor:[UIColor whiteColor]
  3227. height: 50.0
  3228. type:AHKActionSheetButtonTypeEncrypted
  3229. handler:^(AHKActionSheet *as) {
  3230. // close swipe
  3231. [self setEditing:NO animated:YES];
  3232. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3233. }];
  3234. }
  3235. [actionSheet show];
  3236. }
  3237. /******************************************* TEMPLATE *******************************************/
  3238. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3239. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3240. image: [UIImage imageNamed:_metadata.iconName]
  3241. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3242. height: 50.0
  3243. type: AHKActionSheetButtonTypeDisabled
  3244. handler: nil
  3245. ];
  3246. if ([_metadata.model isEqualToString:@"note"]) {
  3247. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3248. image:[UIImage imageNamed:@"actionSheetRename"]
  3249. backgroundColor:[UIColor whiteColor]
  3250. height: 50.0
  3251. type:AHKActionSheetButtonTypeDefault
  3252. handler:^(AHKActionSheet *as) {
  3253. // close swipe
  3254. [self setEditing:NO animated:YES];
  3255. //chiediamo il nome del file
  3256. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3257. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3258. alertView.tag = alertRename;
  3259. UITextField *textField = [alertView textFieldAtIndex:0];
  3260. textField.text = _metadata.fileNamePrint;
  3261. [alertView show];
  3262. }];
  3263. }
  3264. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3265. image:[UIImage imageNamed:@"actionSheetMove"]
  3266. backgroundColor:[UIColor whiteColor]
  3267. height: 50.0
  3268. type:AHKActionSheetButtonTypeDefault
  3269. handler:^(AHKActionSheet *as) {
  3270. // close swipe
  3271. [self setEditing:NO animated:YES];
  3272. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3273. }];
  3274. [actionSheet show];
  3275. }
  3276. }
  3277. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3278. {
  3279. return NSLocalizedString(@"_delete_", nil);
  3280. }
  3281. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3282. {
  3283. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3284. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3285. else return YES;
  3286. }
  3287. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3288. {
  3289. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3290. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3291. else return UITableViewCellEditingStyleDelete;
  3292. }
  3293. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3294. {
  3295. BOOL lockDirectory = NO;
  3296. // Directory locked ?
  3297. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3298. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3299. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3300. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3301. return;
  3302. }
  3303. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3304. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3305. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3306. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3307. style:UIAlertActionStyleDestructive
  3308. handler:^(UIAlertAction *action) {
  3309. [self performSelector:@selector(deleteFile) withObject:nil];
  3310. }]];
  3311. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3312. style:UIAlertActionStyleCancel
  3313. handler:^(UIAlertAction *action) {
  3314. [alertController dismissViewControllerAnimated:YES completion:nil];
  3315. }]];
  3316. alertController.popoverPresentationController.sourceView = self.view;
  3317. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3318. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3319. [alertController.view layoutIfNeeded];
  3320. [self presentViewController:alertController animated:YES completion:nil];
  3321. }
  3322. }
  3323. #pragma --------------------------------------------------------------------------------------------
  3324. #pragma mark - ==== Datasource ====
  3325. #pragma --------------------------------------------------------------------------------------------
  3326. - (void)clearDateReadDataSource:(NSNotification *)notification
  3327. {
  3328. _dateReadDataSource = Nil;
  3329. [self reloadDatasource];
  3330. }
  3331. - (void)reloadDatasource
  3332. {
  3333. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3334. }
  3335. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3336. {
  3337. // test
  3338. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3339. return;
  3340. // Search Mode
  3341. if(_isSearchMode) {
  3342. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3343. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3344. } else {
  3345. [self readFolderWithForced:NO serverUrl:serverUrl];
  3346. }
  3347. [self tableViewReload];
  3348. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3349. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3350. _noFilesSearchDescription = @"";
  3351. }
  3352. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3353. _noFilesSearchTitle = @"";
  3354. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3355. }
  3356. [self.tableView reloadEmptyDataSet];
  3357. return;
  3358. }
  3359. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3360. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3361. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3362. [app.activeTransfers reloadDatasource];
  3363. } else {
  3364. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3365. if (main) {
  3366. [main reloadDatasource];
  3367. } else {
  3368. [self tableViewReload];
  3369. [app.activeTransfers reloadDatasource];
  3370. }
  3371. }
  3372. return;
  3373. }
  3374. // Offline folder ?
  3375. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3376. [app.activeTransfers reloadDatasource];
  3377. // Settaggio variabili per le ottimizzazioni
  3378. _directoryGroupBy = [CCUtility getGroupBySettings];
  3379. _directoryOrder = [CCUtility getOrderSettings];
  3380. // Controllo data lettura Data Source
  3381. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3382. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3383. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3384. _dateReadDataSource = [NSDate date];
  3385. // Data Source
  3386. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3387. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3388. } else {
  3389. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3390. }
  3391. [self tableViewReload];
  3392. }
  3393. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3394. {
  3395. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3396. if (selectedRows.count > 0) {
  3397. for (NSIndexPath *selectionIndex in selectedRows) {
  3398. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3399. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3400. [metadatas addObject:metadata];
  3401. }
  3402. }
  3403. return metadatas;
  3404. }
  3405. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3406. {
  3407. NSInteger section = indexPath.section + 1;
  3408. NSInteger row = indexPath.row + 1;
  3409. NSInteger totSections =[_sectionDataSource.sections count] ;
  3410. if ((totSections < section) || (section > totSections)) {
  3411. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3412. return nil;
  3413. }
  3414. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3415. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3416. if (fileIDs) {
  3417. NSInteger totRows =[fileIDs count] ;
  3418. if ((totRows < row) || (row > totRows)) {
  3419. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3420. return nil;
  3421. }
  3422. } else {
  3423. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3424. return nil;
  3425. }
  3426. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3427. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3428. }
  3429. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3430. {
  3431. NSInteger totSections =[_sectionDataSource.sections count] ;
  3432. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3433. #if DEBUG
  3434. 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];
  3435. [alertView show];
  3436. #endif
  3437. return nil;
  3438. }
  3439. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3440. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3441. }
  3442. #pragma --------------------------------------------------------------------------------------------
  3443. #pragma mark - ==== Table ====
  3444. #pragma --------------------------------------------------------------------------------------------
  3445. - (void)tableViewSelect:(BOOL)edit
  3446. {
  3447. // chiudiamo eventuali swipe aperti
  3448. if (edit) [self.tableView setEditing:NO animated:NO];
  3449. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3450. [self.tableView setEditing:edit animated:YES];
  3451. _isSelectedMode = edit;
  3452. if (edit)
  3453. [self setUINavigationBarSelected];
  3454. else
  3455. [self setUINavigationBarDefault];
  3456. [self setTitle];
  3457. }
  3458. - (void)tableViewReload
  3459. {
  3460. // ricordiamoci le row selezionate
  3461. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3462. [self.tableView reloadData];
  3463. for (NSIndexPath *path in indexPaths)
  3464. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3465. [self setTableViewFooter];
  3466. if (self.tableView.editing)
  3467. [self setTitle];
  3468. }
  3469. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3470. {
  3471. return 60;
  3472. }
  3473. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3474. {
  3475. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3476. }
  3477. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3478. {
  3479. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3480. }
  3481. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3482. {
  3483. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3484. NSString *sectionTitle = [sections objectAtIndex:section];
  3485. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3486. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3487. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3488. return 20.f;
  3489. }
  3490. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3491. {
  3492. float shift;
  3493. UIVisualEffectView *visualEffectView;
  3494. // Titolo
  3495. NSString *titleSection;
  3496. // Controllo
  3497. if ([_sectionDataSource.sections count] == 0)
  3498. return nil;
  3499. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3500. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3501. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3502. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3503. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3504. else titleSection = NSLocalizedString(titleSection,nil);
  3505. // Formato titolo
  3506. NSString *currentDevice = [CCUtility currentDevice];
  3507. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3508. visualEffectView = [[UIVisualEffectView alloc] init];
  3509. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3510. } else {
  3511. UIVisualEffect *blurEffect;
  3512. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3513. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3514. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3515. }
  3516. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3517. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3518. else shift = - 20;
  3519. } else shift = - 10;
  3520. // Title
  3521. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3522. titleLabel.backgroundColor = [UIColor clearColor];
  3523. titleLabel.textColor = [UIColor blackColor];
  3524. titleLabel.font = [UIFont systemFontOfSize:12];
  3525. titleLabel.textAlignment = NSTextAlignmentLeft;
  3526. titleLabel.text = titleSection;
  3527. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3528. [visualEffectView addSubview:titleLabel];
  3529. // Elements
  3530. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3531. elementLabel.backgroundColor = [UIColor clearColor];
  3532. elementLabel.textColor = [UIColor blackColor];;
  3533. elementLabel.font = [UIFont systemFontOfSize:12];
  3534. elementLabel.textAlignment = NSTextAlignmentRight;
  3535. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3536. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3537. NSUInteger rowsCount = [metadatas count];
  3538. if (rowsCount == 0) return nil;
  3539. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3540. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3541. [visualEffectView addSubview:elementLabel];
  3542. return visualEffectView;
  3543. }
  3544. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3545. {
  3546. return [_sectionDataSource.sections indexOfObject:title];
  3547. }
  3548. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3549. {
  3550. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3551. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3552. else
  3553. return nil;
  3554. }
  3555. /*
  3556. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3557. {
  3558. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3559. }
  3560. }
  3561. */
  3562. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3563. {
  3564. NSString *typeCell;
  3565. NSString *dataFile;
  3566. NSString *lunghezzaFile;
  3567. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3568. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3569. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3570. else typeCell = @"CellMainTransfer";
  3571. if (!metadata)
  3572. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3573. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3574. // separator
  3575. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3576. // change color selection
  3577. UIView *selectionColor = [[UIView alloc] init];
  3578. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3579. cell.selectedBackgroundView = selectionColor;
  3580. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3581. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3582. // ----------------------------------------------------------------------------------------------------------
  3583. // DEFAULT
  3584. // ----------------------------------------------------------------------------------------------------------
  3585. cell.fileImageView.image = nil;
  3586. cell.statusImageView.image = nil;
  3587. cell.offlineImageView.image = nil;
  3588. cell.synchronizedImageView.image = nil;
  3589. cell.sharedImageView.image = nil;
  3590. cell.labelTitle.enabled = YES;
  3591. cell.labelTitle.text = @"";
  3592. cell.labelInfoFile.enabled = YES;
  3593. cell.labelInfoFile.text = @"";
  3594. cell.progressView.progress = 0.0;
  3595. cell.progressView.hidden = YES;
  3596. cell.cancelTaskButton.hidden = YES;
  3597. cell.reloadTaskButton.hidden = YES;
  3598. cell.stopTaskButton.hidden = YES;
  3599. // Encrypted color
  3600. if (metadata.cryptated) {
  3601. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3602. } else {
  3603. cell.labelTitle.textColor = [UIColor blackColor];
  3604. }
  3605. // ----------------------------------------------------------------------------------------------------------
  3606. // File Name & Folder
  3607. // ----------------------------------------------------------------------------------------------------------
  3608. // nome del file
  3609. cell.labelTitle.text = metadata.fileNamePrint;
  3610. // è una directory
  3611. if (metadata.directory) {
  3612. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3613. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3614. lunghezzaFile = @" ";
  3615. // ----------------------------------------------------------------------------------------------------------
  3616. // Favorite Folder
  3617. // ----------------------------------------------------------------------------------------------------------
  3618. if (metadata.favorite) {
  3619. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3620. }
  3621. } else {
  3622. // File
  3623. dataFile = [CCUtility dateDiff:metadata.date];
  3624. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3625. // Plist ancora da scaricare
  3626. if (metadata.cryptated && [metadata.title length] == 0) {
  3627. dataFile = @" ";
  3628. lunghezzaFile = @" ";
  3629. }
  3630. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3631. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3632. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3633. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3634. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3635. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3636. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3637. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3638. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3639. else
  3640. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3641. }
  3642. // Plist ancora da scaricare
  3643. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3644. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3645. cell.accessoryType = UITableViewCellAccessoryNone;
  3646. }
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. // File Image View
  3649. // ----------------------------------------------------------------------------------------------------------
  3650. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3651. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3652. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3653. if (cell.fileImageView.image == nil) {
  3654. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3655. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3656. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3657. dispatch_async(dispatch_get_main_queue(), ^{
  3658. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3659. if (cell)
  3660. cell.fileImageView.image = image;
  3661. });
  3662. });
  3663. }
  3664. } else {
  3665. if (metadata.directory)
  3666. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3667. else
  3668. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3669. if (metadata.thumbnailExists)
  3670. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3671. }
  3672. // ----------------------------------------------------------------------------------------------------------
  3673. // Image Status cyptated & Lock Passcode
  3674. // ----------------------------------------------------------------------------------------------------------
  3675. // File Cyptated
  3676. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3677. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3678. }
  3679. // Directory con passcode lock attivato
  3680. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3681. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3682. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3683. // ----------------------------------------------------------------------------------------------------------
  3684. // Offline
  3685. // ----------------------------------------------------------------------------------------------------------
  3686. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3687. if (isOfflineFile) {
  3688. cell.offlineImageView.image = [UIImage imageNamed:@"offline"];
  3689. }
  3690. // ----------------------------------------------------------------------------------------------------------
  3691. // Favorite
  3692. // ----------------------------------------------------------------------------------------------------------
  3693. if (metadata.favorite) {
  3694. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3695. }
  3696. // ----------------------------------------------------------------------------------------------------------
  3697. // Share
  3698. // ----------------------------------------------------------------------------------------------------------
  3699. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3700. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3701. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3702. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3703. // Aggiungiamo il Tap per le shared
  3704. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3705. if (isShare) {
  3706. if (metadata.directory) {
  3707. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3708. cell.sharedImageView.userInteractionEnabled = NO;
  3709. } else {
  3710. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3711. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3712. [tap setNumberOfTapsRequired:1];
  3713. cell.sharedImageView.userInteractionEnabled = YES;
  3714. [cell.sharedImageView addGestureRecognizer:tap];
  3715. }
  3716. }
  3717. if (isMounted) {
  3718. if (metadata.directory) {
  3719. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3720. cell.sharedImageView.userInteractionEnabled = NO;
  3721. } else {
  3722. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3723. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3724. [tap setNumberOfTapsRequired:1];
  3725. cell.sharedImageView.userInteractionEnabled = YES;
  3726. [cell.sharedImageView addGestureRecognizer:tap];
  3727. }
  3728. }
  3729. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3730. if (metadata.directory) {
  3731. if ([shareLink length] > 0)
  3732. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3733. if ([shareUserAndGroup length] > 0)
  3734. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3735. cell.sharedImageView.userInteractionEnabled = NO;
  3736. } else {
  3737. if ([shareLink length] > 0)
  3738. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3739. if ([shareUserAndGroup length] > 0)
  3740. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3741. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3742. [tap setNumberOfTapsRequired:1];
  3743. cell.sharedImageView.userInteractionEnabled = YES;
  3744. [cell.sharedImageView addGestureRecognizer:tap];
  3745. }
  3746. }
  3747. } else {
  3748. cell.sharedImageView.userInteractionEnabled = NO;
  3749. }
  3750. // ----------------------------------------------------------------------------------------------------------
  3751. // downloadFile
  3752. // ----------------------------------------------------------------------------------------------------------
  3753. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3754. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3755. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3756. // sessionTaskIdentifier : RELOAD + STOP
  3757. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3758. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3759. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3760. cell.cancelTaskButton.hidden = NO;
  3761. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3762. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3763. cell.reloadTaskButton.hidden = NO;
  3764. }
  3765. // sessionTaskIdentifierPlist : RELOAD
  3766. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3767. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3768. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3769. cell.reloadTaskButton.hidden = NO;
  3770. }
  3771. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3772. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3773. if (progress > 0) {
  3774. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3775. else cell.progressView.progressTintColor = [UIColor blackColor];
  3776. cell.progressView.progress = progress;
  3777. cell.progressView.hidden = NO;
  3778. }
  3779. // ----------------------------------------------------------------------------------------------------------
  3780. // downloadFile Error
  3781. // ----------------------------------------------------------------------------------------------------------
  3782. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3783. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3784. if ([metadata.sessionError length] == 0)
  3785. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3786. else
  3787. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3788. }
  3789. }
  3790. // ----------------------------------------------------------------------------------------------------------
  3791. // uploadFile
  3792. // ----------------------------------------------------------------------------------------------------------
  3793. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3794. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3795. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3796. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3797. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3798. cell.cancelTaskButton.hidden = NO;
  3799. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3800. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3801. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3802. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3803. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3804. cell.reloadTaskButton.hidden = NO;
  3805. cell.stopTaskButton.hidden = YES;
  3806. } else {
  3807. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3808. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3809. cell.stopTaskButton.hidden = NO;
  3810. cell.reloadTaskButton.hidden = YES;
  3811. }
  3812. // se non c'è una preview in bianconero metti l'immagine di default
  3813. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3814. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3815. cell.labelTitle.enabled = NO;
  3816. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3817. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3818. if (progress > 0) {
  3819. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3820. else cell.progressView.progressTintColor = [UIColor blackColor];
  3821. cell.progressView.progress = progress;
  3822. cell.progressView.hidden = NO;
  3823. }
  3824. // ----------------------------------------------------------------------------------------------------------
  3825. // uploadFileError
  3826. // ----------------------------------------------------------------------------------------------------------
  3827. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3828. cell.labelTitle.enabled = NO;
  3829. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3830. if ([metadata.sessionError length] == 0)
  3831. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3832. else
  3833. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3834. }
  3835. }
  3836. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3837. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3838. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3839. return cell;
  3840. }
  3841. - (void)setTableViewFooter
  3842. {
  3843. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3844. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3845. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3846. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3847. UIFont *appFont = [UIFont systemFontOfSize:12];
  3848. footerLabel.font = appFont;
  3849. footerLabel.textColor = [UIColor grayColor];
  3850. footerLabel.backgroundColor = [UIColor clearColor];
  3851. footerLabel.textAlignment = NSTextAlignmentCenter;
  3852. NSString *folders;
  3853. NSString *files;
  3854. NSString *footerText;
  3855. if (_sectionDataSource.directories > 1) {
  3856. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3857. } else if (_sectionDataSource.directories == 1){
  3858. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3859. } else {
  3860. folders = @"";
  3861. }
  3862. if (_sectionDataSource.files > 1) {
  3863. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3864. } else if (_sectionDataSource.files == 1){
  3865. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3866. } else {
  3867. files = @"";
  3868. }
  3869. if ([folders isEqualToString:@""]) {
  3870. footerText = files;
  3871. } else if ([files isEqualToString:@""]) {
  3872. footerText = folders;
  3873. } else {
  3874. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3875. }
  3876. footerLabel.text = footerText;
  3877. [footerView addSubview:footerLabel];
  3878. [self.tableView setTableFooterView:footerView];
  3879. }
  3880. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3881. {
  3882. NSString *textMessage;
  3883. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3884. // se non può essere selezionata deseleziona
  3885. if ([cell isEditing] == NO)
  3886. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3887. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3888. if (self.tableView.editing) {
  3889. [self setTitle];
  3890. return;
  3891. }
  3892. // test crash
  3893. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3894. if (indexPath.row >= [metadatas count]) return;
  3895. // settiamo il record file.
  3896. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3897. //
  3898. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3899. // se è in corso una sessione
  3900. if ([_metadata.session length] > 0) return;
  3901. if (_metadata.errorPasscode) {
  3902. // se UUID è nil lo sta ancora caricando quindi esci
  3903. if (!_metadata.uuid) return;
  3904. // esiste un hint ??
  3905. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3906. // qui !! la richiesta della nuova passcode
  3907. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3908. // stesso UUID ... la password è stata modificata !!!!!!
  3909. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3910. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3911. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3912. [alertView show];
  3913. } else {
  3914. // UUID diverso.
  3915. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3916. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3917. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3918. [alertView show];
  3919. }
  3920. // chiediamo la passcode e ricarichiamo tutto.
  3921. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3922. viewController.delegate = self;
  3923. viewController.fromType = CCBKPasscodeFromPasscode;
  3924. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3925. viewController.passcodeInputView.maximumLength = 64;
  3926. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3927. viewController.inputViewTitlePassword = NO;
  3928. viewController.title = [NCBrandOptions sharedInstance].brand;
  3929. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3930. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3931. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3932. [self presentViewController:navigationController animated:YES completion:nil];
  3933. }
  3934. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3935. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3936. NSString* selector;
  3937. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3938. else selector = selectorLoadPlist;
  3939. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3940. return;
  3941. }
  3942. // se il plist è caricato ed è un modello aprilo
  3943. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3944. // file
  3945. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3946. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3947. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3948. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3949. } else {
  3950. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3951. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3952. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3953. }
  3954. }
  3955. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3956. }
  3957. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3958. {
  3959. [self setTitle];
  3960. }
  3961. #pragma --------------------------------------------------------------------------------------------
  3962. #pragma mark ===== Synchronize Folder Cell =====
  3963. #pragma --------------------------------------------------------------------------------------------
  3964. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3965. {
  3966. BOOL cryptated = NO;
  3967. CCCellMain *cell;
  3968. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3969. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3970. if (recordMetadata.directory == NO)
  3971. continue;
  3972. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3973. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3974. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3975. cryptated = recordMetadata.cryptated;
  3976. break;
  3977. }
  3978. }
  3979. if (!cell)
  3980. return;
  3981. if (animation) {
  3982. NSURL *myURL;
  3983. if (cryptated)
  3984. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3985. else
  3986. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3987. } else {
  3988. cell.synchronizedImageView.image = nil;
  3989. }
  3990. }
  3991. #pragma --------------------------------------------------------------------------------------------
  3992. #pragma mark ===== Navigation ====
  3993. #pragma --------------------------------------------------------------------------------------------
  3994. - (BOOL)shouldPerformSegue
  3995. {
  3996. // if background return
  3997. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3998. if (self.view.window == NO)
  3999. return NO;
  4000. // Collapsed ma siamo già in detail esci
  4001. if (self.splitViewController.isCollapsed)
  4002. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4003. // Video in esecuzione esci
  4004. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4005. return YES;
  4006. }
  4007. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4008. {
  4009. id viewController = segue.destinationViewController;
  4010. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4011. CCMetadata *metadata;
  4012. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4013. UINavigationController *nav = viewController;
  4014. _detailViewController = (CCDetail *)nav.topViewController;
  4015. } else {
  4016. _detailViewController = segue.destinationViewController;
  4017. }
  4018. if ([sender isKindOfClass:[CCMetadata class]]) {
  4019. metadata = sender;
  4020. [allRecordsDataSourceImagesVideos addObject:sender];
  4021. } else {
  4022. metadata = _metadata;
  4023. for (NSString *fileID in _sectionDataSource.allFileID) {
  4024. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4025. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4026. [allRecordsDataSourceImagesVideos addObject:metadata];
  4027. }
  4028. }
  4029. _detailViewController.metadataDetail = metadata;
  4030. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4031. _detailViewController.dateFilterQuery = nil;
  4032. _detailViewController.isCameraUpload = NO;
  4033. [_detailViewController setTitle:metadata.fileNamePrint];
  4034. }
  4035. // can i go to next viewcontroller
  4036. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4037. {
  4038. NSString *nomeDir;
  4039. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4040. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4041. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4042. // 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
  4043. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4044. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4045. viewController.delegate = self;
  4046. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4047. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4048. viewController.inputViewTitlePassword = YES;
  4049. if ([CCUtility getSimplyBlockCode]) {
  4050. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4051. viewController.passcodeInputView.maximumLength = 6;
  4052. } else {
  4053. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4054. viewController.passcodeInputView.maximumLength = 64;
  4055. }
  4056. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4057. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4058. viewController.touchIDManager = touchIDManager;
  4059. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4060. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4061. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4062. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4063. [self presentViewController:navController animated:YES completion:nil];
  4064. return;
  4065. }
  4066. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4067. else nomeDir = _metadata.fileName;
  4068. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4069. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4070. if (viewController.isViewLoaded == false || viewController == nil) {
  4071. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4072. viewController.isFolderEncrypted = _metadata.cryptated;
  4073. viewController.serverUrl = serverUrlPush;
  4074. viewController.titleMain = _metadata.fileNamePrint;
  4075. viewController.textBackButton = _titleMain;
  4076. // save self
  4077. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4078. }
  4079. // OFF SearchBar
  4080. [viewController cancelSearchBar];
  4081. [self.navigationController pushViewController:viewController animated:YES];
  4082. }
  4083. }
  4084. @end