CCMain.m 253 KB

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