CCMain.m 254 KB

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