CCMain.m 253 KB

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