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