CCMain.m 252 KB

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