CCMain.m 252 KB

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