CCMain.m 252 KB

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