CCMain.m 248 KB

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