CCMain.m 255 KB

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