CCMain.m 253 KB

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