CCMain.m 252 KB

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