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