CCMain.m 254 KB

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