CCMain.m 250 KB

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