CCMain.m 248 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646
  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. // Auto upload All
  1198. if([selector isEqualToString:selectorUploadAutomaticAll])
  1199. [app performSelectorOnMainThread:@selector(loadAutomaticUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1200. // Auto Upload
  1201. if([selector isEqualToString:selectorUploadAutomatic])
  1202. [app performSelectorOnMainThread:@selector(loadAutomaticUpload:) withObject:[NSNumber numberWithInt:1] waitUntilDone:NO];
  1203. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1204. [self readFolderWithForced:YES serverUrl:serverUrl];
  1205. } else {
  1206. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1207. }
  1208. }
  1209. //
  1210. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1211. //
  1212. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1213. {
  1214. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1215. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1216. });
  1217. }
  1218. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1219. {
  1220. NSArray *assets = [arguments objectAtIndex:0];
  1221. NSString *serverUrl = [arguments objectAtIndex:1];
  1222. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1223. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1224. NSString *session = [arguments objectAtIndex:4];
  1225. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1226. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1227. // Create the folder for Photos & if request the subfolders
  1228. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1229. return;
  1230. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1231. for (PHAsset *asset in assets) {
  1232. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1233. NSDate *assetDate = asset.creationDate;
  1234. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1235. // Create serverUrl if use sub folder
  1236. if (useSubFolder) {
  1237. [formatter setDateFormat:@"yyyy"];
  1238. NSString *yearString = [formatter stringFromDate:assetDate];
  1239. [formatter setDateFormat:@"MM"];
  1240. NSString *monthString = [formatter stringFromDate:assetDate];
  1241. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1242. }
  1243. // Check if is in upload
  1244. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1245. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1246. if ([isRecordInSessions count] > 0) {
  1247. // next upload
  1248. continue;
  1249. } else {
  1250. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1251. if (cryptated) {
  1252. metadataNet.action = actionUploadAsset;
  1253. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1254. metadataNet.cryptated = cryptated;
  1255. metadataNet.fileName = fileName;
  1256. metadataNet.priority = NSOperationQueuePriorityNormal;
  1257. metadataNet.session = session;
  1258. metadataNet.selector = selectorUploadFile;
  1259. metadataNet.selectorPost = nil;
  1260. metadataNet.serverUrl = serverUrl;
  1261. metadataNet.taskStatus = k_taskStatusResume;
  1262. } else {
  1263. metadataNet.action = actionReadFile;
  1264. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1265. metadataNet.cryptated = cryptated;
  1266. metadataNet.fileName = fileName;
  1267. metadataNet.priority = NSOperationQueuePriorityNormal;
  1268. metadataNet.session = session;
  1269. metadataNet.selector = selectorReadFileUploadFile;
  1270. metadataNet.serverUrl = serverUrl;
  1271. }
  1272. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1273. }
  1274. }
  1275. }
  1276. #pragma --------------------------------------------------------------------------------------------
  1277. #pragma mark ==== Read File ====
  1278. #pragma --------------------------------------------------------------------------------------------
  1279. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1280. {
  1281. // UploadFile
  1282. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1283. // File not exists
  1284. if (errorCode == 404) {
  1285. metadataNet.action = actionUploadAsset;
  1286. metadataNet.errorCode = 0;
  1287. metadataNet.selector = selectorUploadFile;
  1288. metadataNet.selectorPost = nil;
  1289. metadataNet.taskStatus = k_taskStatusResume;
  1290. if ([metadataNet.session containsString:@"wwan"])
  1291. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1292. else
  1293. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1294. } else {
  1295. // error ho many retry befor notification and go to on next asses
  1296. if (metadataNet.errorRetry < 3) {
  1297. // Retry read file
  1298. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1299. } else {
  1300. // STOP check file, view message error
  1301. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1302. }
  1303. }
  1304. }
  1305. }
  1306. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1307. {
  1308. // UploadFile
  1309. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1310. metadataNet.action = actionUploadAsset;
  1311. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1312. metadataNet.selector = selectorUploadFile;
  1313. metadataNet.selectorPost = nil;
  1314. metadataNet.taskStatus = k_taskStatusResume;
  1315. if ([metadataNet.session containsString:@"wwan"])
  1316. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1317. else
  1318. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1319. }
  1320. }
  1321. #pragma --------------------------------------------------------------------------------------------
  1322. #pragma mark ==== Read Folder ====
  1323. #pragma --------------------------------------------------------------------------------------------
  1324. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1325. {
  1326. // verify active user
  1327. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1328. [_hud hideHud];
  1329. [_refreshControl endRefreshing];
  1330. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1331. if (message && [record.account isEqualToString:metadataNet.account])
  1332. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1333. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1334. if (errorCode == 401)
  1335. [self changePasswordAccount];
  1336. }
  1337. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1338. {
  1339. // verify active user
  1340. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1341. if (![record.account isEqualToString:metadataNet.account])
  1342. return;
  1343. // save father e update permission
  1344. if(!_isSearchMode)
  1345. _fatherPermission = permissions;
  1346. NSArray *recordsInSessions;
  1347. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1348. if (_isSearchMode) {
  1349. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1350. } else {
  1351. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:etag];
  1352. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1353. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1354. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1355. }
  1356. for (tableMetadata *metadata in metadatas) {
  1357. // type of file
  1358. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1359. // if crypto do not insert
  1360. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1361. // verify if the record encrypted has plist + crypto
  1362. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1363. BOOL isCryptoComplete = NO;
  1364. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1365. for (tableMetadata *completeMetadata in metadatas) {
  1366. if (completeMetadata.cryptated == NO) continue;
  1367. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1368. isCryptoComplete = YES;
  1369. break;
  1370. }
  1371. }
  1372. if (isCryptoComplete == NO) continue;
  1373. }
  1374. // verify if the record is in download/upload progress
  1375. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1376. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1377. // is in Download or Upload
  1378. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1379. continue;
  1380. }
  1381. }
  1382. // Insert in Array
  1383. [metadatasToInsertInDB addObject:metadata];
  1384. }
  1385. // insert in Database
  1386. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1387. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1388. // read plist
  1389. if (!_isSearchMode)
  1390. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1391. // File is changed ??
  1392. if (!_isSearchMode && metadatasToInsertInDB)
  1393. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1394. });
  1395. // Search Mode
  1396. if (_isSearchMode)
  1397. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1398. // this is the same directory
  1399. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1400. // reload
  1401. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1402. // stoprefresh
  1403. [_refreshControl endRefreshing];
  1404. // Enable change user
  1405. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1406. [_hud hideHud];
  1407. }
  1408. }
  1409. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1410. {
  1411. // init control
  1412. if (!serverUrl || !app.activeAccount)
  1413. return;
  1414. // Search Mode
  1415. if (_isSearchMode) {
  1416. if (forced) {
  1417. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1418. _searchFileName = @""; // forced reload searchg
  1419. }
  1420. [self updateSearchResultsForSearchController:self.searchController];
  1421. return;
  1422. }
  1423. BOOL isDirectoryOutOfDate = true;
  1424. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1425. if (directory.dateReadDirectory) {
  1426. // Is Directory Out Of Date ?
  1427. NSDateComponents *dateComponents = [NSDateComponents new];
  1428. [dateComponents setWeekday:k_dayForceReadFolder];
  1429. NSCalendar *calendar = [NSCalendar currentCalendar];
  1430. NSDate *datePlus = [calendar dateByAddingComponents:dateComponents toDate:directory.dateReadDirectory options:0];
  1431. NSDate *now = [NSDate date];
  1432. // usa la Cache se richiesto e se la data è entro X giorni dall'ultima volta che l'hai letta.
  1433. if ([now compare:datePlus] == NSOrderedDescending)
  1434. isDirectoryOutOfDate = true;
  1435. else
  1436. isDirectoryOutOfDate = false;
  1437. }
  1438. if (isDirectoryOutOfDate || forced) {
  1439. if (_refreshControl.isRefreshing == NO)
  1440. [_hud visibleIndeterminateHud];
  1441. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1442. metadataNet.action = actionReadFolder;
  1443. metadataNet.date = [NSDate date];
  1444. metadataNet.directoryID = directory.directoryID;
  1445. metadataNet.priority = NSOperationQueuePriorityHigh;
  1446. metadataNet.selector = selectorReadFolder;
  1447. metadataNet.serverUrl = serverUrl;
  1448. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1449. }
  1450. }
  1451. #pragma mark -
  1452. #pragma --------------------------------------------------------------------------------------------
  1453. #pragma mark ===== Search =====
  1454. #pragma --------------------------------------------------------------------------------------------
  1455. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1456. {
  1457. _isSearchMode = YES;
  1458. [self deleteRefreshControl];
  1459. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1460. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1461. _searchFileName = fileName;
  1462. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1463. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1464. _noFilesSearchTitle = @"";
  1465. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1466. [self.tableView reloadEmptyDataSet];
  1467. } else {
  1468. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1469. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1470. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1471. [_searchResultMetadatas removeAllObjects];
  1472. for (tableMetadata *record in records)
  1473. [_searchResultMetadatas addObject:record];
  1474. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1475. metadataNet.account = app.activeAccount;
  1476. metadataNet.action = actionUploadTemplate;
  1477. metadataNet.directoryID = directoryID;
  1478. metadataNet.selector = selectorSearch;
  1479. metadataNet.serverUrl = _serverUrl;
  1480. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1481. }
  1482. }
  1483. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1484. [self reloadDatasource];
  1485. }
  1486. }
  1487. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1488. {
  1489. [self cancelSearchBar];
  1490. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1491. }
  1492. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1493. {
  1494. _searchFileName = @"";
  1495. if (message)
  1496. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1497. }
  1498. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1499. {
  1500. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1501. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1502. }
  1503. - (void)cancelSearchBar
  1504. {
  1505. if (self.searchController.active) {
  1506. [self.searchController setActive:NO];
  1507. [self createRefreshControl];
  1508. _isSearchMode = NO;
  1509. _searchFileName = @"";
  1510. _dateReadDataSource = nil;
  1511. _searchResultMetadatas = [NSMutableArray new];
  1512. [self reloadDatasource];
  1513. }
  1514. }
  1515. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1516. {
  1517. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1518. self.searchController.searchBar.placeholder = title;
  1519. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1520. _depth = @"0";
  1521. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1522. _depth = @"1";
  1523. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1524. _depth = @"infinity";
  1525. _searchFileName = @"";
  1526. [self updateSearchResultsForSearchController:self.searchController];
  1527. }
  1528. #pragma mark -
  1529. #pragma --------------------------------------------------------------------------------------------
  1530. #pragma mark ===== Delete File or Folder =====
  1531. #pragma --------------------------------------------------------------------------------------------
  1532. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1533. {
  1534. [self deleteFileOrFolderSuccess:metadataNet];
  1535. }
  1536. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1537. {
  1538. [_queueSelector removeObject:metadataNet.selector];
  1539. if ([_queueSelector count] == 0) {
  1540. [_hud hideHud];
  1541. if (_isSearchMode)
  1542. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1543. else
  1544. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1545. // next
  1546. if ([_selectedMetadatas count] > 0) {
  1547. [_selectedMetadatas removeObjectAtIndex:0];
  1548. if ([_selectedMetadatas count] > 0)
  1549. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1550. }
  1551. }
  1552. }
  1553. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1554. {
  1555. if (metadata.cryptated) {
  1556. [_queueSelector addObject:selectorDeleteCrypto];
  1557. [_queueSelector addObject:selectorDeletePlist];
  1558. } else {
  1559. [_queueSelector addObject:selectorDelete];
  1560. }
  1561. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1562. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1563. }
  1564. - (void)deleteSelectionFile
  1565. {
  1566. [_selectedMetadatas removeAllObjects];
  1567. [_queueSelector removeAllObjects];
  1568. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1569. _numSelectedMetadatas = [_selectedMetadatas count];
  1570. if ([_selectedMetadatas count] > 0)
  1571. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1572. [self tableViewSelect:NO];
  1573. }
  1574. - (void)deleteFile
  1575. {
  1576. [_selectedMetadatas removeAllObjects];
  1577. [_queueSelector removeAllObjects];
  1578. _numSelectedMetadatas = 1;
  1579. [_selectedMetadatas addObject:_metadata];
  1580. if ([_selectedMetadatas count] > 0)
  1581. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1582. [self tableViewSelect:NO];
  1583. }
  1584. #pragma --------------------------------------------------------------------------------------------
  1585. #pragma mark ===== Rename / Move =====
  1586. #pragma --------------------------------------------------------------------------------------------
  1587. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1588. {
  1589. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1590. }
  1591. - (void)renameFile:(tableMetadata *)metadata fileName:(NSString *)fileName
  1592. {
  1593. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1594. }
  1595. - (void)renameNote:(tableMetadata *)metadata fileName:(NSString *)fileName
  1596. {
  1597. CCTemplates *templates = [[CCTemplates alloc] init];
  1598. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1599. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1600. if (fileNameModel) {
  1601. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1602. metadataNet.action = actionUploadTemplate;
  1603. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1604. metadataNet.fileNamePrint = fileName;
  1605. metadataNet.etag = metadata.etag;
  1606. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1607. metadataNet.session = k_upload_session_foreground;
  1608. metadataNet.taskStatus = k_taskStatusResume;
  1609. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1610. }
  1611. }
  1612. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1613. {
  1614. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1615. [_hud hideHud];
  1616. if (message)
  1617. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1618. [_selectedMetadatas removeAllObjects];
  1619. [_queueSelector removeAllObjects];
  1620. }
  1621. }
  1622. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1623. {
  1624. [_queueSelector removeObject:metadataNet.selector];
  1625. if ([_queueSelector count] == 0) {
  1626. [_hud hideHud];
  1627. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1628. NSString *directoryID = metadataNet.directoryID;
  1629. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1630. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1631. // FILE -> Metadata
  1632. if (metadataNet.directory == NO) {
  1633. // move metadata
  1634. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1635. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1636. }
  1637. // DIRECTORY -> Directory - CCMetadata
  1638. if (metadataNet.directory == YES) {
  1639. // delete all dir / subdir
  1640. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1641. // move metadata
  1642. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1643. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1644. // Add new directory
  1645. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1646. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1647. }
  1648. // reload Datasource
  1649. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1650. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1651. else
  1652. [self reloadDatasource];
  1653. // Next file
  1654. [_selectedMetadatas removeObjectAtIndex:0];
  1655. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1656. }
  1657. }
  1658. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1659. {
  1660. if ([_selectedMetadatas count] > 0) {
  1661. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1662. // Plain
  1663. if (metadata.cryptated == NO) {
  1664. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1665. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1666. if(!error) {
  1667. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1668. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1669. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1670. }];
  1671. [alert addAction:ok];
  1672. [self presentViewController:alert animated:YES completion:nil];
  1673. });
  1674. return;
  1675. }
  1676. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1677. metadataNet.action = actionMoveFileOrFolder;
  1678. metadataNet.directory = metadata.directory;
  1679. metadataNet.fileID = metadata.fileID;
  1680. metadataNet.directoryID = metadata.directoryID;
  1681. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1682. metadataNet.fileName = metadata.fileName;
  1683. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1684. metadataNet.fileNameTo = metadata.fileName;
  1685. metadataNet.etag = metadata.etag;
  1686. metadataNet.selector = selectorMove;
  1687. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1688. metadataNet.serverUrlTo = serverUrlTo;
  1689. [_queueSelector addObject:metadataNet.selector];
  1690. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1691. }
  1692. // cyptated
  1693. if (metadata.cryptated == YES) {
  1694. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1695. metadataNet.action = actionMoveFileOrFolder;
  1696. metadataNet.directory = metadata.directory;
  1697. metadataNet.fileID = metadata.fileID;
  1698. metadataNet.directoryID = metadata.directoryID;
  1699. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1700. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1701. metadataNet.etag = metadata.etag;
  1702. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1703. metadataNet.serverUrlTo = serverUrlTo;
  1704. // data
  1705. metadataNet.fileName = metadata.fileNameData;
  1706. metadataNet.fileNameTo = metadata.fileNameData;
  1707. metadataNet.selector = selectorMoveCrypto;
  1708. [_queueSelector addObject:metadataNet.selector];
  1709. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1710. // plist
  1711. metadataNet.fileName = metadata.fileName;
  1712. metadataNet.fileNameTo = metadata.fileName;
  1713. metadataNet.selector = selectorMovePlist;
  1714. [_queueSelector addObject:metadataNet.selector];
  1715. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1716. }
  1717. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1718. }
  1719. }
  1720. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1721. {
  1722. [_selectedMetadatas removeAllObjects];
  1723. [_queueSelector removeAllObjects];
  1724. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1725. _numSelectedMetadatas = [_selectedMetadatas count];
  1726. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1727. [self tableViewSelect:NO];
  1728. }
  1729. - (void)moveOpenWindow:(NSArray *)indexPaths
  1730. {
  1731. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1732. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1733. viewController.delegate = self;
  1734. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1735. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1736. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1737. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1738. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1739. viewController.networkingOperationQueue = app.netQueue;
  1740. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1741. [self presentViewController:navigationController animated:YES completion:nil];
  1742. }
  1743. #pragma --------------------------------------------------------------------------------------------
  1744. #pragma mark ===== Create folder =====
  1745. #pragma --------------------------------------------------------------------------------------------
  1746. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1747. {
  1748. [_hud hideHud];
  1749. if (message)
  1750. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1751. }
  1752. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1753. {
  1754. [_hud hideHud];
  1755. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1756. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1757. // Load Folder or the Datasource
  1758. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1759. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1760. } else {
  1761. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1762. }
  1763. }
  1764. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1765. {
  1766. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1767. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1768. if (![fileNameFolder length]) return;
  1769. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1770. else metadataNet.serverUrl = _serverUrl;
  1771. metadataNet.action = actionCreateFolder;
  1772. if (autoUploadDirectory)
  1773. metadataNet.options = @"folderAutoUpload";
  1774. metadataNet.fileName = fileNameFolder;
  1775. metadataNet.selector = selectorCreateFolder;
  1776. metadataNet.selectorPost = selectorReadFolderForced;
  1777. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1778. if (!autoUploadDirectory)
  1779. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1780. }
  1781. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1782. {
  1783. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1784. NSString *fileNamePlist;
  1785. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1786. if (![fileNameFolder length]) return;
  1787. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1788. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1789. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1790. // Create folder
  1791. metadataNet.action = actionCreateFolder;
  1792. metadataNet.fileName = fileNamePlist;
  1793. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1794. metadataNet.selector = selectorCreateFolder;
  1795. metadataNet.serverUrl = _serverUrl;
  1796. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1797. // upload plist file
  1798. metadataNet.action = actionUploadOnlyPlist;
  1799. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1800. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1801. metadataNet.selectorPost = selectorReadFolderForced;
  1802. metadataNet.serverUrl = _serverUrl;
  1803. metadataNet.session = k_upload_session_foreground;
  1804. metadataNet.taskStatus = k_taskStatusResume;
  1805. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1806. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1807. }
  1808. - (void)createFolderAutoUpload
  1809. {
  1810. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1811. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1812. }
  1813. #pragma --------------------------------------------------------------------------------------------
  1814. #pragma mark ===== Encrypted / Decrypted Folder =====
  1815. #pragma --------------------------------------------------------------------------------------------
  1816. - (void)encyptedDecryptedFolder
  1817. {
  1818. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1819. if (_metadata.cryptated) {
  1820. // DECRYPTED
  1821. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1822. //-------------------------- RENAME -------------------------------------------//
  1823. metadataNet.action = actionMoveFileOrFolder;
  1824. metadataNet.fileID = _metadata.fileID;
  1825. metadataNet.fileName = _metadata.fileNameData;
  1826. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1827. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1828. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1829. metadataNet.selector = selectorRename;
  1830. metadataNet.serverUrl = serverUrl;
  1831. metadataNet.serverUrlTo = serverUrl;
  1832. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1833. //-------------------------- DELETE -------------------------------------------//
  1834. metadataNet.action = actionDeleteFileDirectory;
  1835. metadataNet.fileID = _metadata.fileID;
  1836. metadataNet.fileName = _metadata.fileName;
  1837. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1838. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1839. metadataNet.selector = selectorDeletePlist;
  1840. metadataNet.selectorPost = selectorReadFolderForced;
  1841. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1842. } else {
  1843. // ENCRYPTED
  1844. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1845. // Create File Plist
  1846. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1847. //-------------------------- RENAME -------------------------------------------//
  1848. metadataNet.action = actionMoveFileOrFolder;
  1849. metadataNet.fileID = _metadata.fileID;
  1850. metadataNet.fileName = _metadata.fileName;
  1851. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1852. metadataNet.fileNameTo = fileNameCrypto;
  1853. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1854. metadataNet.selector = selectorRename;
  1855. metadataNet.serverUrl = serverUrl;
  1856. metadataNet.serverUrlTo = serverUrl;
  1857. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1858. //-------------------------- UPLOAD -------------------------------------------//
  1859. metadataNet.action = actionUploadOnlyPlist;
  1860. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1861. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1862. metadataNet.selectorPost = selectorReadFolderForced;
  1863. metadataNet.serverUrl = serverUrl;
  1864. metadataNet.session = k_upload_session_foreground;
  1865. metadataNet.taskStatus = k_taskStatusResume;
  1866. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1867. }
  1868. }
  1869. #pragma --------------------------------------------------------------------------------------------
  1870. #pragma mark ===== Encrypted/Decrypted File =====
  1871. #pragma --------------------------------------------------------------------------------------------
  1872. - (void)encryptedSelectedFiles
  1873. {
  1874. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1875. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1876. for (tableMetadata *metadata in selectedMetadatas) {
  1877. if (metadata.cryptated == NO && metadata.directory == NO)
  1878. [metadatas addObject:metadata];
  1879. }
  1880. if ([metadatas count] > 0) {
  1881. NSLog(@"[LOG] Start encrypted selected files ...");
  1882. for (tableMetadata* metadata in metadatas) {
  1883. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1884. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1885. }
  1886. }
  1887. [self tableViewSelect:NO];
  1888. }
  1889. - (void)decryptedSelectedFiles
  1890. {
  1891. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1892. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1893. for (tableMetadata *metadata in selectedMetadatas) {
  1894. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1895. [metadatas addObject:metadata];
  1896. }
  1897. if ([metadatas count] > 0) {
  1898. NSLog(@"[LOG] Start decrypted selected files ...");
  1899. for (tableMetadata* metadata in metadatas) {
  1900. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1901. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1902. }
  1903. }
  1904. [self tableViewSelect:NO];
  1905. }
  1906. - (void)cmdEncryptedDecryptedFile
  1907. {
  1908. NSString *selector;
  1909. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1910. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1911. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1912. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1913. }
  1914. - (void)encryptedFile:(tableMetadata *)metadata
  1915. {
  1916. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1917. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1918. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1919. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1920. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1921. dispatch_async(dispatch_get_main_queue(), ^{
  1922. [[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];
  1923. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1924. });
  1925. } else {
  1926. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1927. }
  1928. }
  1929. - (void)decryptedFile:(tableMetadata *)metadata
  1930. {
  1931. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1932. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1933. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1934. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1935. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1936. dispatch_async(dispatch_get_main_queue(), ^{
  1937. [[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];
  1938. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1939. });
  1940. } else {
  1941. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1942. }
  1943. }
  1944. #pragma --------------------------------------------------------------------------------------------
  1945. #pragma mark ===== Progress & Task Button =====
  1946. #pragma --------------------------------------------------------------------------------------------
  1947. - (void)triggerProgressTask:(NSNotification *)notification
  1948. {
  1949. NSDictionary *dict = notification.userInfo;
  1950. NSString *fileID = [dict valueForKey:@"fileID"];
  1951. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1952. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1953. float progress = [[dict valueForKey:@"progress"] floatValue];
  1954. // Check
  1955. if (!fileID)
  1956. return;
  1957. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1958. if (![serverUrl isEqualToString:_serverUrl])
  1959. return;
  1960. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1961. if (indexPath) {
  1962. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1963. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1964. else cell.progressView.progressTintColor = [UIColor blackColor];
  1965. cell.progressView.hidden = NO;
  1966. [cell.progressView setProgress:progress];
  1967. }
  1968. if (progress == 0)
  1969. [self.navigationController cancelCCProgress];
  1970. else
  1971. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1972. }
  1973. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1974. {
  1975. UITouch * touch = [[event allTouches] anyObject];
  1976. CGPoint location = [touch locationInView:self.tableView];
  1977. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1978. if (indexPath) {
  1979. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1980. if (metadata)
  1981. [self reloadTaskButton:metadata];
  1982. }
  1983. }
  1984. - (void)reloadTaskButton:(tableMetadata *)metadata
  1985. {
  1986. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1987. __block NSURLSessionTask *findTask;
  1988. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1989. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  1990. NSString *fileID = metadata.fileID;
  1991. // DOWNLOAD
  1992. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1993. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1994. for (NSURLSessionUploadTask *task in downloadTasks)
  1995. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  1996. findTask = task;
  1997. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1998. [task cancel];
  1999. }
  2000. if (!findTask) {
  2001. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2002. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2003. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2004. }
  2005. }];
  2006. }
  2007. // UPLOAD
  2008. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2009. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2010. for (NSURLSessionUploadTask *task in uploadTasks)
  2011. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2012. findTask = task;
  2013. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2014. [task cancel];
  2015. }
  2016. if (!findTask) {
  2017. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2018. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2019. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2020. }
  2021. }];
  2022. }
  2023. }
  2024. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2025. {
  2026. UITouch * touch = [[event allTouches] anyObject];
  2027. CGPoint location = [touch locationInView:self.tableView];
  2028. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2029. if (indexPath) {
  2030. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2031. if (metadata)
  2032. [self cancelTaskButton:metadata reloadTable:YES];
  2033. }
  2034. }
  2035. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2036. {
  2037. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2038. __block NSURLSessionTask *findTask;
  2039. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2040. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2041. NSString *fileID = metadata.fileID;
  2042. // DOWNLOAD
  2043. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2044. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2045. for (NSURLSessionTask *task in downloadTasks)
  2046. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2047. findTask = task;
  2048. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2049. [task cancel];
  2050. }
  2051. if (!findTask) {
  2052. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2053. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2054. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2055. }
  2056. }];
  2057. }
  2058. // UPLOAD
  2059. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2060. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2061. for (NSURLSessionUploadTask *task in uploadTasks)
  2062. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2063. findTask = task;
  2064. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2065. [task cancel];
  2066. }
  2067. if (!findTask) {
  2068. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2069. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2070. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2071. }
  2072. }];
  2073. }
  2074. }
  2075. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2076. {
  2077. UITouch * touch = [[event allTouches] anyObject];
  2078. CGPoint location = [touch locationInView:self.tableView];
  2079. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2080. if (indexPath) {
  2081. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2082. if (metadata)
  2083. [self stopTaskButton:metadata];
  2084. }
  2085. }
  2086. - (void)stopTaskButton:(tableMetadata *)metadata
  2087. {
  2088. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2089. __block NSURLSessionTask *findTask;
  2090. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2091. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2092. NSString *fileID = metadata.fileID;
  2093. // UPLOAD
  2094. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2095. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2096. for (NSURLSessionUploadTask *task in uploadTasks)
  2097. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2098. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2099. findTask = task;
  2100. [task cancel];
  2101. }
  2102. if (!findTask) {
  2103. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2104. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2105. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2106. }
  2107. }];
  2108. }
  2109. }
  2110. #pragma --------------------------------------------------------------------------------------------
  2111. #pragma mark ===== Shared =====
  2112. #pragma --------------------------------------------------------------------------------------------
  2113. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2114. {
  2115. [_hud hideHud];
  2116. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2117. // change account ?
  2118. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2119. if([record.account isEqualToString:metadataNet.account] == NO)
  2120. return;
  2121. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2122. if (result) {
  2123. appDelegate.sharesLink = result[0];
  2124. appDelegate.sharesUserAndGroup = result[1];
  2125. }
  2126. // Notify Shares View
  2127. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2128. if (openWindow) {
  2129. if (_shareOC) {
  2130. [_shareOC reloadData];
  2131. } else {
  2132. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2133. // Apriamo la view
  2134. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2135. _shareOC.delegate = self;
  2136. _shareOC.metadata = metadata;
  2137. _shareOC.serverUrl = metadataNet.serverUrl;
  2138. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2139. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2140. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2141. [self presentViewController:_shareOC animated:YES completion:nil];
  2142. }
  2143. }
  2144. [self tableViewReload];
  2145. }
  2146. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2147. {
  2148. [_hud hideHud];
  2149. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2150. if (_shareOC)
  2151. [_shareOC reloadData];
  2152. [self tableViewReload];
  2153. if (errorCode == 401)
  2154. [self changePasswordAccount];
  2155. }
  2156. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2157. {
  2158. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2159. metadataNet.action = actionShare;
  2160. metadataNet.fileID = metadata.fileID;
  2161. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2162. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2163. metadataNet.password = password;
  2164. metadataNet.selector = selectorShare;
  2165. metadataNet.serverUrl = serverUrl;
  2166. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2167. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2168. }
  2169. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2170. {
  2171. [_hud hideHud];
  2172. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2173. // rimuoviamo la condivisione da db
  2174. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2175. if (result) {
  2176. appDelegate.sharesLink = result[0];
  2177. appDelegate.sharesUserAndGroup = result[1];
  2178. }
  2179. if (_shareOC)
  2180. [_shareOC reloadData];
  2181. [self tableViewReload];
  2182. }
  2183. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2184. {
  2185. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2186. metadataNet.action = actionUnShare;
  2187. metadataNet.fileID = metadata.fileID;
  2188. metadataNet.fileName = metadata.fileName;
  2189. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2190. metadataNet.selector = selectorUnshare;
  2191. metadataNet.serverUrl = serverUrl;
  2192. metadataNet.share = share;
  2193. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2194. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2195. }
  2196. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2197. {
  2198. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2199. metadataNet.action = actionUpdateShare;
  2200. metadataNet.fileID = metadata.fileID;
  2201. metadataNet.expirationTime = expirationTime;
  2202. metadataNet.password = password;
  2203. metadataNet.selector = selectorUpdateShare;
  2204. metadataNet.serverUrl = serverUrl;
  2205. metadataNet.share = share;
  2206. metadataNet.sharePermission = permission;
  2207. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2208. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2209. }
  2210. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2211. {
  2212. [_hud hideHud];
  2213. if (_shareOC)
  2214. [_shareOC reloadUserAndGroup:items];
  2215. }
  2216. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2217. {
  2218. [_hud hideHud];
  2219. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2220. }
  2221. - (void)getUserAndGroup:(NSString *)find
  2222. {
  2223. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2224. metadataNet.action = actionGetUserAndGroup;
  2225. metadataNet.options = find;
  2226. metadataNet.selector = selectorGetUserAndGroup;
  2227. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2228. [_hud visibleIndeterminateHud];
  2229. }
  2230. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2231. {
  2232. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2233. metadataNet.action = actionShareWith;
  2234. metadataNet.fileID = metadata.fileID;
  2235. metadataNet.directoryID = directoryID;
  2236. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2237. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2238. metadataNet.serverUrl = serverUrl;
  2239. metadataNet.selector = selectorShare;
  2240. metadataNet.share = user;
  2241. metadataNet.shareeType = shareeType;
  2242. metadataNet.sharePermission = permission;
  2243. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2244. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2245. }
  2246. - (void)openWindowShare:(tableMetadata *)metadata
  2247. {
  2248. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2249. metadataNet.action = actionReadShareServer;
  2250. metadataNet.fileID = metadata.fileID;
  2251. metadataNet.fileName = metadata.fileName;
  2252. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2253. metadataNet.selector = selectorOpenWindowShare;
  2254. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2255. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2256. [_hud visibleIndeterminateHud];
  2257. }
  2258. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2259. {
  2260. CGPoint location = [tapGesture locationInView:self.tableView];
  2261. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2262. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2263. if (metadata)
  2264. [self openWindowShare:metadata];
  2265. }
  2266. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2267. {
  2268. CGPoint location = [tapGesture locationInView:self.tableView];
  2269. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2270. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2271. if (metadata) {
  2272. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2273. vc.metadata = metadata;
  2274. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2275. [self presentViewController:vc animated:YES completion:nil];
  2276. }
  2277. }
  2278. #pragma --------------------------------------------------------------------------------------------
  2279. #pragma mark ===== Favorite =====
  2280. #pragma --------------------------------------------------------------------------------------------
  2281. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2282. {
  2283. _dateReadDataSource = nil;
  2284. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2285. if (_isSearchMode)
  2286. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2287. else
  2288. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2289. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2290. if (metadata.directory && metadata.favorite) {
  2291. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2292. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2293. }
  2294. }
  2295. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2296. {
  2297. }
  2298. - (void)addFavorite:(tableMetadata *)metadata
  2299. {
  2300. if (metadata.directory) {
  2301. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2302. } else {
  2303. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2304. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2305. }
  2306. }
  2307. - (void)removeFavorite:(tableMetadata *)metadata
  2308. {
  2309. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2310. }
  2311. #pragma --------------------------------------------------------------------------------------------
  2312. #pragma mark ===== Local =====
  2313. #pragma --------------------------------------------------------------------------------------------
  2314. - (void)addLocal:(tableMetadata *)metadata
  2315. {
  2316. if (metadata.errorPasscode || !metadata.uuid) return;
  2317. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2318. if ([metadata.type isEqualToString: k_metadataType_file])
  2319. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2320. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2321. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2322. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2323. }
  2324. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2325. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2326. }
  2327. #pragma --------------------------------------------------------------------------------------------
  2328. #pragma mark ===== Open in... =====
  2329. #pragma --------------------------------------------------------------------------------------------
  2330. - (void)openIn:(tableMetadata *)metadata
  2331. {
  2332. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2333. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2334. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2335. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2336. }
  2337. #pragma --------------------------------------------------------------------------------------------
  2338. #pragma mark ===== Remove Local File =====
  2339. #pragma --------------------------------------------------------------------------------------------
  2340. - (void)removeLocalFile:(tableMetadata *)metadata
  2341. {
  2342. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2343. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2344. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2345. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2346. }
  2347. #pragma --------------------------------------------------------------------------------------------
  2348. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2349. #pragma --------------------------------------------------------------------------------------------
  2350. - (void)orderTable:(NSString *)order
  2351. {
  2352. [CCUtility setOrderSettings:order];
  2353. // Clear data-read of DataSource
  2354. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2355. }
  2356. - (void)ascendingTable:(BOOL)ascending
  2357. {
  2358. [CCUtility setAscendingSettings:ascending];
  2359. // Clear data-read of DataSource
  2360. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2361. }
  2362. - (void)directoryOnTop:(BOOL)directoryOnTop
  2363. {
  2364. [CCUtility setDirectoryOnTop:directoryOnTop];
  2365. // Clear data-read of DataSource
  2366. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2367. }
  2368. - (void)tableGroupBy:(NSString *)groupBy
  2369. {
  2370. [CCUtility setGroupBySettings:groupBy];
  2371. // Clear data-read of DataSource
  2372. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2373. }
  2374. #pragma --------------------------------------------------------------------------------------------
  2375. #pragma mark ==== Menu LOGO ====
  2376. #pragma --------------------------------------------------------------------------------------------
  2377. - (void)menuLogo
  2378. {
  2379. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2380. return;
  2381. // Brand
  2382. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2383. return;
  2384. 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) {
  2385. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2386. return;
  2387. }
  2388. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2389. NSMutableArray *menuArray = [NSMutableArray new];
  2390. for (NSString *account in listAccount) {
  2391. if ([account isEqualToString:app.activeAccount]) continue;
  2392. CCMenuItem *item = [[CCMenuItem alloc] init];
  2393. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2394. item.argument = account;
  2395. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2396. item.target = self;
  2397. item.action = @selector(changeDefaultAccount:);
  2398. [menuArray addObject:item];
  2399. }
  2400. if ([menuArray count] == 0)
  2401. return;
  2402. OptionalConfiguration options;
  2403. Color textColor, backgroundColor;
  2404. textColor.R = 0;
  2405. textColor.G = 0;
  2406. textColor.B = 0;
  2407. backgroundColor.R = 1;
  2408. backgroundColor.G = 1;
  2409. backgroundColor.B = 1;
  2410. NSInteger originY = 60;
  2411. options.arrowSize = 9;
  2412. options.marginXSpacing = 7;
  2413. options.marginYSpacing = 10;
  2414. options.intervalSpacing = 20;
  2415. options.menuCornerRadius = 6.5;
  2416. options.maskToBackground = NO;
  2417. options.shadowOfMenu = YES;
  2418. options.hasSeperatorLine = YES;
  2419. options.seperatorLineHasInsets = YES;
  2420. options.textColor = textColor;
  2421. options.menuBackgroundColor = backgroundColor;
  2422. CGRect rect = self.view.frame;
  2423. rect.origin.y = rect.origin.y + originY;
  2424. rect.size.height = rect.size.height - originY;
  2425. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2426. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2427. }
  2428. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2429. {
  2430. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2431. // STOP, erase all in queue networking
  2432. [app cancelAllOperations];
  2433. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2434. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2435. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2436. if (tableAccount)
  2437. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2438. // go to home sweet home
  2439. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2440. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2441. });
  2442. }
  2443. #pragma --------------------------------------------------------------------------------------------
  2444. #pragma mark ==== ReMenu ====
  2445. #pragma --------------------------------------------------------------------------------------------
  2446. - (void)createReMenuBackgroundView:(REMenu *)menu
  2447. {
  2448. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2449. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2450. [UIView animateWithDuration:0.2 animations:^{
  2451. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2452. if (height < self.tabBarController.tabBar.frame.size.height)
  2453. height = self.tabBarController.tabBar.frame.size.height;
  2454. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2455. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2456. }];
  2457. }
  2458. - (void)createReMainMenu
  2459. {
  2460. NSString *ordinamento;
  2461. NSString *groupBy = _directoryGroupBy;
  2462. __block NSString *nuovoOrdinamento;
  2463. NSString *titoloNuovo, *titoloAttuale;
  2464. BOOL ascendente;
  2465. __block BOOL nuovoAscendente;
  2466. UIImage *image;
  2467. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2468. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2469. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2470. [self tableViewSelect:YES];
  2471. }
  2472. }];
  2473. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2474. ordinamento = _directoryOrder;
  2475. if ([ordinamento isEqualToString:@"fileName"]) {
  2476. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2477. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2478. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2479. nuovoOrdinamento = @"date";
  2480. }
  2481. if ([ordinamento isEqualToString:@"date"]) {
  2482. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2483. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2484. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2485. nuovoOrdinamento = @"fileName";
  2486. }
  2487. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2488. [self orderTable:nuovoOrdinamento];
  2489. }];
  2490. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2491. ascendente = [CCUtility getAscendingSettings];
  2492. if (ascendente) {
  2493. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2494. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2495. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2496. nuovoAscendente = false;
  2497. }
  2498. if (!ascendente) {
  2499. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2500. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2501. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2502. nuovoAscendente = true;
  2503. }
  2504. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2505. [self ascendingTable:nuovoAscendente];
  2506. }];
  2507. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2508. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2509. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2510. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2511. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2512. else [self tableGroupBy:@"alphabetic"];
  2513. }];
  2514. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2515. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2516. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2517. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2518. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2519. else [self tableGroupBy:@"typefile"];
  2520. }];
  2521. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2522. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2523. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2524. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2525. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2526. else [self tableGroupBy:@"date"];
  2527. }];
  2528. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2529. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2530. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2531. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2532. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2533. else [self directoryOnTop:YES];
  2534. }];
  2535. // REMENU --------------------------------------------------------------------------------------------------------------
  2536. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2537. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2538. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2539. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2540. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2541. app.reMainMenu.separatorHeight = 0.5;
  2542. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2543. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2544. app.reMainMenu.textColor = [UIColor blackColor];
  2545. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2546. app.reMainMenu.textShadowColor = nil;
  2547. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2548. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2549. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2550. app.reMainMenu.highlightedSeparatorColor = nil;
  2551. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2552. app.reMainMenu.highlightedTextShadowColor = nil;
  2553. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2554. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2555. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2556. app.reMainMenu.subtitleTextShadowColor = nil;
  2557. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2558. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2559. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2560. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2561. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2562. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2563. app.reMainMenu.borderWidth = 0.3;
  2564. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2565. app.reMainMenu.animationDuration = 0.2;
  2566. app.reMainMenu.closeAnimationDuration = 0.2;
  2567. app.reMainMenu.bounce = NO;
  2568. [app.reMainMenu setClosePreparationBlock:^{
  2569. // Backgroun reMenu (Gesture)
  2570. [_reMenuBackgroundView removeFromSuperview];
  2571. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2572. }];
  2573. }
  2574. - (void)toggleReMainMenu
  2575. {
  2576. if (app.reMainMenu.isOpen) {
  2577. [app.reMainMenu close];
  2578. } else {
  2579. [self createReMainMenu];
  2580. [app.reMainMenu showFromNavigationController:self.navigationController];
  2581. // Backgroun reMenu & (Gesture)
  2582. [self createReMenuBackgroundView:app.reMainMenu];
  2583. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2584. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2585. }
  2586. }
  2587. - (void)createReSelectMenu
  2588. {
  2589. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2590. 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) {
  2591. [self deleteSelectionFile];
  2592. }];
  2593. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2594. 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) {
  2595. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2596. }];
  2597. if (app.isCryptoCloudMode) {
  2598. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2599. 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) {
  2600. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2601. }];
  2602. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2603. 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) {
  2604. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2605. }];
  2606. }
  2607. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2608. 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) {
  2609. [self downloadSelectedFiles];
  2610. }];
  2611. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2612. 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) {
  2613. [self saveSelectedFiles];
  2614. }];
  2615. // REMENU --------------------------------------------------------------------------------------------------------------
  2616. if (app.isCryptoCloudMode) {
  2617. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2618. } else {
  2619. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2620. }
  2621. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2622. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2623. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2624. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2625. app.reSelectMenu.separatorHeight = 0.5;
  2626. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2627. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2628. app.reSelectMenu.textColor = [UIColor blackColor];
  2629. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2630. app.reSelectMenu.textShadowColor = nil;
  2631. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2632. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2633. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2634. app.reSelectMenu.highlightedSeparatorColor = nil;
  2635. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2636. app.reSelectMenu.highlightedTextShadowColor = nil;
  2637. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2638. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2639. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2640. app.reSelectMenu.subtitleTextShadowColor = nil;
  2641. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2642. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2643. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2644. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2645. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2646. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2647. app.reSelectMenu.borderWidth = 0.3;
  2648. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2649. app.reSelectMenu.closeAnimationDuration = 0.2;
  2650. app.reSelectMenu.animationDuration = 0.2;
  2651. app.reSelectMenu.bounce = NO;
  2652. [app.reSelectMenu setClosePreparationBlock:^{
  2653. // Backgroun reMenu (Gesture)
  2654. [_reMenuBackgroundView removeFromSuperview];
  2655. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2656. }];
  2657. }
  2658. - (void)toggleReSelectMenu
  2659. {
  2660. if (app.reSelectMenu.isOpen) {
  2661. [app.reSelectMenu close];
  2662. } else {
  2663. [self createReSelectMenu];
  2664. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2665. // Backgroun reMenu & (Gesture)
  2666. [self createReMenuBackgroundView:app.reSelectMenu];
  2667. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2668. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2669. }
  2670. }
  2671. #pragma --------------------------------------------------------------------------------------------
  2672. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2673. #pragma --------------------------------------------------------------------------------------------
  2674. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2675. {
  2676. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2677. UITableView *tableView = (UITableView*)self.view;
  2678. CGPoint touchPoint = [recognizer locationInView:self.view];
  2679. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2680. if (indexPath)
  2681. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2682. else
  2683. _metadata = nil;
  2684. [self becomeFirstResponder];
  2685. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2686. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2687. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2688. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2689. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2690. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2691. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2692. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2693. if (app.isCryptoCloudMode)
  2694. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2695. else
  2696. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2697. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2698. [menuController setMenuVisible:YES animated:YES];
  2699. }
  2700. }
  2701. - (BOOL)canBecomeFirstResponder
  2702. {
  2703. return YES;
  2704. }
  2705. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2706. {
  2707. // For copy file, copy files, Open in ... :
  2708. //
  2709. // NO Directory
  2710. // NO Error Passcode
  2711. // NO In Session mode (download/upload)
  2712. // NO Template
  2713. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2714. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2715. // NO Cryptated with Title lenght = 0
  2716. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2717. return YES;
  2718. }
  2719. return NO;
  2720. }
  2721. if (@selector(copyFiles:) == action) {
  2722. if (_isSelectedMode) {
  2723. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2724. for (tableMetadata *metadata in selectedMetadatas) {
  2725. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2726. // NO Cryptated with Title lenght = 0
  2727. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2728. return YES;
  2729. }
  2730. }
  2731. }
  2732. return NO;
  2733. }
  2734. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2735. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2736. NSArray *items = [pasteboard items];
  2737. if ([items count] == 1) {
  2738. // Value : (NSData) fileID
  2739. NSDictionary *dic = [items objectAtIndex:0];
  2740. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2741. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2742. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2743. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2744. if (directoryUser) {
  2745. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2746. return YES;
  2747. }
  2748. return NO;
  2749. } else return NO;
  2750. }
  2751. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2752. BOOL isValid = NO;
  2753. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2754. NSArray *items = [pasteboard items];
  2755. if ([items count] <= 1) return NO;
  2756. for (NSDictionary *dic in items) {
  2757. // Value : (NSData) fileID
  2758. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2759. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2760. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2761. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2762. if (directoryUser) {
  2763. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2764. isValid = YES;
  2765. }
  2766. }
  2767. return isValid;
  2768. }
  2769. return NO;
  2770. }
  2771. /************************************ COPY ************************************/
  2772. - (void)copyFile:(id)sender
  2773. {
  2774. // Remove all item
  2775. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2776. pasteboard.items = [[NSArray alloc] init];
  2777. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2778. [self copyFileToPasteboard:_metadata];
  2779. } else {
  2780. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2781. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2782. }
  2783. }
  2784. - (void)copyFiles:(id)sender
  2785. {
  2786. // Remove all item
  2787. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2788. pasteboard.items = [[NSArray alloc] init];
  2789. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2790. for (tableMetadata *metadata in selectedMetadatas) {
  2791. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2792. [self copyFileToPasteboard:metadata];
  2793. } else {
  2794. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2795. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2796. }
  2797. }
  2798. [self tableViewSelect:NO];
  2799. }
  2800. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2801. {
  2802. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2803. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2804. // Value : (NSData) fileID
  2805. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2806. [items addObject:item];
  2807. [pasteboard setItems:items];
  2808. }
  2809. /************************************ OPEN IN ... ************************************/
  2810. - (void)openinFile:(id)sender
  2811. {
  2812. [self openIn:_metadata];
  2813. }
  2814. /************************************ PASTE ************************************/
  2815. - (void)pasteFile:(id)sender
  2816. {
  2817. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2818. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2819. }
  2820. - (void)pasteFileEncrypted:(id)sender
  2821. {
  2822. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2823. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2824. }
  2825. - (void)pasteFiles:(id)sender
  2826. {
  2827. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2828. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2829. }
  2830. - (void)pasteFilesEncrypted:(id)sender
  2831. {
  2832. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2833. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2834. }
  2835. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2836. {
  2837. for (NSDictionary *dic in items) {
  2838. // Value : (NSData) fileID
  2839. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2840. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2841. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2842. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2843. if (!metadata || !account) return;
  2844. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2845. if (directoryUser) {
  2846. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2847. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2848. [[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];
  2849. }
  2850. }
  2851. }
  2852. }
  2853. #pragma --------------------------------------------------------------------------------------------
  2854. #pragma mark ===== Lock Passcode =====
  2855. #pragma --------------------------------------------------------------------------------------------
  2856. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2857. {
  2858. return _failedAttempts;
  2859. }
  2860. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2861. {
  2862. return _lockUntilDate;
  2863. }
  2864. - (void)passcodeViewCloseButtonPressed:(id)sender
  2865. {
  2866. [self dismissViewControllerAnimated:YES completion:nil];
  2867. }
  2868. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2869. {
  2870. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2871. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2872. _lockUntilDate = nil;
  2873. _failedAttempts = 0;
  2874. aResultHandler(YES);
  2875. } else aResultHandler(NO);
  2876. } else aResultHandler(YES);
  2877. }
  2878. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2879. {
  2880. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2881. switch (aViewController.type) {
  2882. case BKPasscodeViewControllerCheckPasscodeType: {
  2883. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2884. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2885. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2886. // scriviamo il passcode
  2887. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2888. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2889. } else {
  2890. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2891. [alertView show];
  2892. }
  2893. }
  2894. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2895. // possiamo procedere alla prossima directory
  2896. [self performSegueDirectoryWithControlPasscode:false];
  2897. // avviamo la sessione Passcode Lock con now
  2898. app.sessionePasscodeLock = [NSDate date];
  2899. }
  2900. // disattivazione lock cartella
  2901. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2902. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2903. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2904. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2905. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2906. }
  2907. [self.tableView reloadData];
  2908. }
  2909. }
  2910. break;
  2911. default:
  2912. break;
  2913. }
  2914. }
  2915. - (void)comandoLockPassword
  2916. {
  2917. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2918. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2919. // se non è abilitato il Lock Passcode esci
  2920. if ([[CCUtility getBlockCode] length] == 0) {
  2921. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2922. [alertView show];
  2923. return;
  2924. }
  2925. // se è richiesta la disattivazione si chiede la password
  2926. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2927. if (directory.lock) {
  2928. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2929. viewController.delegate = self;
  2930. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2931. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2932. viewController.inputViewTitlePassword = YES;
  2933. if ([CCUtility getSimplyBlockCode]) {
  2934. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2935. viewController.passcodeInputView.maximumLength = 6;
  2936. } else {
  2937. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2938. viewController.passcodeInputView.maximumLength = 64;
  2939. }
  2940. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2941. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2942. viewController.touchIDManager = touchIDManager;
  2943. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2944. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2945. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2946. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2947. [self presentViewController:navigationController animated:YES completion:nil];
  2948. return;
  2949. }
  2950. // ---------------- ACTIVATE PASSWORD
  2951. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2952. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2953. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2954. } else {
  2955. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2956. }
  2957. }
  2958. #pragma mark -
  2959. #pragma --------------------------------------------------------------------------------------------
  2960. #pragma mark ===== Swipe Tablet -> menu =====
  2961. #pragma --------------------------------------------------------------------------------------------
  2962. // more
  2963. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2964. return NSLocalizedString(@"_more_", nil);
  2965. }
  2966. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2967. {
  2968. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2969. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2970. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2971. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2972. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2973. if (_metadata.favorite) {
  2974. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2975. } else {
  2976. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2977. }
  2978. if (_metadata.directory) {
  2979. // calcolo lockServerUrl
  2980. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2981. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2982. if (directory.lock)
  2983. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2984. else
  2985. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2986. }
  2987. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2988. /******************************************* AHKActionSheet *******************************************/
  2989. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  2990. actionSheet.animationDuration = 0.2;
  2991. actionSheet.blurRadius = 0.0f;
  2992. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  2993. actionSheet.buttonHeight = 50.0;
  2994. actionSheet.cancelButtonHeight = 50.0f;
  2995. actionSheet.separatorHeight = 5.0f;
  2996. actionSheet.automaticallyTintButtonImages = @(NO);
  2997. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2998. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2999. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3000. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3001. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3002. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3003. /******************************************* DIRECTORY *******************************************/
  3004. if (_metadata.directory) {
  3005. BOOL lockDirectory = NO;
  3006. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3007. // Directory bloccata ?
  3008. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3009. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3010. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3011. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3012. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3013. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3014. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3015. height: 50.0
  3016. type: AHKActionSheetButtonTypeDisabled
  3017. handler: nil
  3018. ];
  3019. if (!lockDirectory && !_metadata.cryptated) {
  3020. [actionSheet addButtonWithTitle:titleFavorite
  3021. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3022. backgroundColor:[UIColor whiteColor]
  3023. height: 50.0
  3024. type:AHKActionSheetButtonTypeDefault
  3025. handler:^(AHKActionSheet *as) {
  3026. // close swipe
  3027. [self setEditing:NO animated:YES];
  3028. if (_metadata.favorite)
  3029. [self removeFavorite:_metadata];
  3030. else
  3031. [self addFavorite:_metadata];
  3032. }];
  3033. }
  3034. if (_metadata.cryptated == NO && !lockDirectory) {
  3035. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3036. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3037. backgroundColor:[UIColor whiteColor]
  3038. height: 50.0
  3039. type:AHKActionSheetButtonTypeDefault
  3040. handler:^(AHKActionSheet *as) {
  3041. // close swipe
  3042. [self setEditing:NO animated:YES];
  3043. [self openWindowShare:_metadata];
  3044. }];
  3045. }
  3046. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3047. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3048. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3049. backgroundColor:[UIColor whiteColor]
  3050. height: 50.0
  3051. type:AHKActionSheetButtonTypeDefault
  3052. handler:^(AHKActionSheet *as) {
  3053. // close swipe
  3054. [self setEditing:NO animated:YES];
  3055. //chiediamo il nome del file
  3056. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3057. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3058. alertView.tag = alertRename;
  3059. UITextField *textField = [alertView textFieldAtIndex:0];
  3060. textField.text = _metadata.fileNamePrint;
  3061. [alertView show];
  3062. }];
  3063. }
  3064. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3065. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3066. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3067. backgroundColor:[UIColor whiteColor]
  3068. height: 50.0
  3069. type:AHKActionSheetButtonTypeDefault
  3070. handler:^(AHKActionSheet *as) {
  3071. // close swipe
  3072. [self setEditing:NO animated:YES];
  3073. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3074. }];
  3075. }
  3076. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3077. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3078. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3079. backgroundColor:[UIColor whiteColor]
  3080. height: 50.0
  3081. type:AHKActionSheetButtonTypeDefault
  3082. handler:^(AHKActionSheet *as) {
  3083. // close swipe
  3084. [self setEditing:NO animated:YES];
  3085. // Settings new folder Automatatic upload
  3086. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3087. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3088. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3089. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3090. if (app.activeAccount.length > 0 && app.activePhotos)
  3091. [app.activePhotos reloadDatasourceForced];
  3092. [self readFolderWithForced:YES serverUrl:serverUrl];
  3093. NSLog(@"[LOG] Update Folder Photo");
  3094. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3095. if ([autoUploadPath length] > 0)
  3096. [[CCSynchronize sharedSynchronize] readFolderServerUrl:autoUploadPath directoryID:[[NCManageDatabase sharedInstance] getDirectoryID:autoUploadPath] selector:selectorReadFolder];
  3097. }];
  3098. }
  3099. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3100. [actionSheet addButtonWithTitle:titoloLock
  3101. image:[UIImage imageNamed:@"actionSheetLock"]
  3102. backgroundColor:[UIColor whiteColor]
  3103. height: 50.0
  3104. type:AHKActionSheetButtonTypeEncrypted
  3105. handler:^(AHKActionSheet *as) {
  3106. // close swipe
  3107. [self setEditing:NO animated:YES];
  3108. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3109. }];
  3110. }
  3111. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3112. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3113. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3114. backgroundColor:[UIColor whiteColor]
  3115. height: 50.0
  3116. type:AHKActionSheetButtonTypeEncrypted
  3117. handler:^(AHKActionSheet *as) {
  3118. // close swipe
  3119. [self setEditing:NO animated:YES];
  3120. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3121. }];
  3122. }
  3123. [actionSheet show];
  3124. }
  3125. /******************************************* FILE *******************************************/
  3126. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3127. UIImage *iconHeader;
  3128. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3129. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3130. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3131. else
  3132. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3133. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3134. image: iconHeader
  3135. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3136. height: 50.0
  3137. type: AHKActionSheetButtonTypeDisabled
  3138. handler: nil
  3139. ];
  3140. if (!_metadata.cryptated) {
  3141. [actionSheet addButtonWithTitle:titleFavorite
  3142. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3143. backgroundColor:[UIColor whiteColor]
  3144. height: 50.0
  3145. type:AHKActionSheetButtonTypeDefault
  3146. handler:^(AHKActionSheet *as) {
  3147. // close swipe
  3148. [self setEditing:NO animated:YES];
  3149. if (_metadata.favorite)
  3150. [self removeFavorite:_metadata];
  3151. else
  3152. [self addFavorite:_metadata];
  3153. }];
  3154. }
  3155. if (_metadata.cryptated == NO) {
  3156. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3157. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3158. backgroundColor:[UIColor whiteColor]
  3159. height: 50.0
  3160. type:AHKActionSheetButtonTypeDefault
  3161. handler:^(AHKActionSheet *as) {
  3162. // close swipe
  3163. [self setEditing:NO animated:YES];
  3164. [self openWindowShare:_metadata];
  3165. }];
  3166. }
  3167. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3168. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3169. backgroundColor:[UIColor whiteColor]
  3170. height: 50.0
  3171. type:AHKActionSheetButtonTypeDefault
  3172. handler:^(AHKActionSheet *as) {
  3173. // close swipe
  3174. [self setEditing:NO animated:YES];
  3175. [self performSelector:@selector(openIn:) withObject:_metadata];
  3176. }];
  3177. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3178. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3179. backgroundColor:[UIColor whiteColor]
  3180. height: 50.0
  3181. type:AHKActionSheetButtonTypeDefault
  3182. handler:^(AHKActionSheet *as) {
  3183. // close swipe
  3184. [self setEditing:NO animated:YES];
  3185. //chiediamo il nome del file
  3186. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3187. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3188. alertView.tag = alertRename;
  3189. UITextField *textField = [alertView textFieldAtIndex:0];
  3190. textField.text = _metadata.fileNamePrint;
  3191. [alertView show];
  3192. }];
  3193. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3194. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3195. backgroundColor:[UIColor whiteColor]
  3196. height: 50.0
  3197. type:AHKActionSheetButtonTypeDefault
  3198. handler:^(AHKActionSheet *as) {
  3199. // close swipe
  3200. [self setEditing:NO animated:YES];
  3201. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3202. }];
  3203. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3204. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3205. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3206. backgroundColor:[UIColor whiteColor]
  3207. height: 50.0
  3208. type:AHKActionSheetButtonTypeDefault
  3209. handler:^(AHKActionSheet *as) {
  3210. // close swipe
  3211. [self setEditing:NO animated:YES];
  3212. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3213. }];
  3214. }
  3215. if (app.isCryptoCloudMode) {
  3216. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3217. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3218. backgroundColor:[UIColor whiteColor]
  3219. height: 50.0
  3220. type:AHKActionSheetButtonTypeEncrypted
  3221. handler:^(AHKActionSheet *as) {
  3222. // close swipe
  3223. [self setEditing:NO animated:YES];
  3224. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3225. }];
  3226. }
  3227. [actionSheet show];
  3228. }
  3229. /******************************************* TEMPLATE *******************************************/
  3230. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3231. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3232. image: [UIImage imageNamed:_metadata.iconName]
  3233. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3234. height: 50.0
  3235. type: AHKActionSheetButtonTypeDisabled
  3236. handler: nil
  3237. ];
  3238. if ([_metadata.model isEqualToString:@"note"]) {
  3239. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3240. image:[UIImage imageNamed:@"actionSheetRename"]
  3241. backgroundColor:[UIColor whiteColor]
  3242. height: 50.0
  3243. type:AHKActionSheetButtonTypeDefault
  3244. handler:^(AHKActionSheet *as) {
  3245. // close swipe
  3246. [self setEditing:NO animated:YES];
  3247. //chiediamo il nome del file
  3248. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3249. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3250. alertView.tag = alertRename;
  3251. UITextField *textField = [alertView textFieldAtIndex:0];
  3252. textField.text = _metadata.fileNamePrint;
  3253. [alertView show];
  3254. }];
  3255. }
  3256. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3257. image:[UIImage imageNamed:@"actionSheetMove"]
  3258. backgroundColor:[UIColor whiteColor]
  3259. height: 50.0
  3260. type:AHKActionSheetButtonTypeDefault
  3261. handler:^(AHKActionSheet *as) {
  3262. // close swipe
  3263. [self setEditing:NO animated:YES];
  3264. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3265. }];
  3266. [actionSheet show];
  3267. }
  3268. }
  3269. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3270. {
  3271. return NSLocalizedString(@"_delete_", nil);
  3272. }
  3273. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3274. {
  3275. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3276. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3277. return NO;
  3278. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3279. else return YES;
  3280. }
  3281. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3282. {
  3283. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3284. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3285. else return UITableViewCellEditingStyleDelete;
  3286. }
  3287. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3288. {
  3289. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3290. BOOL lockDirectory = NO;
  3291. // Directory locked ?
  3292. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3293. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3294. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil)
  3295. lockDirectory = YES;
  3296. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3297. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3298. return;
  3299. }
  3300. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3301. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3302. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3303. style:UIAlertActionStyleDestructive
  3304. handler:^(UIAlertAction *action) {
  3305. [self performSelector:@selector(deleteFile) withObject:nil];
  3306. }]];
  3307. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3308. style:UIAlertActionStyleCancel
  3309. handler:^(UIAlertAction *action) {
  3310. [alertController dismissViewControllerAnimated:YES completion:nil];
  3311. }]];
  3312. alertController.popoverPresentationController.sourceView = self.view;
  3313. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3314. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3315. [alertController.view layoutIfNeeded];
  3316. [self presentViewController:alertController animated:YES completion:nil];
  3317. }
  3318. }
  3319. #pragma --------------------------------------------------------------------------------------------
  3320. #pragma mark - ==== Datasource ====
  3321. #pragma --------------------------------------------------------------------------------------------
  3322. - (void)clearDateReadDataSource:(NSNotification *)notification
  3323. {
  3324. _dateReadDataSource = Nil;
  3325. [self reloadDatasource];
  3326. }
  3327. - (void)reloadDatasource
  3328. {
  3329. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3330. }
  3331. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3332. {
  3333. // test
  3334. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3335. return;
  3336. // Search Mode
  3337. if(_isSearchMode) {
  3338. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3339. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3340. } else {
  3341. [self readFolderWithForced:NO serverUrl:serverUrl];
  3342. }
  3343. [self tableViewReload];
  3344. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3345. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3346. _noFilesSearchDescription = @"";
  3347. }
  3348. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3349. _noFilesSearchTitle = @"";
  3350. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3351. }
  3352. [self.tableView reloadEmptyDataSet];
  3353. return;
  3354. }
  3355. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3356. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3357. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3358. [app.activeTransfers reloadDatasource];
  3359. } else {
  3360. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3361. if (main) {
  3362. [main reloadDatasource];
  3363. } else {
  3364. [self tableViewReload];
  3365. [app.activeTransfers reloadDatasource];
  3366. }
  3367. }
  3368. return;
  3369. }
  3370. [app.activeTransfers reloadDatasource];
  3371. // Settaggio variabili per le ottimizzazioni
  3372. _directoryGroupBy = [CCUtility getGroupBySettings];
  3373. _directoryOrder = [CCUtility getOrderSettings];
  3374. // Controllo data lettura Data Source
  3375. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3376. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3377. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3378. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3379. _dateReadDataSource = [NSDate date];
  3380. // Data Source
  3381. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3382. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3383. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3384. } else {
  3385. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3386. }
  3387. [self tableViewReload];
  3388. }
  3389. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3390. {
  3391. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3392. if (selectedRows.count > 0) {
  3393. for (NSIndexPath *selectionIndex in selectedRows) {
  3394. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3395. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3396. [metadatas addObject:metadata];
  3397. }
  3398. }
  3399. return metadatas;
  3400. }
  3401. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3402. {
  3403. NSInteger section = indexPath.section + 1;
  3404. NSInteger row = indexPath.row + 1;
  3405. NSInteger totSections =[_sectionDataSource.sections count] ;
  3406. if ((totSections < section) || (section > totSections)) {
  3407. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3408. return nil;
  3409. }
  3410. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3411. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3412. if (fileIDs) {
  3413. NSInteger totRows =[fileIDs count] ;
  3414. if ((totRows < row) || (row > totRows)) {
  3415. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3416. return nil;
  3417. }
  3418. } else {
  3419. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3420. return nil;
  3421. }
  3422. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3423. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3424. return metadata;
  3425. }
  3426. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3427. {
  3428. NSInteger totSections =[_sectionDataSource.sections count] ;
  3429. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3430. #if DEBUG
  3431. 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];
  3432. [alertView show];
  3433. #endif
  3434. return nil;
  3435. }
  3436. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3437. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3438. }
  3439. #pragma --------------------------------------------------------------------------------------------
  3440. #pragma mark - ==== Table ====
  3441. #pragma --------------------------------------------------------------------------------------------
  3442. - (void)tableViewSelect:(BOOL)edit
  3443. {
  3444. // chiudiamo eventuali swipe aperti
  3445. if (edit) [self.tableView setEditing:NO animated:NO];
  3446. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3447. [self.tableView setEditing:edit animated:YES];
  3448. _isSelectedMode = edit;
  3449. if (edit)
  3450. [self setUINavigationBarSelected];
  3451. else
  3452. [self setUINavigationBarDefault];
  3453. [self setTitle];
  3454. }
  3455. - (void)tableViewReload
  3456. {
  3457. // ricordiamoci le row selezionate
  3458. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3459. [self.tableView reloadData];
  3460. for (NSIndexPath *path in indexPaths)
  3461. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3462. [self setTableViewFooter];
  3463. if (self.tableView.editing)
  3464. [self setTitle];
  3465. }
  3466. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3467. {
  3468. return 60;
  3469. }
  3470. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3471. {
  3472. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3473. }
  3474. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3475. {
  3476. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3477. }
  3478. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3479. {
  3480. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3481. NSString *sectionTitle = [sections objectAtIndex:section];
  3482. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3483. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3484. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3485. return 20.f;
  3486. }
  3487. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3488. {
  3489. float shift;
  3490. UIVisualEffectView *visualEffectView;
  3491. // Titolo
  3492. NSString *titleSection;
  3493. // Controllo
  3494. if ([_sectionDataSource.sections count] == 0)
  3495. return nil;
  3496. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3497. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3498. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3499. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3500. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3501. else titleSection = NSLocalizedString(titleSection,nil);
  3502. // Formato titolo
  3503. NSString *currentDevice = [CCUtility currentDevice];
  3504. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3505. visualEffectView = [[UIVisualEffectView alloc] init];
  3506. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3507. } else {
  3508. UIVisualEffect *blurEffect;
  3509. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3510. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3511. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3512. }
  3513. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3514. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3515. else shift = - 20;
  3516. } else shift = - 10;
  3517. // Title
  3518. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3519. titleLabel.backgroundColor = [UIColor clearColor];
  3520. titleLabel.textColor = [UIColor blackColor];
  3521. titleLabel.font = [UIFont systemFontOfSize:12];
  3522. titleLabel.textAlignment = NSTextAlignmentLeft;
  3523. titleLabel.text = titleSection;
  3524. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3525. [visualEffectView addSubview:titleLabel];
  3526. // Elements
  3527. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3528. elementLabel.backgroundColor = [UIColor clearColor];
  3529. elementLabel.textColor = [UIColor blackColor];;
  3530. elementLabel.font = [UIFont systemFontOfSize:12];
  3531. elementLabel.textAlignment = NSTextAlignmentRight;
  3532. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3533. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3534. NSUInteger rowsCount = [metadatas count];
  3535. if (rowsCount == 0) return nil;
  3536. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3537. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3538. [visualEffectView addSubview:elementLabel];
  3539. return visualEffectView;
  3540. }
  3541. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3542. {
  3543. return [_sectionDataSource.sections indexOfObject:title];
  3544. }
  3545. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3546. {
  3547. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3548. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3549. else
  3550. return nil;
  3551. }
  3552. /*
  3553. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3554. {
  3555. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3556. }
  3557. }
  3558. */
  3559. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3560. {
  3561. NSString *typeCell;
  3562. NSString *dataFile;
  3563. NSString *lunghezzaFile;
  3564. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3565. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3566. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3567. }
  3568. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3569. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3570. else typeCell = @"CellMainTransfer";
  3571. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3572. // separator
  3573. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3574. // change color selection
  3575. UIView *selectionColor = [[UIView alloc] init];
  3576. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3577. cell.selectedBackgroundView = selectionColor;
  3578. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3579. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3580. // ----------------------------------------------------------------------------------------------------------
  3581. // DEFAULT
  3582. // ----------------------------------------------------------------------------------------------------------
  3583. cell.fileImageView.image = nil;
  3584. cell.statusImageView.image = nil;
  3585. cell.offlineImageView.image = nil;
  3586. cell.synchronizedImageView.image = nil;
  3587. cell.sharedImageView.image = nil;
  3588. cell.labelTitle.enabled = YES;
  3589. cell.labelTitle.text = @"";
  3590. cell.labelInfoFile.enabled = YES;
  3591. cell.labelInfoFile.text = @"";
  3592. cell.progressView.progress = 0.0;
  3593. cell.progressView.hidden = YES;
  3594. cell.cancelTaskButton.hidden = YES;
  3595. cell.reloadTaskButton.hidden = YES;
  3596. cell.stopTaskButton.hidden = YES;
  3597. // Encrypted color
  3598. if (metadata.cryptated) {
  3599. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3600. } else {
  3601. cell.labelTitle.textColor = [UIColor blackColor];
  3602. }
  3603. // ----------------------------------------------------------------------------------------------------------
  3604. // File Name & Folder
  3605. // ----------------------------------------------------------------------------------------------------------
  3606. // nome del file
  3607. cell.labelTitle.text = metadata.fileNamePrint;
  3608. // è una directory
  3609. if (metadata.directory) {
  3610. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3611. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3612. lunghezzaFile = @" ";
  3613. // ----------------------------------------------------------------------------------------------------------
  3614. // Favorite Folder
  3615. // ----------------------------------------------------------------------------------------------------------
  3616. if (metadata.favorite) {
  3617. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3618. }
  3619. } else {
  3620. // File
  3621. dataFile = [CCUtility dateDiff:metadata.date];
  3622. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3623. // Plist ancora da scaricare
  3624. if (metadata.cryptated && [metadata.title length] == 0) {
  3625. dataFile = @" ";
  3626. lunghezzaFile = @" ";
  3627. }
  3628. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3629. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3630. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3631. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3632. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3633. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3634. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3635. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3636. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3637. else
  3638. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3639. }
  3640. // Plist ancora da scaricare
  3641. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3642. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3643. cell.accessoryType = UITableViewCellAccessoryNone;
  3644. }
  3645. // ----------------------------------------------------------------------------------------------------------
  3646. // File Image View
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3649. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3650. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3651. if (cell.fileImageView.image == nil) {
  3652. NSString *fileID = metadata.fileID;
  3653. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3654. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3655. [app.icoImagesCache setObject:image forKey:fileID];
  3656. dispatch_async(dispatch_get_main_queue(), ^{
  3657. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3658. if (cell)
  3659. cell.fileImageView.image = image;
  3660. });
  3661. });
  3662. }
  3663. } else {
  3664. if (metadata.directory)
  3665. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3666. else
  3667. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3668. if (metadata.thumbnailExists)
  3669. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3670. }
  3671. // ----------------------------------------------------------------------------------------------------------
  3672. // Image Status cyptated & Lock Passcode
  3673. // ----------------------------------------------------------------------------------------------------------
  3674. // File Cyptated
  3675. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3676. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3677. }
  3678. // Directory con passcode lock attivato
  3679. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3680. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3681. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3682. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3683. // ----------------------------------------------------------------------------------------------------------
  3684. // Favorite
  3685. // ----------------------------------------------------------------------------------------------------------
  3686. if (metadata.favorite) {
  3687. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3688. }
  3689. // ----------------------------------------------------------------------------------------------------------
  3690. // Share
  3691. // ----------------------------------------------------------------------------------------------------------
  3692. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3693. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3694. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3695. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3696. // Aggiungiamo il Tap per le shared
  3697. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3698. if (isShare) {
  3699. if (metadata.directory) {
  3700. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3701. cell.sharedImageView.userInteractionEnabled = NO;
  3702. } else {
  3703. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3704. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3705. [tap setNumberOfTapsRequired:1];
  3706. cell.sharedImageView.userInteractionEnabled = YES;
  3707. [cell.sharedImageView addGestureRecognizer:tap];
  3708. }
  3709. }
  3710. if (isMounted) {
  3711. if (metadata.directory) {
  3712. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3713. cell.sharedImageView.userInteractionEnabled = NO;
  3714. } else {
  3715. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3716. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3717. [tap setNumberOfTapsRequired:1];
  3718. cell.sharedImageView.userInteractionEnabled = YES;
  3719. [cell.sharedImageView addGestureRecognizer:tap];
  3720. }
  3721. }
  3722. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3723. if (metadata.directory) {
  3724. if ([shareLink length] > 0)
  3725. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3726. if ([shareUserAndGroup length] > 0)
  3727. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3728. cell.sharedImageView.userInteractionEnabled = NO;
  3729. } else {
  3730. if ([shareLink length] > 0)
  3731. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3732. if ([shareUserAndGroup length] > 0)
  3733. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3734. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3735. [tap setNumberOfTapsRequired:1];
  3736. cell.sharedImageView.userInteractionEnabled = YES;
  3737. [cell.sharedImageView addGestureRecognizer:tap];
  3738. }
  3739. }
  3740. } else {
  3741. cell.sharedImageView.userInteractionEnabled = NO;
  3742. }
  3743. // ----------------------------------------------------------------------------------------------------------
  3744. // downloadFile
  3745. // ----------------------------------------------------------------------------------------------------------
  3746. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3747. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3748. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3749. // sessionTaskIdentifier : RELOAD + STOP
  3750. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3751. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3752. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3753. cell.cancelTaskButton.hidden = NO;
  3754. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3755. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3756. cell.reloadTaskButton.hidden = NO;
  3757. }
  3758. // sessionTaskIdentifierPlist : RELOAD
  3759. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3760. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3761. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3762. cell.reloadTaskButton.hidden = NO;
  3763. }
  3764. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3765. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3766. if (progress > 0) {
  3767. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3768. else cell.progressView.progressTintColor = [UIColor blackColor];
  3769. cell.progressView.progress = progress;
  3770. cell.progressView.hidden = NO;
  3771. }
  3772. // ----------------------------------------------------------------------------------------------------------
  3773. // downloadFile Error
  3774. // ----------------------------------------------------------------------------------------------------------
  3775. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3776. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3777. if ([metadata.sessionError length] == 0)
  3778. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3779. else
  3780. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3781. }
  3782. }
  3783. // ----------------------------------------------------------------------------------------------------------
  3784. // uploadFile
  3785. // ----------------------------------------------------------------------------------------------------------
  3786. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3787. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3788. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3789. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3790. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3791. cell.cancelTaskButton.hidden = NO;
  3792. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3793. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3794. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3795. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3796. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3797. cell.reloadTaskButton.hidden = NO;
  3798. cell.stopTaskButton.hidden = YES;
  3799. } else {
  3800. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3801. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3802. cell.stopTaskButton.hidden = NO;
  3803. cell.reloadTaskButton.hidden = YES;
  3804. }
  3805. // se non c'è una preview in bianconero metti l'immagine di default
  3806. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3807. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3808. cell.labelTitle.enabled = NO;
  3809. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3810. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3811. if (progress > 0) {
  3812. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3813. else cell.progressView.progressTintColor = [UIColor blackColor];
  3814. cell.progressView.progress = progress;
  3815. cell.progressView.hidden = NO;
  3816. }
  3817. // ----------------------------------------------------------------------------------------------------------
  3818. // uploadFileError
  3819. // ----------------------------------------------------------------------------------------------------------
  3820. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3821. cell.labelTitle.enabled = NO;
  3822. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3823. if ([metadata.sessionError length] == 0)
  3824. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3825. else
  3826. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3827. }
  3828. }
  3829. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3830. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3831. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3832. return cell;
  3833. }
  3834. - (void)setTableViewFooter
  3835. {
  3836. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3837. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3838. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3839. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3840. UIFont *appFont = [UIFont systemFontOfSize:12];
  3841. footerLabel.font = appFont;
  3842. footerLabel.textColor = [UIColor grayColor];
  3843. footerLabel.backgroundColor = [UIColor clearColor];
  3844. footerLabel.textAlignment = NSTextAlignmentCenter;
  3845. NSString *folders;
  3846. NSString *files;
  3847. NSString *footerText;
  3848. if (_sectionDataSource.directories > 1) {
  3849. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3850. } else if (_sectionDataSource.directories == 1){
  3851. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3852. } else {
  3853. folders = @"";
  3854. }
  3855. if (_sectionDataSource.files > 1) {
  3856. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3857. } else if (_sectionDataSource.files == 1){
  3858. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3859. } else {
  3860. files = @"";
  3861. }
  3862. if ([folders isEqualToString:@""]) {
  3863. footerText = files;
  3864. } else if ([files isEqualToString:@""]) {
  3865. footerText = folders;
  3866. } else {
  3867. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3868. }
  3869. footerLabel.text = footerText;
  3870. [footerView addSubview:footerLabel];
  3871. [self.tableView setTableFooterView:footerView];
  3872. }
  3873. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3874. {
  3875. NSString *textMessage;
  3876. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3877. // settiamo il record file.
  3878. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3879. // se non può essere selezionata deseleziona
  3880. if ([cell isEditing] == NO)
  3881. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3882. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3883. if (self.tableView.editing) {
  3884. [self setTitle];
  3885. return;
  3886. }
  3887. // test crash
  3888. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3889. if (indexPath.row >= [metadatas count]) return;
  3890. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3891. // se è in corso una sessione
  3892. if ([_metadata.session length] > 0) return;
  3893. if (_metadata.errorPasscode) {
  3894. // se UUID è nil lo sta ancora caricando quindi esci
  3895. if (!_metadata.uuid) return;
  3896. // esiste un hint ??
  3897. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3898. // qui !! la richiesta della nuova passcode
  3899. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3900. // stesso UUID ... la password è stata modificata !!!!!!
  3901. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3902. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3903. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3904. [alertView show];
  3905. } else {
  3906. // UUID diverso.
  3907. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3908. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3909. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3910. [alertView show];
  3911. }
  3912. // chiediamo la passcode e ricarichiamo tutto.
  3913. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3914. viewController.delegate = self;
  3915. viewController.fromType = CCBKPasscodeFromPasscode;
  3916. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3917. viewController.passcodeInputView.maximumLength = 64;
  3918. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3919. viewController.inputViewTitlePassword = NO;
  3920. viewController.title = [NCBrandOptions sharedInstance].brand;
  3921. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3922. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3923. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3924. [self presentViewController:navigationController animated:YES completion:nil];
  3925. }
  3926. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3927. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3928. NSString* selector;
  3929. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3930. else selector = selectorLoadPlist;
  3931. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3932. return;
  3933. }
  3934. // se il plist è caricato ed è un modello aprilo
  3935. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3936. // file
  3937. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3938. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3939. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3940. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3941. } else {
  3942. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3943. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3944. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3945. }
  3946. }
  3947. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3948. }
  3949. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3950. {
  3951. [self setTitle];
  3952. }
  3953. #pragma --------------------------------------------------------------------------------------------
  3954. #pragma mark ===== Synchronize Folder Cell =====
  3955. #pragma --------------------------------------------------------------------------------------------
  3956. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3957. {
  3958. BOOL cryptated = NO;
  3959. CCCellMain *cell;
  3960. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3961. tableMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3962. if (recordMetadata.directory == NO)
  3963. continue;
  3964. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3965. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3966. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3967. cryptated = recordMetadata.cryptated;
  3968. break;
  3969. }
  3970. }
  3971. if (!cell)
  3972. return;
  3973. if (animation) {
  3974. NSURL *myURL;
  3975. if (cryptated)
  3976. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3977. else
  3978. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3979. } else {
  3980. cell.synchronizedImageView.image = nil;
  3981. }
  3982. }
  3983. #pragma --------------------------------------------------------------------------------------------
  3984. #pragma mark ===== Navigation ====
  3985. #pragma --------------------------------------------------------------------------------------------
  3986. - (BOOL)shouldPerformSegue
  3987. {
  3988. // if background return
  3989. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3990. if (self.view.window == NO)
  3991. return NO;
  3992. // Collapsed ma siamo già in detail esci
  3993. if (self.splitViewController.isCollapsed)
  3994. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3995. // Video in esecuzione esci
  3996. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  3997. return YES;
  3998. }
  3999. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4000. {
  4001. id viewController = segue.destinationViewController;
  4002. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4003. tableMetadata *metadata;
  4004. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4005. UINavigationController *nav = viewController;
  4006. _detailViewController = (CCDetail *)nav.topViewController;
  4007. } else {
  4008. _detailViewController = segue.destinationViewController;
  4009. }
  4010. if ([sender isKindOfClass:[tableMetadata class]]) {
  4011. metadata = sender;
  4012. [allRecordsDataSourceImagesVideos addObject:sender];
  4013. } else {
  4014. metadata = _metadata;
  4015. for (NSString *fileID in _sectionDataSource.allEtag) {
  4016. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4017. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4018. [allRecordsDataSourceImagesVideos addObject:metadata];
  4019. }
  4020. }
  4021. _detailViewController.metadataDetail = metadata;
  4022. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4023. _detailViewController.dateFilterQuery = nil;
  4024. [_detailViewController setTitle:metadata.fileNamePrint];
  4025. }
  4026. // can i go to next viewcontroller
  4027. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4028. {
  4029. NSString *nomeDir;
  4030. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4031. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4032. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4033. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4034. // 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
  4035. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4036. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4037. viewController.delegate = self;
  4038. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4039. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4040. viewController.inputViewTitlePassword = YES;
  4041. if ([CCUtility getSimplyBlockCode]) {
  4042. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4043. viewController.passcodeInputView.maximumLength = 6;
  4044. } else {
  4045. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4046. viewController.passcodeInputView.maximumLength = 64;
  4047. }
  4048. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4049. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4050. viewController.touchIDManager = touchIDManager;
  4051. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4052. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4053. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4054. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4055. [self presentViewController:navController animated:YES completion:nil];
  4056. return;
  4057. }
  4058. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4059. else nomeDir = _metadata.fileName;
  4060. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4061. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4062. if (viewController.isViewLoaded == false || viewController == nil) {
  4063. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4064. viewController.isFolderEncrypted = _metadata.cryptated;
  4065. viewController.serverUrl = serverUrlPush;
  4066. viewController.titleMain = _metadata.fileNamePrint;
  4067. viewController.textBackButton = _titleMain;
  4068. // save self
  4069. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4070. }
  4071. // OFF SearchBar
  4072. [viewController cancelSearchBar];
  4073. [self.navigationController pushViewController:viewController animated:YES];
  4074. }
  4075. }
  4076. @end