CCMain.m 251 KB

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