CCMain.m 251 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 "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCBridgeSwift.h"
  37. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  38. {
  39. tableMetadata *_metadata;
  40. BOOL _isRoot;
  41. BOOL _isViewDidLoad;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. BOOL _loadingFolder;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  104. _statusSwipeCell = [NSMutableDictionary new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [CCNetworking sharedNetworking].delegate = self;
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl];
  147. // Read (File) Folder
  148. [self readFileReloadFolder];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  157. [self.searchController.searchBar sizeToFit];
  158. self.searchController.searchBar.delegate = self;
  159. // Hide Search Filed on Load
  160. self.tableView.tableHeaderView = self.searchController.searchBar;
  161. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  162. }
  163. // Apparirà
  164. - (void)viewWillAppear:(BOOL)animated
  165. {
  166. [super viewWillAppear:animated];
  167. // test
  168. if (app.activeAccount.length == 0)
  169. return;
  170. // Settings this folder & delegate & Loading datasource
  171. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  172. [CCNetworking sharedNetworking].delegate = self;
  173. // Color
  174. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  175. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  176. if (_isSelectedMode)
  177. [self setUINavigationBarSelected];
  178. else
  179. [self setUINavigationBarDefault];
  180. // If not editing mode remove _selectedFileIDs
  181. if (!self.tableView.editing)
  182. [_selectedFileIDsMetadatas removeAllObjects];
  183. // Plus Button
  184. [app plusButtonVisibile:true];
  185. }
  186. // E' arrivato
  187. - (void)viewDidAppear:(BOOL)animated
  188. {
  189. [super viewDidAppear:animated];
  190. // Active Main
  191. app.activeMain = self;
  192. // Test viewDidLoad
  193. if (_isViewDidLoad) {
  194. _isViewDidLoad = NO;
  195. } else {
  196. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  197. // Load Datasource
  198. [self reloadDatasource:_serverUrl];
  199. // Read (file) Folder
  200. [self readFileReloadFolder];
  201. }
  202. }
  203. // Title
  204. [self setTitle];
  205. }
  206. - (void)viewWillDisappear:(BOOL)animated
  207. {
  208. [super viewWillDisappear:animated];
  209. [self closeAllMenu];
  210. }
  211. - (void)didReceiveMemoryWarning
  212. {
  213. [super didReceiveMemoryWarning];
  214. // Dispose of any resources that can be recreated.
  215. }
  216. - (BOOL)prefersStatusBarHidden
  217. {
  218. return NO;
  219. }
  220. // detect scroll for remove keyboard in search mode
  221. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  222. {
  223. if (_isSearchMode && scrollView == self.tableView) {
  224. [self.searchController.searchBar endEditing:YES];
  225. }
  226. }
  227. - (void)changeTheming
  228. {
  229. if (self.isViewLoaded && self.view.window)
  230. [app changeTheming:self];
  231. // Refresh control
  232. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  233. // Reload Table View
  234. [self tableViewReloadData];
  235. }
  236. #pragma --------------------------------------------------------------------------------------------
  237. #pragma mark ===== Initizlize Mail =====
  238. #pragma --------------------------------------------------------------------------------------------
  239. - (void)initializeMain:(NSNotification *)notification
  240. {
  241. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  242. _directoryGroupBy = nil;
  243. _directoryOrder = nil;
  244. _dateReadDataSource = nil;
  245. // test
  246. if (app.activeAccount.length == 0)
  247. return;
  248. if ([app.listMainVC count] == 0 || _isRoot) {
  249. // This is Root home main add list
  250. appDelegate.homeMain = self;
  251. _isRoot = YES;
  252. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  253. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  254. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  255. // go Home
  256. [self.navigationController popToRootViewControllerAnimated:NO];
  257. // Crypto Mode
  258. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  259. appDelegate.isCryptoCloudMode = NO;
  260. } else {
  261. appDelegate.isCryptoCloudMode = YES;
  262. }
  263. _isFolderEncrypted = NO;
  264. // setting Networking
  265. [CCNetworking sharedNetworking].delegate = self;
  266. [[CCNetworking sharedNetworking] settingAccount];
  267. // Remove search mode
  268. [self cancelSearchBar];
  269. // populate shared Link & User
  270. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  271. if (results) {
  272. appDelegate.sharesLink = results[0];
  273. appDelegate.sharesUserAndGroup = results[1];
  274. }
  275. // Load Datasource
  276. [self reloadDatasource:_serverUrl];
  277. // Read (File) Folder
  278. [self readFileReloadFolder];
  279. // Setting Theming
  280. [app settingThemingColorBrand];
  281. // Load photo datasorce
  282. if (appDelegate.activePhotos)
  283. [appDelegate.activePhotos reloadDatasourceForced];
  284. // remove all of detail
  285. if (appDelegate.activeDetail)
  286. [appDelegate.activeDetail removeAllView];
  287. // remove all Notification Messages
  288. [appDelegate.listOfNotifications removeAllObjects];
  289. // Initializations
  290. [appDelegate applicationInitialized];
  291. } else {
  292. // reload datasource
  293. [self reloadDatasource:_serverUrl];
  294. }
  295. }
  296. #pragma --------------------------------------------------------------------------------------------
  297. #pragma mark ==== DZNEmptyDataSetSource ====
  298. #pragma --------------------------------------------------------------------------------------------
  299. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  300. {
  301. if (_loadingFolder)
  302. return NO;
  303. else
  304. return YES;
  305. }
  306. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  307. {
  308. return [UIColor whiteColor];
  309. }
  310. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  311. {
  312. if (_isSearchMode)
  313. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  314. else
  315. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  316. }
  317. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  318. {
  319. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  320. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  321. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  322. activityView.color = [NCBrandColor sharedInstance].brand;
  323. [activityView startAnimating];
  324. return activityView;
  325. }
  326. return nil;
  327. }
  328. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  329. {
  330. NSString *text;
  331. if (_isSearchMode) {
  332. text = _noFilesSearchTitle;
  333. } else {
  334. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  335. }
  336. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  337. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  338. }
  339. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  340. {
  341. NSString *text;
  342. if (_isSearchMode) {
  343. text = _noFilesSearchDescription;
  344. } else {
  345. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  346. }
  347. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  348. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  349. paragraph.alignment = NSTextAlignmentCenter;
  350. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  351. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  352. }
  353. #pragma --------------------------------------------------------------------------------------------
  354. #pragma mark ===== Text Field =====
  355. #pragma --------------------------------------------------------------------------------------------
  356. - (void)minCharTextFieldDidChange:(UITextField *)sender
  357. {
  358. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  359. if (alertController)
  360. {
  361. UITextField *fileName = alertController.textFields.firstObject;
  362. UIAlertAction *okAction = alertController.actions.lastObject;
  363. okAction.enabled = fileName.text.length > 0;
  364. }
  365. }
  366. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  367. [textField selectAll:textField];
  368. }
  369. #pragma --------------------------------------------------------------------------------------------
  370. #pragma mark ===== Graphic Window =====
  371. #pragma --------------------------------------------------------------------------------------------
  372. - (void)createRefreshControl
  373. {
  374. _refreshControl = [UIRefreshControl new];
  375. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  376. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  377. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  378. [self setRefreshControl:_refreshControl];
  379. }
  380. - (void)deleteRefreshControl
  381. {
  382. [_refreshControl endRefreshing];
  383. self.refreshControl = nil;
  384. }
  385. - (void)refreshControlTarget
  386. {
  387. [self readFolder:_serverUrl];
  388. // Actuate `Peek` feedback (weak boom)
  389. AudioServicesPlaySystemSound(1519);
  390. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  391. }
  392. - (void)setTitle
  393. {
  394. // Color text self.navigationItem.title
  395. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  396. if (_isSelectedMode) {
  397. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  398. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  399. self.navigationItem.titleView = nil;
  400. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  401. } else {
  402. // we are in home : LOGO BRAND
  403. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  404. self.navigationItem.title = nil;
  405. if ([app.reachability isReachable] == NO)
  406. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  407. else
  408. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  409. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  410. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  411. [singleTap setNumberOfTapsRequired:1];
  412. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  413. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  414. } else {
  415. self.navigationItem.title = _titleMain;
  416. }
  417. }
  418. }
  419. - (void)setUINavigationBarDefault
  420. {
  421. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  422. UIBarButtonItem *buttonMore, *buttonNotification;
  423. // =
  424. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  425. buttonMore.enabled = true;
  426. // <
  427. self.navigationController.navigationBar.hidden = NO;
  428. // Notification
  429. if ([app.listOfNotifications count] > 0) {
  430. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  431. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  432. buttonNotification.enabled = true;
  433. }
  434. if (buttonNotification)
  435. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  436. else
  437. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  438. self.navigationItem.leftBarButtonItem = nil;
  439. }
  440. - (void)setUINavigationBarSelected
  441. {
  442. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  443. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  444. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  445. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  446. self.navigationItem.leftBarButtonItem = leftButton;
  447. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  448. }
  449. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  450. {
  451. [self closeAllMenu];
  452. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  453. }];
  454. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  455. }
  456. - (void)cancelSelect
  457. {
  458. [self tableViewSelect:NO];
  459. [app.reSelectMenu close];
  460. }
  461. - (void)closeAllMenu
  462. {
  463. // close Menu
  464. [app.reSelectMenu close];
  465. [app.reMainMenu close];
  466. // Close Menu Logo
  467. [CCMenuAccount dismissMenu];
  468. }
  469. #pragma --------------------------------------------------------------------------------------------
  470. #pragma mark ===== Document Picker =====
  471. #pragma --------------------------------------------------------------------------------------------
  472. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  473. {
  474. NSLog(@"Cancelled");
  475. }
  476. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  477. {
  478. NSLog(@"Cancelled");
  479. }
  480. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  481. {
  482. documentPicker.delegate = self;
  483. [self presentViewController:documentPicker animated:YES completion:nil];
  484. }
  485. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  486. {
  487. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  488. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  489. __block NSError *error;
  490. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  491. NSString *fileName = [url lastPathComponent];
  492. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  493. NSData *data = [NSData dataWithContentsOfURL:newURL];
  494. if (data && error == nil) {
  495. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  496. // Upload File
  497. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  498. } else {
  499. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  500. }
  501. } else {
  502. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  503. }
  504. }];
  505. }
  506. }
  507. - (void)openImportDocumentPicker
  508. {
  509. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  510. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  511. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  512. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  513. documentProviderMenu.delegate = self;
  514. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  515. }
  516. #pragma --------------------------------------------------------------------------------------------
  517. #pragma mark ===== Assets Picker =====
  518. #pragma --------------------------------------------------------------------------------------------
  519. -(void)dismissFormUploadAssets
  520. {
  521. [self reloadDatasource];
  522. }
  523. - (void)openAssetsPickerController
  524. {
  525. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  526. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  527. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  528. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  529. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  530. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  531. dispatch_async(dispatch_get_main_queue(), ^{
  532. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  533. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  534. // init picker
  535. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  536. // set delegate
  537. picker.delegate = self;
  538. // to show selection order
  539. //picker.showsSelectionIndex = YES;
  540. // to present picker as a form sheet in iPad
  541. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  542. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  543. // present picker
  544. [self presentViewController:picker animated:YES completion:nil];
  545. });
  546. }];
  547. }
  548. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  549. {
  550. if (picker.selectedAssets.count > k_pickerControllerMax) {
  551. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  552. return NO;
  553. }
  554. return YES;
  555. }
  556. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  557. {
  558. [picker dismissViewControllerAnimated:YES completion:^{
  559. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session delegate:self];
  560. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  561. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  562. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  563. [self presentViewController:navigationController animated:YES completion:nil];
  564. }];
  565. }
  566. #pragma --------------------------------------------------------------------------------------------
  567. #pragma mark ===== Create New (OpenModel) =====
  568. #pragma --------------------------------------------------------------------------------------------
  569. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  570. {
  571. UIViewController *viewController;
  572. NSString *fileName, *uuid, *fileID, *serverUrl;
  573. NSIndexPath *index = [self.tableView indexPathForSelectedRow];
  574. [self.tableView deselectRowAtIndexPath:index animated:NO];
  575. if (isnew) {
  576. fileName = nil;
  577. uuid = [CCUtility getUUID];
  578. fileID = nil;
  579. serverUrl = _serverUrl;
  580. } else {
  581. fileName = _metadata.fileName;
  582. uuid = _metadata.uuid;
  583. fileID = _metadata.fileID;
  584. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  585. }
  586. if (serverUrl) {
  587. if ([tipo isEqualToString:@"cartadicredito"])
  588. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  589. if ([tipo isEqualToString:@"bancomat"])
  590. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  591. if ([tipo isEqualToString:@"contocorrente"])
  592. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  593. if ([tipo isEqualToString:@"accountweb"])
  594. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  595. if ([tipo isEqualToString:@"patenteguida"])
  596. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  597. if ([tipo isEqualToString:@"cartaidentita"])
  598. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  599. if ([tipo isEqualToString:@"passaporto"])
  600. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  601. if ([tipo isEqualToString:@"note"]) {
  602. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  603. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  604. [self presentViewController:navigationController animated:YES completion:nil];
  605. } else {
  606. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  607. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  608. [self presentViewController:navigationController animated:YES completion:nil];
  609. }
  610. }
  611. }
  612. // New folder or new photo or video
  613. - (void)returnCreate:(NSInteger)type
  614. {
  615. switch (type) {
  616. /* PLAIN */
  617. case k_returnCreateFolderPlain: {
  618. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  619. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  620. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  621. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  622. }];
  623. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  624. NSLog(@"Cancel action");
  625. }];
  626. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  627. UITextField *fileName = alertController.textFields.firstObject;
  628. [self createFolder:fileName.text autoUploadDirectory:NO];
  629. }];
  630. okAction.enabled = NO;
  631. [alertController addAction:cancelAction];
  632. [alertController addAction:okAction];
  633. [self presentViewController:alertController animated:YES completion:nil];
  634. }
  635. break;
  636. case k_returnCreateFotoVideoPlain: {
  637. _isPickerCriptate = false;
  638. [self openAssetsPickerController];
  639. }
  640. break;
  641. case k_returnCreateFilePlain: {
  642. _isPickerCriptate = false;
  643. [self openImportDocumentPicker];
  644. }
  645. break;
  646. /* ENCRYPTED */
  647. case k_returnCreateFolderEncrypted: {
  648. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  649. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  650. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  651. }];
  652. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  653. NSLog(@"Cancel action");
  654. }];
  655. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  656. UITextField *fileName = alertController.textFields.firstObject;
  657. [self createFolderEncrypted:fileName.text];
  658. }];
  659. okAction.enabled = NO;
  660. [alertController addAction:cancelAction];
  661. [alertController addAction:okAction];
  662. [self presentViewController:alertController animated:YES completion:nil];
  663. }
  664. break;
  665. case k_returnCreateFotoVideoEncrypted: {
  666. _isPickerCriptate = true;
  667. [self openAssetsPickerController];
  668. }
  669. break;
  670. case k_returnCreateFileEncrypted: {
  671. _isPickerCriptate = true;
  672. [self openImportDocumentPicker];
  673. }
  674. break;
  675. case k_returnCreateFileText: {
  676. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  677. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  678. [self presentViewController:navigationController animated:YES completion:nil];
  679. }
  680. break;
  681. /* UTILITY */
  682. case k_returnNote:
  683. [self openModel:@"note" isNew:true];
  684. break;
  685. case k_returnAccountWeb:
  686. [self openModel:@"accountweb" isNew:true];
  687. break;
  688. /* BANK */
  689. case k_returnCartaDiCredito:
  690. [self openModel:@"cartadicredito" isNew:true];
  691. break;
  692. case k_returnBancomat:
  693. [self openModel:@"bancomat" isNew:true];
  694. break;
  695. case k_returnContoCorrente:
  696. [self openModel:@"contocorrente" isNew:true];
  697. break;
  698. /* DOCUMENT */
  699. case k_returnPatenteGuida:
  700. [self openModel:@"patenteguida" isNew:true];
  701. break;
  702. case k_returnCartaIdentita:
  703. [self openModel:@"cartaidentita" isNew:true];
  704. break;
  705. case k_returnPassaporto:
  706. [self openModel:@"passaporto" isNew:true];
  707. break;
  708. }
  709. }
  710. #pragma --------------------------------------------------------------------------------------------
  711. #pragma mark ===== Save selected File =====
  712. #pragma --------------------------------------------------------------------------------------------
  713. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  714. {
  715. if (error)
  716. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  717. else
  718. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  719. }
  720. - (void)saveSelectedFiles
  721. {
  722. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  723. return;
  724. NSLog(@"[LOG] Start download selected files ...");
  725. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  726. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  727. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  728. for (tableMetadata *metadata in metadatas) {
  729. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  730. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  731. if (serverUrl)
  732. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  733. }
  734. }
  735. [_hud hideHud];
  736. });
  737. [self tableViewSelect:NO];
  738. }
  739. #pragma --------------------------------------------------------------------------------------------
  740. #pragma mark ===== Change Password =====
  741. #pragma --------------------------------------------------------------------------------------------
  742. - (void) loginSuccess:(NSInteger)loginType
  743. {
  744. [self readFolder:_serverUrl];
  745. }
  746. - (void)changePasswordAccount
  747. {
  748. // Brand
  749. if ([NCBrandOptions sharedInstance].use_login_web) {
  750. _loginWeb = [CCLoginWeb new];
  751. _loginWeb.delegate = self;
  752. _loginWeb.loginType = loginModifyPasswordUser;
  753. dispatch_async(dispatch_get_main_queue(), ^ {
  754. [_loginWeb presentModalWithDefaultTheme:self];
  755. });
  756. } else {
  757. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  758. _loginVC.delegate = self;
  759. _loginVC.loginType = loginModifyPasswordUser;
  760. [self presentViewController:_loginVC animated:YES completion:nil];
  761. }
  762. }
  763. #pragma mark -
  764. #pragma --------------------------------------------------------------------------------------------
  765. #pragma mark ===== Peek & Pop =====
  766. #pragma --------------------------------------------------------------------------------------------
  767. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  768. {
  769. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  770. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  771. if (metadata.thumbnailExists && !metadata.cryptated) {
  772. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  773. if (cell) {
  774. previewingContext.sourceRect = cell.frame;
  775. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  776. vc.delegate = self;
  777. vc.metadata = metadata;
  778. return vc;
  779. }
  780. }
  781. return nil;
  782. }
  783. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  784. {
  785. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  786. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  787. }
  788. #pragma mark -
  789. #pragma --------------------------------------------------------------------------------------------
  790. #pragma mark ==== External Sites ====
  791. #pragma --------------------------------------------------------------------------------------------
  792. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  793. {
  794. [[NCManageDatabase sharedInstance] deleteExternalSites];
  795. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  796. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  797. }
  798. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  799. {
  800. NSLog(@"[LOG] No External Sites found");
  801. }
  802. #pragma --------------------------------------------------------------------------------------------
  803. #pragma mark ==== Activity ====
  804. #pragma --------------------------------------------------------------------------------------------
  805. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  806. {
  807. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  808. // Reload Activity Data Source
  809. [app.activeActivity reloadDatasource];
  810. }
  811. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  812. {
  813. NSLog(@"[LOG] No Activity found");
  814. }
  815. #pragma --------------------------------------------------------------------------------------------
  816. #pragma mark ==== Notification ====
  817. #pragma --------------------------------------------------------------------------------------------
  818. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  819. {
  820. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  821. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  822. // Order by date
  823. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  824. OCNotifications *notification1 = obj1, *notification2 = obj2;
  825. return [notification2.date compare: notification1.date];
  826. }];
  827. // verify if listOfNotifications is changed
  828. NSString *old = @"", *new = @"";
  829. for (OCNotifications *notification in listOfNotifications)
  830. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  831. for (OCNotifications *notification in appDelegate.listOfNotifications)
  832. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  833. if (![new isEqualToString:old]) {
  834. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  835. // reload Notification view
  836. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  837. }
  838. // Update NavigationBar
  839. if (!_isSelectedMode) {
  840. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  841. }
  842. });
  843. }
  844. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  845. {
  846. // Update NavigationBar
  847. if (!_isSelectedMode)
  848. [self setUINavigationBarDefault];
  849. }
  850. - (void)viewNotification
  851. {
  852. if ([app.listOfNotifications count] > 0) {
  853. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  854. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  855. [self presentViewController:notificationVC animated:YES completion:nil];
  856. }
  857. }
  858. #pragma --------------------------------------------------------------------------------------------
  859. #pragma mark ==== User Profile ====
  860. #pragma --------------------------------------------------------------------------------------------
  861. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  862. {
  863. if (errorCode == 401)
  864. [self changePasswordAccount];
  865. }
  866. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  867. {
  868. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  869. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  870. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  871. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  872. if (avatar)
  873. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  874. else
  875. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  876. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  877. });
  878. }
  879. #pragma --------------------------------------------------------------------------------------------
  880. #pragma mark ==== Capabilities ====
  881. #pragma --------------------------------------------------------------------------------------------
  882. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  883. {
  884. // Change Theming color
  885. [app settingThemingColorBrand];
  886. if (errorCode == 401)
  887. [self changePasswordAccount];
  888. }
  889. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  890. {
  891. // Update capabilities db
  892. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  893. // ------ THEMING -----------------------------------------------------------------------
  894. // Download Theming Background & Change Theming color
  895. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  896. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  897. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  898. if (themingBackground)
  899. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  900. else
  901. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  902. }
  903. dispatch_async(dispatch_get_main_queue(), ^{
  904. [app settingThemingColorBrand];
  905. });
  906. });
  907. // ------ SEARCH ------------------------------------------------------------------------
  908. // Search bar if change version
  909. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  910. [self cancelSearchBar];
  911. }
  912. // ------ GET SERVICE SERVER ------------------------------------------------------------
  913. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  914. // Read External Sites
  915. if (capabilities.isExternalSitesServerEnabled) {
  916. metadataNet.action = actionGetExternalSitesServer;
  917. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  918. }
  919. // Read Share
  920. if (capabilities.isFilesSharingAPIEnabled) {
  921. [app.sharesID removeAllObjects];
  922. metadataNet.action = actionReadShareServer;
  923. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  924. }
  925. // Read Notification
  926. metadataNet.action = actionGetNotificationServer;
  927. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  928. // Read User Profile
  929. metadataNet.action = actionGetUserProfile;
  930. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  931. // Read Activity
  932. metadataNet.action = actionGetActivityServer;
  933. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  934. }
  935. #pragma mark -
  936. #pragma --------------------------------------------------------------------------------------------
  937. #pragma mark ==== Request Server Information ====
  938. #pragma --------------------------------------------------------------------------------------------
  939. - (void)requestServerCapabilities
  940. {
  941. // test
  942. if (app.activeAccount.length == 0)
  943. return;
  944. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  945. metadataNet.action = actionGetCapabilities;
  946. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  947. }
  948. #pragma mark -
  949. #pragma --------------------------------------------------------------------------------------------
  950. #pragma mark ==== Middleware Ping ====
  951. #pragma --------------------------------------------------------------------------------------------
  952. - (void)middlewarePing
  953. {
  954. // test
  955. if (app.activeAccount.length == 0)
  956. return;
  957. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  958. metadataNet.action = actionMiddlewarePing;
  959. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  960. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  961. }
  962. #pragma mark -
  963. #pragma --------------------------------------------------------------------------------------------
  964. #pragma mark ==== Download Thumbnail Delegate ====
  965. #pragma --------------------------------------------------------------------------------------------
  966. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  967. {
  968. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  969. if ([self indexPathIsValid:indexPath]) {
  970. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  971. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  972. }
  973. }
  974. #pragma --------------------------------------------------------------------------------------------
  975. #pragma mark ==== Download ====
  976. #pragma --------------------------------------------------------------------------------------------
  977. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  978. {
  979. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  980. // File do not exists on server, remove in local
  981. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  982. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  983. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  984. if (metadata.directory && serverUrl) {
  985. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  986. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  987. }
  988. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  989. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  990. }
  991. if ([selector isEqualToString:selectorLoadViewImage]) {
  992. dispatch_async(dispatch_get_main_queue(), ^{
  993. // Updating Detail
  994. if (app.activeDetail)
  995. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  996. // Updating Photos
  997. if (app.activePhotos)
  998. [app.activePhotos downloadFileFailure:errorCode];
  999. });
  1000. } else {
  1001. if (errorCode != kCFURLErrorCancelled)
  1002. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1003. }
  1004. [self reloadDatasource:serverUrl];
  1005. }
  1006. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1007. {
  1008. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1009. if (metadata == nil)
  1010. return;
  1011. // Download
  1012. if ([selector isEqualToString:selectorDownloadFile]) {
  1013. [self reloadDatasource:serverUrl];
  1014. }
  1015. // Synchronized
  1016. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1017. [self reloadDatasource:serverUrl];
  1018. }
  1019. // add Favorite
  1020. if ([selector isEqualToString:selectorAddFavorite]) {
  1021. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1022. }
  1023. // encrypted file
  1024. if ([selector isEqualToString:selectorEncryptFile]) {
  1025. [self encryptedFile:metadata];
  1026. }
  1027. // decrypted file
  1028. if ([selector isEqualToString:selectorDecryptFile]) {
  1029. [self decryptedFile:metadata];
  1030. }
  1031. // open View File
  1032. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1033. [self reloadDatasource:serverUrl];
  1034. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1035. selector = selectorOpenIn;
  1036. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1037. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1038. selector = selectorOpenIn;
  1039. } else {
  1040. _metadata = metadata;
  1041. if ([self shouldPerformSegue])
  1042. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1043. }
  1044. }
  1045. // Open with...
  1046. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1047. [self reloadDatasource:serverUrl];
  1048. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1049. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1050. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1051. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1052. _docController.delegate = self;
  1053. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1054. }
  1055. // Save to Photo Album
  1056. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1057. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1058. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1059. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1060. if (image)
  1061. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1062. else
  1063. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1064. }
  1065. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1066. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1067. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1068. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1069. } else {
  1070. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1071. }
  1072. }
  1073. [self reloadDatasource:serverUrl];
  1074. }
  1075. // Copy File
  1076. if ([selector isEqualToString:selectorLoadCopy]) {
  1077. [self reloadDatasource:serverUrl];
  1078. [self copyFileToPasteboard:metadata];
  1079. }
  1080. // download and view a template
  1081. if ([selector isEqualToString:selectorLoadModelView]) {
  1082. // se è un template aggiorniamo anche nel FileSystem
  1083. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1084. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1085. }
  1086. [self openModel:metadata.model isNew:false];
  1087. [self reloadDatasource:serverUrl];
  1088. }
  1089. //download file plist
  1090. if ([selector isEqualToString:selectorLoadPlist]) {
  1091. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1092. long countSelectorLoadPlist = 0;
  1093. for (NSOperation *operation in [app.netQueue operations]) {
  1094. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1095. countSelectorLoadPlist++;
  1096. }
  1097. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1098. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1099. dispatch_async(dispatch_get_main_queue(), ^{
  1100. [self reloadDatasource:serverUrl];
  1101. });
  1102. }
  1103. });
  1104. }
  1105. //selectorLoadViewImage
  1106. if ([selector isEqualToString:selectorLoadViewImage]) {
  1107. // Detail
  1108. if (app.activeDetail)
  1109. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1110. // Photos
  1111. if (app.activePhotos)
  1112. [app.activePhotos downloadFileSuccess:metadata];
  1113. [self reloadDatasource:serverUrl];
  1114. }
  1115. // if exists postselector call self with selectorPost
  1116. if ([selectorPost length] > 0)
  1117. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1118. }
  1119. - (void)downloadSelectedFilesFolders
  1120. {
  1121. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1122. return;
  1123. NSLog(@"[LOG] Start download selected ...");
  1124. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1125. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1126. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1127. for (tableMetadata *metadata in selectedMetadatas) {
  1128. if ([metadata.type isEqualToString: k_metadataType_file]) {
  1129. if (metadata.directory) {
  1130. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1131. if (serverUrl) {
  1132. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1133. [[CCSynchronize sharedSynchronize] synchronizedFolder:serverUrl selector:selectorReadFolderWithDownload];
  1134. }
  1135. } else {
  1136. [[CCSynchronize sharedSynchronize] synchronizedFile:metadata selector:selectorReadFileWithDownload];
  1137. }
  1138. }
  1139. }
  1140. [_hud hideHud];
  1141. });
  1142. [self tableViewSelect:NO];
  1143. }
  1144. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1145. {
  1146. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1147. for (tableMetadata *metadata in metadatas) {
  1148. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1149. [[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];
  1150. }
  1151. }
  1152. }
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. #pragma mark ===== Upload new Photos/Videos =====
  1155. #pragma --------------------------------------------------------------------------------------------
  1156. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1157. {
  1158. // Auto Upload
  1159. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1160. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1161. // Change priority Auto Upload
  1162. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1163. // Activity
  1164. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1165. }
  1166. if (errorCode != kCFURLErrorCancelled)
  1167. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1168. } else {
  1169. // Delete record on Table Auto Upload
  1170. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1171. // Activity
  1172. [[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];
  1173. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1174. }
  1175. } else {
  1176. // Read File test do not exists
  1177. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1178. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1179. // reUpload
  1180. if (metadata)
  1181. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1182. }
  1183. // Print error
  1184. else if (errorCode != kCFURLErrorCancelled) {
  1185. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1186. }
  1187. }
  1188. [self reloadDatasource:serverUrl];
  1189. }
  1190. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1191. {
  1192. // Auto Upload
  1193. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1194. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1195. // ONLY BACKGROUND
  1196. [app performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1197. } else {
  1198. // ONLY FOREFROUND
  1199. [app performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1200. }
  1201. }
  1202. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1203. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1204. [self readFolder:serverUrl];
  1205. } else {
  1206. [self reloadDatasource:serverUrl];
  1207. }
  1208. });
  1209. }
  1210. //
  1211. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1212. //
  1213. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1214. {
  1215. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1216. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1217. });
  1218. }
  1219. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1220. {
  1221. NSArray *assets = [arguments objectAtIndex:0];
  1222. NSString *serverUrl = [arguments objectAtIndex:1];
  1223. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1224. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1225. NSString *session = [arguments objectAtIndex:4];
  1226. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1227. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1228. if (!directoryID) return;
  1229. // if request create the folder for Photos & the subfolders
  1230. if ([autoUploadPath isEqualToString:serverUrl])
  1231. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1232. return;
  1233. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1234. for (PHAsset *asset in assets) {
  1235. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1236. NSDate *assetDate = asset.creationDate;
  1237. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1238. // Create serverUrl if use sub folder
  1239. if (useSubFolder) {
  1240. [formatter setDateFormat:@"yyyy"];
  1241. NSString *yearString = [formatter stringFromDate:assetDate];
  1242. [formatter setDateFormat:@"MM"];
  1243. NSString *monthString = [formatter stringFromDate:assetDate];
  1244. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1245. }
  1246. // Check if is in upload
  1247. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1248. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1249. if ([isRecordInSessions count] > 0) {
  1250. // next upload
  1251. continue;
  1252. } else {
  1253. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1254. if (cryptated) {
  1255. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1256. metadataNet.cryptated = cryptated;
  1257. metadataNet.fileName = fileName;
  1258. metadataNet.session = session;
  1259. metadataNet.selector = selectorUploadFile;
  1260. metadataNet.selectorPost = nil;
  1261. metadataNet.serverUrl = serverUrl;
  1262. metadataNet.taskStatus = k_taskStatusResume;
  1263. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1264. } else {
  1265. metadataNet.action = actionReadFile;
  1266. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1267. metadataNet.cryptated = cryptated;
  1268. metadataNet.fileName = fileName;
  1269. metadataNet.session = session;
  1270. metadataNet.selector = selectorReadFileUploadFile;
  1271. metadataNet.serverUrl = serverUrl;
  1272. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1273. }
  1274. }
  1275. }
  1276. }
  1277. #pragma --------------------------------------------------------------------------------------------
  1278. #pragma mark ==== Read File ====
  1279. #pragma --------------------------------------------------------------------------------------------
  1280. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1281. {
  1282. // Read Folder
  1283. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1284. //[self readFolderWithForced:NO serverUrl:metadataNet.serverUrl];
  1285. }
  1286. // UploadFile
  1287. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1288. // File not exists
  1289. if (errorCode == 404) {
  1290. metadataNet.errorCode = 0;
  1291. metadataNet.selector = selectorUploadFile;
  1292. metadataNet.selectorPost = nil;
  1293. metadataNet.taskStatus = k_taskStatusResume;
  1294. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1295. } else {
  1296. // error ho many retry befor notification and go to on next asses
  1297. if (metadataNet.errorRetry < 3) {
  1298. // Retry read file
  1299. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1300. } else {
  1301. // STOP check file, view message error
  1302. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1303. }
  1304. }
  1305. }
  1306. }
  1307. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1308. {
  1309. // Read Folder
  1310. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1311. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1312. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1313. [self readFolder:metadataNet.serverUrl];
  1314. }
  1315. }
  1316. // UploadFile
  1317. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1318. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1319. metadataNet.selector = selectorUploadFile;
  1320. metadataNet.selectorPost = nil;
  1321. metadataNet.taskStatus = k_taskStatusResume;
  1322. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1323. }
  1324. }
  1325. - (void)readFileReloadFolder
  1326. {
  1327. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1328. return;
  1329. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1330. metadataNet.action = actionReadFile;
  1331. metadataNet.priority = NSOperationQueuePriorityHigh;
  1332. metadataNet.selector = selectorReadFileReloadFolder;
  1333. metadataNet.serverUrl = _serverUrl;
  1334. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1335. }
  1336. #pragma --------------------------------------------------------------------------------------------
  1337. #pragma mark ==== Read Folder ====
  1338. #pragma --------------------------------------------------------------------------------------------
  1339. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1340. {
  1341. // verify active user
  1342. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1343. _loadingFolder = NO;
  1344. [self tableViewReloadData];
  1345. [_refreshControl endRefreshing];
  1346. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1347. if (message && [record.account isEqualToString:metadataNet.account])
  1348. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1349. [self reloadDatasource:metadataNet.serverUrl];
  1350. if (errorCode == 401)
  1351. [self changePasswordAccount];
  1352. }
  1353. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1354. {
  1355. // verify active user
  1356. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1357. if (![record.account isEqualToString:metadataNet.account])
  1358. return;
  1359. // save father e update permission
  1360. if(!_isSearchMode && metadataFolder)
  1361. _fatherPermission = metadataFolder.permissions;
  1362. NSArray *recordsInSessions;
  1363. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1364. if (_isSearchMode) {
  1365. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1366. } else {
  1367. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1368. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1369. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1370. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1371. }
  1372. for (tableMetadata *metadata in metadatas) {
  1373. // type of file
  1374. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1375. // if crypto do not insert
  1376. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1377. // verify if the record encrypted has plist + crypto
  1378. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1379. BOOL isCryptoComplete = NO;
  1380. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1381. for (tableMetadata *completeMetadata in metadatas) {
  1382. if (completeMetadata.cryptated == NO) continue;
  1383. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1384. isCryptoComplete = YES;
  1385. break;
  1386. }
  1387. }
  1388. if (isCryptoComplete == NO) continue;
  1389. }
  1390. // verify if the record is in download/upload progress
  1391. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1392. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1393. // is in Download or Upload
  1394. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1395. continue;
  1396. }
  1397. }
  1398. // Insert in Array
  1399. [metadatasToInsertInDB addObject:metadata];
  1400. }
  1401. // insert in Database
  1402. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1403. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1404. // read plist
  1405. if (!_isSearchMode)
  1406. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1407. // File is changed ??
  1408. if (!_isSearchMode && metadatasToInsertInDB)
  1409. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1410. });
  1411. // Search Mode
  1412. if (_isSearchMode) {
  1413. // Fix managed -> Unmanaged _searchResultMetadatas
  1414. if (metadatasToInsertInDB)
  1415. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1416. [self reloadDatasource:metadataNet.serverUrl];
  1417. }
  1418. // this is the same directory
  1419. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1420. // reload
  1421. [self reloadDatasource:metadataNet.serverUrl];
  1422. // stoprefresh
  1423. [_refreshControl endRefreshing];
  1424. // Enable change user
  1425. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1426. _loadingFolder = NO;
  1427. [self tableViewReloadData];
  1428. }
  1429. }
  1430. - (void)readFolder:(NSString *)serverUrl
  1431. {
  1432. // init control
  1433. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1434. [_refreshControl endRefreshing];
  1435. return;
  1436. }
  1437. // Search Mode
  1438. if (_isSearchMode) {
  1439. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1440. _searchFileName = @""; // forced reload searchg
  1441. [self updateSearchResultsForSearchController:self.searchController];
  1442. return;
  1443. }
  1444. _loadingFolder = YES;
  1445. [self tableViewReloadData];
  1446. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1447. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1448. metadataNet.action = actionReadFolder;
  1449. metadataNet.date = [NSDate date];
  1450. metadataNet.depth = @"1";
  1451. metadataNet.directoryID = directory.directoryID;
  1452. metadataNet.priority = NSOperationQueuePriorityHigh;
  1453. metadataNet.selector = selectorReadFolder;
  1454. metadataNet.serverUrl = serverUrl;
  1455. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1456. }
  1457. #pragma mark -
  1458. #pragma --------------------------------------------------------------------------------------------
  1459. #pragma mark ===== Search =====
  1460. #pragma --------------------------------------------------------------------------------------------
  1461. -(void)searchStartTimer
  1462. {
  1463. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1464. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1465. _noFilesSearchTitle = @"";
  1466. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1467. [self.tableView reloadEmptyDataSet];
  1468. }
  1469. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1470. {
  1471. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  1472. _isSearchMode = YES;
  1473. [self deleteRefreshControl];
  1474. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1475. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1476. _searchFileName = fileName;
  1477. // First : filter
  1478. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1479. if (!directoryID) return;
  1480. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1481. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1482. [_searchResultMetadatas removeAllObjects];
  1483. for (tableMetadata *record in records)
  1484. [_searchResultMetadatas addObject:record];
  1485. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1486. metadataNet.account = app.activeAccount;
  1487. metadataNet.directoryID = directoryID;
  1488. metadataNet.selector = selectorSearch;
  1489. metadataNet.serverUrl = _serverUrl;
  1490. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1491. // Version >= 12
  1492. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1493. [_timerWaitInput invalidate];
  1494. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1495. }
  1496. }
  1497. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1498. [self reloadDatasource];
  1499. }
  1500. }
  1501. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1502. {
  1503. [self cancelSearchBar];
  1504. [self readFolder:_serverUrl];
  1505. }
  1506. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1507. {
  1508. _searchFileName = @"";
  1509. if (message)
  1510. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1511. }
  1512. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1513. {
  1514. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1515. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1516. }
  1517. - (void)cancelSearchBar
  1518. {
  1519. if (self.searchController.active) {
  1520. [self.searchController setActive:NO];
  1521. [self createRefreshControl];
  1522. _isSearchMode = NO;
  1523. _searchFileName = @"";
  1524. _dateReadDataSource = nil;
  1525. _searchResultMetadatas = [NSMutableArray new];
  1526. [self reloadDatasource];
  1527. }
  1528. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  1529. }
  1530. #pragma mark -
  1531. #pragma --------------------------------------------------------------------------------------------
  1532. #pragma mark ===== Delete File or Folder =====
  1533. #pragma --------------------------------------------------------------------------------------------
  1534. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1535. {
  1536. [self deleteFileOrFolderSuccess:metadataNet];
  1537. }
  1538. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1539. {
  1540. [_queueSelector removeObject:metadataNet.selector];
  1541. if ([_queueSelector count] == 0) {
  1542. [_hud hideHud];
  1543. // next
  1544. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1545. if ([_selectedFileIDsMetadatas count] > 0) {
  1546. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1547. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1548. } else {
  1549. // End Select Table View
  1550. [self tableViewSelect:NO];
  1551. // Reload
  1552. if (_isSearchMode)
  1553. [self readFolder:metadataNet.serverUrl];
  1554. else
  1555. [self reloadDatasource:metadataNet.serverUrl];
  1556. }
  1557. }
  1558. }
  1559. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1560. {
  1561. if (metadata.cryptated) {
  1562. [_queueSelector addObject:selectorDeleteCrypto];
  1563. [_queueSelector addObject:selectorDeletePlist];
  1564. } else {
  1565. [_queueSelector addObject:selectorDelete];
  1566. }
  1567. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1568. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1569. }
  1570. - (void)deleteFile
  1571. {
  1572. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1573. return;
  1574. [_queueSelector removeAllObjects];
  1575. if ([_selectedFileIDsMetadatas count] > 0) {
  1576. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1577. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1578. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1579. } else {
  1580. _numSelectedFileIDsMetadatas = 1;
  1581. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1582. }
  1583. }
  1584. #pragma --------------------------------------------------------------------------------------------
  1585. #pragma mark ===== Rename / Move =====
  1586. #pragma --------------------------------------------------------------------------------------------
  1587. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1588. {
  1589. [self readFolder:metadataNet.serverUrl];
  1590. }
  1591. - (void)renameFile:(NSArray *)arguments
  1592. {
  1593. tableMetadata* metadata = [arguments objectAtIndex:0];
  1594. NSString *fileName = [arguments objectAtIndex:1];
  1595. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1596. }
  1597. - (void)renameNote:(NSArray *)arguments
  1598. {
  1599. tableMetadata* metadata = [arguments objectAtIndex:0];
  1600. NSString *fileName = [arguments objectAtIndex:1];
  1601. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1602. if (!serverUrl) return;
  1603. CCTemplates *templates = [[CCTemplates alloc] init];
  1604. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1605. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1606. if (fileNameModel) {
  1607. [[CCNetworking sharedNetworking] uploadTemplate:fileName fileNameCrypto:[CCUtility trasformedFileNamePlistInCrypto:fileNameModel] serverUrl:serverUrl session:k_upload_session_foreground taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:self];
  1608. }
  1609. }
  1610. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1611. {
  1612. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1613. [_hud hideHud];
  1614. if (message)
  1615. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1616. // End Select Table View
  1617. [self tableViewSelect:NO];
  1618. // reload Datasource
  1619. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1620. [self readFolder:metadataNet.serverUrl];
  1621. else
  1622. [self reloadDatasource];
  1623. }
  1624. }
  1625. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1626. {
  1627. [_queueSelector removeObject:metadataNet.selector];
  1628. if ([_queueSelector count] == 0) {
  1629. [_hud hideHud];
  1630. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1631. NSString *directoryID = metadataNet.directoryID;
  1632. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1633. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1634. if (!serverUrlTo) return;
  1635. // FILE -> Metadata
  1636. if (metadataNet.directory == NO)
  1637. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1638. // DIRECTORY -> Directory - CCMetadata
  1639. if (metadataNet.directory == YES) {
  1640. // delete all dir / subdir
  1641. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1642. // move metadata
  1643. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1644. // Add new directory
  1645. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1646. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1647. }
  1648. // next
  1649. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1650. if ([_selectedFileIDsMetadatas count] > 0) {
  1651. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1652. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1653. } else {
  1654. // End Select Table View
  1655. [self tableViewSelect:NO];
  1656. // reload Datasource
  1657. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1658. [self readFolder:metadataNet.serverUrl];
  1659. else
  1660. [self reloadDatasource];
  1661. }
  1662. }
  1663. }
  1664. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1665. {
  1666. tableMetadata *metadata = [arguments objectAtIndex:0];
  1667. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1668. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1669. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1670. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1671. if (!serverUrl) return;
  1672. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1673. if (!directoryIDTo) return;
  1674. // Plain
  1675. if (metadata.cryptated == NO) {
  1676. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1677. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1678. if(!error) {
  1679. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1680. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1681. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1682. }];
  1683. [alert addAction:ok];
  1684. [self presentViewController:alert animated:YES completion:nil];
  1685. });
  1686. // End Select Table View
  1687. [self tableViewSelect:NO];
  1688. // reload Datasource
  1689. [self readFileReloadFolder];
  1690. return;
  1691. }
  1692. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1693. metadataNet.action = actionMoveFileOrFolder;
  1694. metadataNet.directory = metadata.directory;
  1695. metadataNet.fileID = metadata.fileID;
  1696. metadataNet.directoryID = metadata.directoryID;
  1697. metadataNet.directoryIDTo = directoryIDTo;
  1698. metadataNet.fileName = metadata.fileName;
  1699. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1700. metadataNet.fileNameTo = metadata.fileName;
  1701. metadataNet.etag = metadata.etag;
  1702. metadataNet.selector = selectorMove;
  1703. metadataNet.serverUrl = serverUrl;
  1704. metadataNet.serverUrlTo = serverUrlTo;
  1705. [_queueSelector addObject:metadataNet.selector];
  1706. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1707. }
  1708. // cyptated
  1709. if (metadata.cryptated == YES) {
  1710. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1711. metadataNet.action = actionMoveFileOrFolder;
  1712. metadataNet.directory = metadata.directory;
  1713. metadataNet.fileID = metadata.fileID;
  1714. metadataNet.directoryID = metadata.directoryID;
  1715. metadataNet.directoryIDTo = directoryIDTo;
  1716. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1717. metadataNet.etag = metadata.etag;
  1718. metadataNet.serverUrl = serverUrl;
  1719. metadataNet.serverUrlTo = serverUrlTo;
  1720. // data
  1721. metadataNet.fileName = metadata.fileNameData;
  1722. metadataNet.fileNameTo = metadata.fileNameData;
  1723. metadataNet.selector = selectorMoveCrypto;
  1724. [_queueSelector addObject:metadataNet.selector];
  1725. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1726. // plist
  1727. metadataNet.fileName = metadata.fileName;
  1728. metadataNet.fileNameTo = metadata.fileName;
  1729. metadataNet.selector = selectorMovePlist;
  1730. [_queueSelector addObject:metadataNet.selector];
  1731. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1732. }
  1733. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1734. }
  1735. // DELEGATE : Move
  1736. - (void)dismissMove
  1737. {
  1738. [self reloadDatasource];
  1739. }
  1740. // DELEGATE : Move
  1741. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1742. {
  1743. [_queueSelector removeAllObjects];
  1744. if ([_selectedFileIDsMetadatas count] > 0) {
  1745. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1746. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1747. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1748. } else {
  1749. _numSelectedFileIDsMetadatas = 1;
  1750. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1751. }
  1752. }
  1753. - (void)moveOpenWindow:(NSArray *)indexPaths
  1754. {
  1755. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1756. return;
  1757. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1758. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1759. viewController.delegate = self;
  1760. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1761. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1762. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1763. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1764. viewController.networkingOperationQueue = app.netQueue;
  1765. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1766. [self presentViewController:navigationController animated:YES completion:nil];
  1767. }
  1768. #pragma --------------------------------------------------------------------------------------------
  1769. #pragma mark ===== Create folder =====
  1770. #pragma --------------------------------------------------------------------------------------------
  1771. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1772. {
  1773. if (metadataNet.cryptated == NO) {
  1774. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1775. [self reloadDatasource];
  1776. // We are in directory fail ?
  1777. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1778. if (vc)
  1779. [vc.navigationController popViewControllerAnimated:YES];
  1780. }
  1781. if (message)
  1782. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1783. }
  1784. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1785. {
  1786. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1787. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1788. if (metadataNet.cryptated == NO) {
  1789. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1790. if (metadata) {
  1791. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1792. metadata.fileID = metadataNet.fileID;
  1793. metadata.date = metadataNet.date;
  1794. metadata.permissions = @"RDNVCK";
  1795. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1796. [self reloadDatasource];
  1797. } else {
  1798. [self readFileReloadFolder];
  1799. }
  1800. }
  1801. }
  1802. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1803. {
  1804. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1805. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1806. if (![fileNameFolder length]) return;
  1807. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1808. else metadataNet.serverUrl = _serverUrl;
  1809. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1810. if (!directoryID) return;
  1811. metadataNet.action = actionCreateFolder;
  1812. metadataNet.directoryID = directoryID;
  1813. if (autoUploadDirectory)
  1814. metadataNet.options = @"folderAutoUpload";
  1815. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1816. metadataNet.fileName = fileNameFolder;
  1817. metadataNet.selector = selectorCreateFolder;
  1818. metadataNet.serverUrl = _serverUrl;
  1819. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1820. // Create Directory on metadata
  1821. 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];
  1822. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1823. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1824. [self reloadDatasource];
  1825. }
  1826. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1827. {
  1828. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1829. NSString *fileNamePlist;
  1830. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1831. if (![fileNameFolder length]) return;
  1832. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1833. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1834. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1835. // Create folder
  1836. metadataNet.action = actionCreateFolder;
  1837. metadataNet.cryptated = YES;
  1838. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1839. metadataNet.fileName = fileNamePlist;
  1840. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1841. metadataNet.selector = selectorCreateFolder;
  1842. metadataNet.serverUrl = _serverUrl;
  1843. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1844. [[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];
  1845. }
  1846. #pragma --------------------------------------------------------------------------------------------
  1847. #pragma mark ===== Encrypted / Decrypted Folder =====
  1848. #pragma --------------------------------------------------------------------------------------------
  1849. - (void)encyptedDecryptedFolder
  1850. {
  1851. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1852. if (!serverUrl) return;
  1853. if (_metadata.cryptated) {
  1854. // DECRYPTED
  1855. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1856. //-------------------------- RENAME -------------------------------------------//
  1857. metadataNet.action = actionMoveFileOrFolder;
  1858. metadataNet.fileID = _metadata.fileID;
  1859. metadataNet.fileName = _metadata.fileNameData;
  1860. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1861. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1862. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1863. metadataNet.selector = selectorRename;
  1864. metadataNet.serverUrl = serverUrl;
  1865. metadataNet.serverUrlTo = serverUrl;
  1866. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1867. //-------------------------- DELETE -------------------------------------------//
  1868. metadataNet.action = actionDeleteFileDirectory;
  1869. metadataNet.fileID = _metadata.fileID;
  1870. metadataNet.fileName = _metadata.fileName;
  1871. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1872. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1873. metadataNet.selector = selectorDeletePlist;
  1874. metadataNet.selectorPost = selectorReadFolderForced;
  1875. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1876. } else {
  1877. // ENCRYPTED
  1878. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1879. // Create File Plist
  1880. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1881. //-------------------------- RENAME -------------------------------------------//
  1882. metadataNet.action = actionMoveFileOrFolder;
  1883. metadataNet.fileID = _metadata.fileID;
  1884. metadataNet.fileName = _metadata.fileName;
  1885. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1886. metadataNet.fileNameTo = fileNameCrypto;
  1887. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1888. metadataNet.selector = selectorRename;
  1889. metadataNet.serverUrl = serverUrl;
  1890. metadataNet.serverUrlTo = serverUrl;
  1891. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1892. //-------------------------- UPLOAD -------------------------------------------//
  1893. [[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];
  1894. }
  1895. }
  1896. #pragma --------------------------------------------------------------------------------------------
  1897. #pragma mark ===== Encrypted/Decrypted File =====
  1898. #pragma --------------------------------------------------------------------------------------------
  1899. - (void)encryptedSelectedFiles
  1900. {
  1901. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1902. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1903. for (tableMetadata *metadata in selectedMetadatas) {
  1904. if (metadata.cryptated == NO && metadata.directory == NO)
  1905. [metadatas addObject:metadata];
  1906. }
  1907. if ([metadatas count] > 0) {
  1908. NSLog(@"[LOG] Start encrypted selected files ...");
  1909. for (tableMetadata* metadata in metadatas) {
  1910. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1911. if(serverUrl)
  1912. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1913. }
  1914. }
  1915. [self tableViewSelect:NO];
  1916. }
  1917. - (void)decryptedSelectedFiles
  1918. {
  1919. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1920. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1921. for (tableMetadata *metadata in selectedMetadatas) {
  1922. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1923. [metadatas addObject:metadata];
  1924. }
  1925. if ([metadatas count] > 0) {
  1926. NSLog(@"[LOG] Start decrypted selected files ...");
  1927. for (tableMetadata* metadata in metadatas) {
  1928. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1929. if (serverUrl)
  1930. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1931. }
  1932. }
  1933. [self tableViewSelect:NO];
  1934. }
  1935. - (void)cmdEncryptedDecryptedFile
  1936. {
  1937. NSString *selector;
  1938. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1939. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1940. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1941. if (serverUrl)
  1942. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1943. }
  1944. - (void)encryptedFile:(tableMetadata *)metadata
  1945. {
  1946. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1947. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1948. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1949. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1950. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo] && serverUrl) {
  1951. dispatch_async(dispatch_get_main_queue(), ^{
  1952. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  1953. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1954. });
  1955. } else {
  1956. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1957. }
  1958. }
  1959. - (void)decryptedFile:(tableMetadata *)metadata
  1960. {
  1961. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1962. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1963. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1964. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1965. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo] && serverUrl) {
  1966. dispatch_async(dispatch_get_main_queue(), ^{
  1967. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  1968. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1969. });
  1970. } else {
  1971. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1972. }
  1973. }
  1974. #pragma --------------------------------------------------------------------------------------------
  1975. #pragma mark ===== Progress & Task Button =====
  1976. #pragma --------------------------------------------------------------------------------------------
  1977. - (void)triggerProgressTask:(NSNotification *)notification
  1978. {
  1979. NSDictionary *dict = notification.userInfo;
  1980. NSString *fileID = [dict valueForKey:@"fileID"];
  1981. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1982. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1983. float progress = [[dict valueForKey:@"progress"] floatValue];
  1984. // CCProgress
  1985. if (progress == 0)
  1986. [self.navigationController cancelCCProgress];
  1987. else
  1988. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1989. // Check
  1990. if (!fileID || [fileID isEqualToString: @""])
  1991. return;
  1992. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1993. if (![serverUrl isEqualToString:_serverUrl])
  1994. return;
  1995. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1996. if ([self indexPathIsValid:indexPath]) {
  1997. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1998. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1999. else cell.progressView.progressTintColor = [UIColor blackColor];
  2000. cell.progressView.hidden = NO;
  2001. [cell.progressView setProgress:progress];
  2002. }
  2003. }
  2004. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  2005. {
  2006. UITouch * touch = [[event allTouches] anyObject];
  2007. CGPoint location = [touch locationInView:self.tableView];
  2008. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2009. if ([self indexPathIsValid:indexPath]) {
  2010. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2011. if (metadata)
  2012. [self reloadTaskButton:metadata];
  2013. }
  2014. }
  2015. - (void)reloadTaskButton:(tableMetadata *)metadata
  2016. {
  2017. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2018. __block NSURLSessionTask *findTask;
  2019. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2020. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2021. NSString *fileID = metadata.fileID;
  2022. // DOWNLOAD
  2023. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2024. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2025. for (NSURLSessionUploadTask *task in downloadTasks)
  2026. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2027. findTask = task;
  2028. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2029. [task cancel];
  2030. }
  2031. if (!findTask) {
  2032. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2033. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2034. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2035. }
  2036. }];
  2037. }
  2038. // UPLOAD
  2039. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2040. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2041. for (NSURLSessionUploadTask *task in uploadTasks)
  2042. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2043. findTask = task;
  2044. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2045. [task cancel];
  2046. }
  2047. if (!findTask) {
  2048. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2049. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2050. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2051. }
  2052. }];
  2053. }
  2054. }
  2055. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2056. {
  2057. UITouch * touch = [[event allTouches] anyObject];
  2058. CGPoint location = [touch locationInView:self.tableView];
  2059. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2060. if ([self indexPathIsValid:indexPath]) {
  2061. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2062. if (metadata)
  2063. [self cancelTaskButton:metadata reloadTable:YES];
  2064. }
  2065. }
  2066. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2067. {
  2068. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2069. __block NSURLSessionTask *findTask;
  2070. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2071. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2072. NSString *fileID = metadata.fileID;
  2073. // DOWNLOAD
  2074. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2075. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2076. for (NSURLSessionTask *task in downloadTasks)
  2077. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2078. findTask = task;
  2079. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2080. [task cancel];
  2081. }
  2082. if (!findTask) {
  2083. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2084. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2085. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2086. }
  2087. }];
  2088. }
  2089. // UPLOAD
  2090. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2091. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2092. for (NSURLSessionUploadTask *task in uploadTasks)
  2093. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2094. findTask = task;
  2095. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2096. [task cancel];
  2097. }
  2098. if (!findTask) {
  2099. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2100. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2101. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2102. }
  2103. }];
  2104. }
  2105. }
  2106. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2107. {
  2108. UITouch * touch = [[event allTouches] anyObject];
  2109. CGPoint location = [touch locationInView:self.tableView];
  2110. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2111. if ([self indexPathIsValid:indexPath]) {
  2112. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2113. if (metadata)
  2114. [self stopTaskButton:metadata];
  2115. }
  2116. }
  2117. - (void)stopTaskButton:(tableMetadata *)metadata
  2118. {
  2119. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2120. __block NSURLSessionTask *findTask;
  2121. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2122. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2123. NSString *fileID = metadata.fileID;
  2124. // UPLOAD
  2125. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2126. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2127. for (NSURLSessionUploadTask *task in uploadTasks)
  2128. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2129. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2130. findTask = task;
  2131. [task cancel];
  2132. }
  2133. if (!findTask) {
  2134. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2135. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2136. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2137. }
  2138. }];
  2139. }
  2140. }
  2141. #pragma --------------------------------------------------------------------------------------------
  2142. #pragma mark ===== Shared =====
  2143. #pragma --------------------------------------------------------------------------------------------
  2144. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2145. {
  2146. [_hud hideHud];
  2147. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2148. // change account ?
  2149. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2150. if([record.account isEqualToString:metadataNet.account] == NO)
  2151. return;
  2152. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2153. if (result) {
  2154. appDelegate.sharesLink = result[0];
  2155. appDelegate.sharesUserAndGroup = result[1];
  2156. }
  2157. // Notify Shares View
  2158. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2159. if (openWindow) {
  2160. if (_shareOC) {
  2161. [_shareOC reloadData];
  2162. } else {
  2163. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2164. // Apriamo la view
  2165. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2166. _shareOC.delegate = self;
  2167. _shareOC.metadata = metadata;
  2168. _shareOC.serverUrl = metadataNet.serverUrl;
  2169. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2170. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2171. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2172. [self presentViewController:_shareOC animated:YES completion:nil];
  2173. }
  2174. }
  2175. [self tableViewReloadData];
  2176. }
  2177. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2178. {
  2179. [_hud hideHud];
  2180. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2181. if (_shareOC)
  2182. [_shareOC reloadData];
  2183. [self tableViewReloadData];
  2184. if (errorCode == 401)
  2185. [self changePasswordAccount];
  2186. }
  2187. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2188. {
  2189. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2190. metadataNet.action = actionShare;
  2191. metadataNet.fileID = metadata.fileID;
  2192. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2193. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2194. metadataNet.password = password;
  2195. metadataNet.selector = selectorShare;
  2196. metadataNet.serverUrl = serverUrl;
  2197. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2198. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2199. }
  2200. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2201. {
  2202. [_hud hideHud];
  2203. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2204. // rimuoviamo la condivisione da db
  2205. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2206. if (result) {
  2207. appDelegate.sharesLink = result[0];
  2208. appDelegate.sharesUserAndGroup = result[1];
  2209. }
  2210. if (_shareOC)
  2211. [_shareOC reloadData];
  2212. [self tableViewReloadData];
  2213. }
  2214. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2215. {
  2216. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2217. metadataNet.action = actionUnShare;
  2218. metadataNet.fileID = metadata.fileID;
  2219. metadataNet.fileName = metadata.fileName;
  2220. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2221. metadataNet.selector = selectorUnshare;
  2222. metadataNet.serverUrl = serverUrl;
  2223. metadataNet.share = share;
  2224. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2225. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2226. }
  2227. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2228. {
  2229. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2230. metadataNet.action = actionUpdateShare;
  2231. metadataNet.fileID = metadata.fileID;
  2232. metadataNet.expirationTime = expirationTime;
  2233. metadataNet.password = password;
  2234. metadataNet.selector = selectorUpdateShare;
  2235. metadataNet.serverUrl = serverUrl;
  2236. metadataNet.share = share;
  2237. metadataNet.sharePermission = permission;
  2238. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2239. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2240. }
  2241. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2242. {
  2243. [_hud hideHud];
  2244. if (_shareOC)
  2245. [_shareOC reloadUserAndGroup:items];
  2246. }
  2247. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2248. {
  2249. [_hud hideHud];
  2250. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2251. }
  2252. - (void)getUserAndGroup:(NSString *)find
  2253. {
  2254. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2255. metadataNet.action = actionGetUserAndGroup;
  2256. metadataNet.options = find;
  2257. metadataNet.selector = selectorGetUserAndGroup;
  2258. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2259. [_hud visibleIndeterminateHud];
  2260. }
  2261. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2262. {
  2263. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2264. metadataNet.action = actionShareWith;
  2265. metadataNet.fileID = metadata.fileID;
  2266. metadataNet.directoryID = directoryID;
  2267. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2268. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2269. metadataNet.serverUrl = serverUrl;
  2270. metadataNet.selector = selectorShare;
  2271. metadataNet.share = user;
  2272. metadataNet.shareeType = shareeType;
  2273. metadataNet.sharePermission = permission;
  2274. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2275. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2276. }
  2277. - (void)openWindowShare:(tableMetadata *)metadata
  2278. {
  2279. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2280. if (!serverUrl) return;
  2281. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2282. metadataNet.action = actionReadShareServer;
  2283. metadataNet.fileID = metadata.fileID;
  2284. metadataNet.fileName = metadata.fileName;
  2285. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2286. metadataNet.selector = selectorOpenWindowShare;
  2287. metadataNet.serverUrl = serverUrl;
  2288. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2289. [_hud visibleIndeterminateHud];
  2290. }
  2291. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2292. {
  2293. CGPoint location = [tapGesture locationInView:self.tableView];
  2294. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2295. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2296. if (metadata)
  2297. [self openWindowShare:metadata];
  2298. }
  2299. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2300. {
  2301. CGPoint location = [tapGesture locationInView:self.tableView];
  2302. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2303. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2304. if (metadata) {
  2305. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2306. vc.metadata = metadata;
  2307. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2308. [self presentViewController:vc animated:YES completion:nil];
  2309. }
  2310. }
  2311. #pragma --------------------------------------------------------------------------------------------
  2312. #pragma mark ===== Favorite =====
  2313. #pragma --------------------------------------------------------------------------------------------
  2314. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2315. {
  2316. _dateReadDataSource = nil;
  2317. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2318. if (_isSearchMode)
  2319. [self readFolder:metadataNet.serverUrl];
  2320. else
  2321. [self reloadDatasource:metadataNet.serverUrl];
  2322. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2323. if (metadata.directory && metadata.favorite) {
  2324. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2325. [app.activeFavorites addFavoriteFolder:dir];
  2326. }
  2327. }
  2328. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2329. {
  2330. }
  2331. - (void)addFavorite:(tableMetadata *)metadata
  2332. {
  2333. if (metadata.directory) {
  2334. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2335. } else {
  2336. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2337. if (serverUrl)
  2338. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2339. }
  2340. }
  2341. - (void)removeFavorite:(tableMetadata *)metadata
  2342. {
  2343. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2344. }
  2345. #pragma --------------------------------------------------------------------------------------------
  2346. #pragma mark ===== Open in... =====
  2347. #pragma --------------------------------------------------------------------------------------------
  2348. - (void)openIn:(tableMetadata *)metadata
  2349. {
  2350. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2351. if (!serverUrl) return;
  2352. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2353. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2354. if ([self indexPathIsValid:indexPath])
  2355. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2356. }
  2357. #pragma --------------------------------------------------------------------------------------------
  2358. #pragma mark ===== Remove Local File =====
  2359. #pragma --------------------------------------------------------------------------------------------
  2360. - (void)removeLocalFile:(tableMetadata *)metadata
  2361. {
  2362. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2363. if (!serverUrl) return;
  2364. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2365. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2366. [self reloadDatasource:serverUrl];
  2367. }
  2368. #pragma --------------------------------------------------------------------------------------------
  2369. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2370. #pragma --------------------------------------------------------------------------------------------
  2371. - (void)orderTable:(NSString *)order
  2372. {
  2373. [CCUtility setOrderSettings:order];
  2374. // Clear data-read of DataSource
  2375. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2376. }
  2377. - (void)ascendingTable:(BOOL)ascending
  2378. {
  2379. [CCUtility setAscendingSettings:ascending];
  2380. // Clear data-read of DataSource
  2381. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2382. }
  2383. - (void)directoryOnTop:(BOOL)directoryOnTop
  2384. {
  2385. [CCUtility setDirectoryOnTop:directoryOnTop];
  2386. // Clear data-read of DataSource
  2387. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2388. }
  2389. - (void)tableGroupBy:(NSString *)groupBy
  2390. {
  2391. [CCUtility setGroupBySettings:groupBy];
  2392. // Clear data-read of DataSource
  2393. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2394. }
  2395. #pragma --------------------------------------------------------------------------------------------
  2396. #pragma mark ==== Menu LOGO ====
  2397. #pragma --------------------------------------------------------------------------------------------
  2398. - (void)menuLogo
  2399. {
  2400. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2401. return;
  2402. // Brand
  2403. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2404. return;
  2405. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2406. NSUInteger numInQueue = [app.netQueue operationCount];
  2407. if (numInSession+numInQueue > 0) {
  2408. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2409. return;
  2410. }
  2411. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2412. NSMutableArray *menuArray = [NSMutableArray new];
  2413. for (NSString *account in listAccount) {
  2414. if ([account isEqualToString:app.activeAccount]) continue;
  2415. CCMenuItem *item = [[CCMenuItem alloc] init];
  2416. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2417. item.argument = account;
  2418. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2419. item.target = self;
  2420. item.action = @selector(changeDefaultAccount:);
  2421. [menuArray addObject:item];
  2422. }
  2423. if ([menuArray count] == 0)
  2424. return;
  2425. OptionalConfiguration options;
  2426. Color textColor, backgroundColor;
  2427. textColor.R = 0;
  2428. textColor.G = 0;
  2429. textColor.B = 0;
  2430. backgroundColor.R = 1;
  2431. backgroundColor.G = 1;
  2432. backgroundColor.B = 1;
  2433. NSInteger originY = 60;
  2434. options.arrowSize = 9;
  2435. options.marginXSpacing = 7;
  2436. options.marginYSpacing = 10;
  2437. options.intervalSpacing = 20;
  2438. options.menuCornerRadius = 6.5;
  2439. options.maskToBackground = NO;
  2440. options.shadowOfMenu = YES;
  2441. options.hasSeperatorLine = YES;
  2442. options.seperatorLineHasInsets = YES;
  2443. options.textColor = textColor;
  2444. options.menuBackgroundColor = backgroundColor;
  2445. CGRect rect = self.view.frame;
  2446. rect.origin.y = rect.origin.y + originY;
  2447. rect.size.height = rect.size.height - originY;
  2448. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2449. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2450. }
  2451. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2452. {
  2453. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  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