CCMain.m 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  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 "OCActivity.h"
  28. #import "OCNotifications.h"
  29. #import "OCNotificationsAction.h"
  30. #import "OCFrameworkConstants.h"
  31. #import "OCCapabilities.h"
  32. #import "CTAssetCheckmark.h"
  33. #import "JDStatusBarNotification.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. #import "NCNetworkingEndToEnd.h"
  37. #import "PKDownloadButton.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. AppDelegate *appDelegate;
  41. tableMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. UIImageView *_ImageTitleHomeCryptoCloud;
  48. NSString *_directoryGroupBy;
  49. NSString *_directoryOrder;
  50. NSUInteger _failedAttempts;
  51. NSDate *_lockUntilDate;
  52. NSString *_fatherPermission;
  53. UIRefreshControl *_refreshControl;
  54. UIDocumentInteractionController *_docController;
  55. CCHud *_hud;
  56. // Datasource
  57. CCSectionDataSourceMetadata *_sectionDataSource;
  58. NSDate *_dateReadDataSource;
  59. // Search
  60. BOOL _isSearchMode;
  61. NSString *_searchFileName;
  62. NSMutableArray *_searchResultMetadatas;
  63. NSString *_noFilesSearchTitle;
  64. NSString *_noFilesSearchDescription;
  65. NSTimer *_timerWaitInput;
  66. // Automatic Upload Folder
  67. NSString *_autoUploadFileName;
  68. NSString *_autoUploadDirectory;
  69. // Folder
  70. BOOL _loadingFolder;
  71. tableMetadata *_metadataFolder;
  72. // Image Title Segue
  73. UIImage *imageTitleSegue;
  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. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. // Active Main
  92. appDelegate.activeMain = self;
  93. }
  94. return self;
  95. }
  96. #pragma --------------------------------------------------------------------------------------------
  97. #pragma mark ===== View =====
  98. #pragma --------------------------------------------------------------------------------------------
  99. - (void)viewDidLoad
  100. {
  101. [super viewDidLoad];
  102. // init object
  103. _metadata = [tableMetadata new];
  104. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  105. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  106. _queueSelector = [NSMutableArray new];
  107. _isViewDidLoad = YES;
  108. _fatherPermission = @"";
  109. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  110. _searchResultMetadatas = [NSMutableArray new];
  111. _searchFileName = @"";
  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. // Actie Delegate Networking
  123. [CCNetworking sharedNetworking].delegate = self;
  124. // Register cell
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  126. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  127. // long press recognizer TableView
  128. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  129. [self.tableView addGestureRecognizer:longPressRecognizer];
  130. // Pull-to-Refresh
  131. [self createRefreshControl];
  132. // Register for 3D Touch Previewing if available
  133. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  134. {
  135. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  136. }
  137. // Back Button
  138. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  139. UIImage *backButtonImage = [UIImage imageNamed:@"navigationLogo"];
  140. backButtonImage = [backButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  141. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backButtonImage style:UIBarButtonItemStylePlain target:nil action:nil];
  142. }
  143. // reMenu Background
  144. _reMenuBackgroundView = [UIView new];
  145. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  146. // if this is not Main (the Main uses inizializeMain)
  147. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  148. // Read (File) Folder
  149. [self readFileReloadFolder];
  150. }
  151. // Title
  152. [self setTitle];
  153. }
  154. // Apparirà
  155. - (void)viewWillAppear:(BOOL)animated
  156. {
  157. [super viewWillAppear:animated];
  158. // test
  159. if (appDelegate.activeAccount.length == 0)
  160. return;
  161. // delegate for Networking
  162. [CCNetworking sharedNetworking].delegate = self;
  163. // Color
  164. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  165. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  166. if (_isSelectedMode)
  167. [self setUINavigationBarSelected];
  168. else
  169. [self setUINavigationBarDefault];
  170. // If not editing mode remove _selectedFileIDs
  171. if (!self.tableView.editing)
  172. [_selectedFileIDsMetadatas removeAllObjects];
  173. // Plus Button
  174. [appDelegate plusButtonVisibile:true];
  175. // Search Bar
  176. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  177. [self searchEnabled:NO];
  178. } else {
  179. [self searchEnabled:YES];
  180. }
  181. }
  182. // E' arrivato
  183. - (void)viewDidAppear:(BOOL)animated
  184. {
  185. [super viewDidAppear:animated];
  186. // Active Main
  187. appDelegate.activeMain = self;
  188. // Test viewDidLoad
  189. if (_isViewDidLoad) {
  190. _isViewDidLoad = NO;
  191. } else {
  192. if (appDelegate.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  193. // Read (file) Folder
  194. [self readFileReloadFolder];
  195. }
  196. }
  197. // Title
  198. [self setTitle];
  199. }
  200. - (void)viewWillDisappear:(BOOL)animated
  201. {
  202. [super viewWillDisappear:animated];
  203. [self closeAllMenu];
  204. }
  205. - (void)didReceiveMemoryWarning
  206. {
  207. [super didReceiveMemoryWarning];
  208. // Dispose of any resources that can be recreated.
  209. }
  210. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  211. {
  212. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  213. [self closeAllMenu];
  214. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  215. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  216. // Portrait
  217. } else {
  218. // Landscape
  219. }
  220. [self.tableView reloadData];
  221. }];
  222. }
  223. - (BOOL)prefersStatusBarHidden
  224. {
  225. return NO;
  226. }
  227. // detect scroll for remove keyboard in search mode
  228. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  229. {
  230. if (_isSearchMode && scrollView == self.tableView) {
  231. [self.searchController.searchBar endEditing:YES];
  232. }
  233. }
  234. - (void)changeTheming
  235. {
  236. if (self.isViewLoaded && self.view.window)
  237. [appDelegate changeTheming:self];
  238. // Refresh control
  239. _refreshControl.tintColor = [NCBrandColor sharedInstance].brandText;
  240. _refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  241. // color searchbar
  242. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  243. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  244. // color searchbbar button text (cancel)
  245. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  246. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  247. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  248. }
  249. // Title
  250. [self setTitle];
  251. // Reload Table View
  252. [self tableViewReloadData];
  253. }
  254. #pragma --------------------------------------------------------------------------------------------
  255. #pragma mark ===== Initizlize Mail =====
  256. #pragma --------------------------------------------------------------------------------------------
  257. //
  258. // Callers :
  259. //
  260. // loginSuccess (delagate)
  261. // ChangeDefaultAccount (delegate)
  262. // Split : inizialize
  263. // Settings Advanced : removeAllFiles
  264. //
  265. - (void)initializeMain:(NSNotification *)notification
  266. {
  267. _directoryGroupBy = nil;
  268. _directoryOrder = nil;
  269. _dateReadDataSource = nil;
  270. // test
  271. if (appDelegate.activeAccount.length == 0)
  272. return;
  273. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  274. // This is Root home main add list
  275. appDelegate.homeMain = self;
  276. _isRoot = YES;
  277. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  278. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  279. // go Home
  280. [self.navigationController popToRootViewControllerAnimated:NO];
  281. // setting Networking
  282. [CCNetworking sharedNetworking].delegate = self;
  283. [[CCNetworking sharedNetworking] settingAccount];
  284. // Remove search mode
  285. [self cancelSearchBar];
  286. // populate shared Link & User
  287. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  288. if (results) {
  289. appDelegate.sharesLink = results[0];
  290. appDelegate.sharesUserAndGroup = results[1];
  291. }
  292. // Setting Theming
  293. [appDelegate settingThemingColorBrand];
  294. // remove all of detail
  295. [appDelegate.activeDetail removeAllView];
  296. // remove all Notification Messages
  297. [appDelegate.listOfNotifications removeAllObjects];
  298. // Not Photos Video in library ? then align and Init Auto Upload
  299. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  300. if ([recordsPhotoLibrary count] == 0) {
  301. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  302. }
  303. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  304. NSLog(@"[LOG] Request Service Server Nextcloud");
  305. [[NCService sharedInstance] startRequestServicesServer];
  306. // Clear datasorce
  307. [appDelegate.activePhotos reloadDatasourceFromSearch:NO];
  308. [appDelegate.activeFavorites reloadDatasource];
  309. // Read this folder
  310. [self readFileReloadFolder];
  311. } else {
  312. // reload datasource
  313. [self reloadDatasource:_serverUrl];
  314. }
  315. }
  316. #pragma --------------------------------------------------------------------------------------------
  317. #pragma mark ==== DZNEmptyDataSetSource ====
  318. #pragma --------------------------------------------------------------------------------------------
  319. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  320. {
  321. if (_loadingFolder)
  322. return NO;
  323. else
  324. return YES;
  325. }
  326. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. return [NCBrandColor sharedInstance].backgroundView;
  329. }
  330. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. if (_isSearchMode)
  333. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  334. else
  335. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  336. }
  337. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  338. {
  339. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  340. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  341. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  342. activityView.color = [NCBrandColor sharedInstance].brandElement;
  343. [activityView startAnimating];
  344. return activityView;
  345. }
  346. return nil;
  347. }
  348. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  349. {
  350. NSString *text;
  351. if (_isSearchMode) {
  352. text = _noFilesSearchTitle;
  353. } else {
  354. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  355. }
  356. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  357. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  358. }
  359. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  360. {
  361. NSString *text;
  362. if (_isSearchMode) {
  363. text = _noFilesSearchDescription;
  364. } else {
  365. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  366. }
  367. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  368. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  369. paragraph.alignment = NSTextAlignmentCenter;
  370. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  371. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  372. }
  373. #pragma --------------------------------------------------------------------------------------------
  374. #pragma mark ===== Text Field =====
  375. #pragma --------------------------------------------------------------------------------------------
  376. - (void)minCharTextFieldDidChange:(UITextField *)sender
  377. {
  378. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  379. if (alertController)
  380. {
  381. UITextField *fileName = alertController.textFields.firstObject;
  382. UIAlertAction *okAction = alertController.actions.lastObject;
  383. okAction.enabled = fileName.text.length > 0;
  384. }
  385. }
  386. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  387. [textField selectAll:textField];
  388. }
  389. #pragma --------------------------------------------------------------------------------------------
  390. #pragma mark ===== Graphic Window =====
  391. #pragma --------------------------------------------------------------------------------------------
  392. - (void)createRefreshControl
  393. {
  394. _refreshControl = [UIRefreshControl new];
  395. if (@available(iOS 10, *)) {
  396. _tableView.refreshControl = _refreshControl;
  397. } else {
  398. [_tableView addSubview:_refreshControl];
  399. }
  400. _refreshControl.tintColor = [NCBrandColor sharedInstance].brandText;
  401. _refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  402. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  403. }
  404. - (void)deleteRefreshControl
  405. {
  406. [_refreshControl endRefreshing];
  407. for (UIView *subview in [_tableView subviews]) {
  408. if (subview == _refreshControl)
  409. [subview removeFromSuperview];
  410. }
  411. _tableView.refreshControl = nil;
  412. _refreshControl = nil;
  413. }
  414. - (void)refreshControlTarget
  415. {
  416. [self readFolder:_serverUrl];
  417. // Actuate `Peek` feedback (weak boom)
  418. AudioServicesPlaySystemSound(1519);
  419. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  420. }
  421. - (void)setTitle
  422. {
  423. // Color text self.navigationItem.title
  424. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  425. if (_isSelectedMode) {
  426. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  427. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  428. self.navigationItem.titleView = nil;
  429. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  430. } else {
  431. // we are in home : LOGO BRAND
  432. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  433. self.navigationItem.title = nil;
  434. if ([appDelegate.reachability isReachable] == NO) {
  435. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  436. } else {
  437. if ([NCBrandOptions sharedInstance].use_themingColor) {
  438. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  439. if ([capabilities.themingColor isEqualToString:@"#FFFFFF"])
  440. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"navigationLogo"] multiplier:2 color:[UIColor blackColor]]];
  441. else
  442. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"navigationLogo"] multiplier:2 color:[UIColor whiteColor]]];
  443. } else {
  444. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  445. }
  446. }
  447. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  448. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  449. [singleTap setNumberOfTapsRequired:1];
  450. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  451. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  452. } else {
  453. NSString *shareLink, *shareUserAndGroup;
  454. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataFolder.directoryID];
  455. if (serverUrl) {
  456. shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:_metadataFolder.fileName]];
  457. shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:_metadataFolder.fileName]];
  458. }
  459. if (self.imageTitle) {
  460. [CCGraphics addImageToTitle:_titleMain colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:self.imageTitle multiplier:2 color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  461. } else {
  462. self.navigationItem.titleView = nil;
  463. self.navigationItem.title = _titleMain;
  464. }
  465. }
  466. }
  467. }
  468. - (void)setUINavigationBarDefault
  469. {
  470. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  471. UIBarButtonItem *buttonMore, *buttonNotification;
  472. // =
  473. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  474. buttonMore.enabled = true;
  475. // <
  476. self.navigationController.navigationBar.hidden = NO;
  477. // Notification
  478. if ([appDelegate.listOfNotifications count] > 0) {
  479. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  480. buttonNotification.tintColor = [NCBrandColor sharedInstance].brandText;
  481. buttonNotification.enabled = true;
  482. }
  483. if (buttonNotification)
  484. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  485. else
  486. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  487. self.navigationItem.leftBarButtonItem = nil;
  488. }
  489. - (void)setUINavigationBarSelected
  490. {
  491. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  492. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  493. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  494. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  495. self.navigationItem.leftBarButtonItem = leftButton;
  496. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  497. }
  498. - (void)cancelSelect
  499. {
  500. [self tableViewSelect:NO];
  501. [appDelegate.reSelectMenu close];
  502. }
  503. - (void)closeAllMenu
  504. {
  505. // close Menu
  506. [appDelegate.reSelectMenu close];
  507. [appDelegate.reMainMenu close];
  508. // Close Menu Logo
  509. [CCMenuAccount dismissMenu];
  510. }
  511. #pragma --------------------------------------------------------------------------------------------
  512. #pragma mark ===== Document Picker =====
  513. #pragma --------------------------------------------------------------------------------------------
  514. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  515. {
  516. NSLog(@"[LOG] Cancelled");
  517. }
  518. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  519. {
  520. NSLog(@"[LOG] Cancelled");
  521. }
  522. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  523. {
  524. documentPicker.delegate = self;
  525. [self presentViewController:documentPicker animated:YES completion:nil];
  526. }
  527. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  528. {
  529. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  530. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  531. __block NSError *error;
  532. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  533. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  534. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  535. NSString *fileName = [[NCUtility sharedInstance] createFileName:[url lastPathComponent] directoryID:directoryID];
  536. NSString *fileID = [directoryID stringByAppendingString:fileName];
  537. NSData *data = [NSData dataWithContentsOfURL:newURL];
  538. if (data && error == nil) {
  539. if ([data writeToFile:[CCUtility getDirectoryProviderStorageFileID:fileID fileName:fileName] options:NSDataWritingAtomic error:&error]) {
  540. tableMetadata *metadataForUpload = [tableMetadata new];
  541. metadataForUpload.account = appDelegate.activeAccount;
  542. metadataForUpload.date = [NSDate new];
  543. metadataForUpload.directoryID = directoryID;
  544. metadataForUpload.fileID = fileID;
  545. metadataForUpload.fileName = fileName;
  546. metadataForUpload.fileNameView = fileName;
  547. metadataForUpload.session = k_upload_session;
  548. metadataForUpload.sessionSelector = selectorUploadFile;
  549. metadataForUpload.status = k_metadataStatusWaitUpload;
  550. // Add Medtadata for upload
  551. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  552. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  553. [self reloadDatasource];
  554. } else {
  555. [appDelegate messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  556. }
  557. } else {
  558. [appDelegate messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  559. }
  560. }];
  561. }
  562. }
  563. - (void)openImportDocumentPicker
  564. {
  565. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  566. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  567. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  568. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  569. documentProviderMenu.delegate = self;
  570. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  571. }
  572. #pragma --------------------------------------------------------------------------------------------
  573. #pragma mark ===== Assets Picker =====
  574. #pragma --------------------------------------------------------------------------------------------
  575. -(void)dismissFormUploadAssets
  576. {
  577. [self reloadDatasource];
  578. }
  579. - (void)openAssetsPickerController
  580. {
  581. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  582. checkmark.tintColor = [NCBrandColor sharedInstance].brandElement;
  583. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  584. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  585. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  586. [appDelegate aspectNavigationControllerBar:navBar online:YES hidden:NO];
  587. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  588. dispatch_async(dispatch_get_main_queue(), ^{
  589. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  590. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  591. // init picker
  592. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  593. // set delegate
  594. picker.delegate = self;
  595. // to show selection order
  596. //picker.showsSelectionIndex = YES;
  597. // to present picker as a form sheet in iPad
  598. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  599. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  600. // present picker
  601. [self presentViewController:picker animated:YES completion:nil];
  602. });
  603. }];
  604. }
  605. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  606. {
  607. if (picker.selectedAssets.count > k_pickerControllerMax) {
  608. [appDelegate messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:k_CCErrorInternalError];
  609. return NO;
  610. }
  611. return YES;
  612. }
  613. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  614. {
  615. [picker dismissViewControllerAnimated:YES completion:^{
  616. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  617. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  618. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  619. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  620. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  621. [self presentViewController:navigationController animated:YES completion:nil];
  622. }];
  623. }
  624. // New folder or new photo or video
  625. - (void)returnCreate:(NSInteger)type
  626. {
  627. switch (type) {
  628. case k_returnCreateFolderPlain: {
  629. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  630. NSString *message;
  631. UIAlertController *alertController;
  632. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  633. message = @"/";
  634. } else {
  635. message = [serverUrl lastPathComponent];
  636. }
  637. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  638. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  639. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  640. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  641. }];
  642. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  643. NSLog(@"[LOG] Cancel action");
  644. }];
  645. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  646. UITextField *fileName = alertController.textFields.firstObject;
  647. [self createFolder:fileName.text serverUrl:serverUrl];
  648. }];
  649. okAction.enabled = NO;
  650. [alertController addAction:cancelAction];
  651. [alertController addAction:okAction];
  652. [self presentViewController:alertController animated:YES completion:nil];
  653. }
  654. break;
  655. case k_returnCreateFotoVideoPlain: {
  656. [self openAssetsPickerController];
  657. }
  658. break;
  659. case k_returnCreateFilePlain: {
  660. [self openImportDocumentPicker];
  661. }
  662. break;
  663. case k_returnCreateFotoVideoEncrypted: {
  664. [self openAssetsPickerController];
  665. }
  666. break;
  667. case k_returnCreateFileEncrypted: {
  668. [self openImportDocumentPicker];
  669. }
  670. break;
  671. case k_returnCreateFileText: {
  672. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  673. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  674. [self presentViewController:navigationController animated:YES completion:nil];
  675. }
  676. break;
  677. }
  678. }
  679. #pragma --------------------------------------------------------------------------------------------
  680. #pragma mark ===== Save selected File =====
  681. #pragma --------------------------------------------------------------------------------------------
  682. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  683. {
  684. if (error)
  685. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  686. else
  687. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  688. }
  689. - (void)saveSelectedFiles
  690. {
  691. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  692. return;
  693. NSLog(@"[LOG] Start download selected files ...");
  694. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  695. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  696. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  697. for (tableMetadata *metadata in metadatas) {
  698. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  699. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  700. if (serverUrl) {
  701. metadata.session = k_download_session;
  702. metadata.sessionError = @"";
  703. metadata.sessionSelector = selectorSave;
  704. metadata.status = k_metadataStatusWaitDownload;
  705. // Add Metadata for Download
  706. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  707. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  708. }
  709. }
  710. }
  711. [_hud hideHud];
  712. });
  713. [self tableViewSelect:NO];
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ==== View Notification ====
  717. #pragma --------------------------------------------------------------------------------------------
  718. - (void)viewNotification
  719. {
  720. if ([appDelegate.listOfNotifications count] > 0) {
  721. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  722. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  723. [self presentViewController:notificationVC animated:YES completion:nil];
  724. }
  725. }
  726. #pragma --------------------------------------------------------------------------------------------
  727. #pragma mark === Delegate Login ===
  728. #pragma --------------------------------------------------------------------------------------------
  729. - (void)loginSuccess:(NSInteger)loginType
  730. {
  731. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  732. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  733. // go to home sweet home
  734. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  735. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  736. });
  737. }
  738. - (void)loginClose
  739. {
  740. appDelegate.activeLogin = nil;
  741. }
  742. - (void)loginWebClose
  743. {
  744. appDelegate.activeLoginWeb = nil;
  745. }
  746. #pragma mark -
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ===== Peek & Pop =====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  751. {
  752. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  753. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  754. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  755. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO) {
  756. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  757. if (cell) {
  758. previewingContext.sourceRect = cell.frame;
  759. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  760. vc.delegate = self;
  761. vc.metadata = metadata;
  762. return vc;
  763. }
  764. }
  765. return nil;
  766. }
  767. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  768. {
  769. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  770. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  771. }
  772. #pragma mark -
  773. #pragma --------------------------------------------------------------------------------------------
  774. #pragma mark ==== Download Thumbnail Delegate ====
  775. #pragma --------------------------------------------------------------------------------------------
  776. - (void)downloadThumbnailSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  777. {
  778. // Check Active Account
  779. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  780. return;
  781. if (errorCode == 0) {
  782. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  783. if ([self indexPathIsValid:indexPath]) {
  784. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadataNet.fileID fileNameView:metadataNet.fileNameView]])
  785. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  786. }
  787. } else {
  788. NSLog(@"[LOG] Download Thumbnail Failure error %d, %@", (int)errorCode, message);
  789. }
  790. }
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ==== Download ====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (void)downloadStart:(NSString *)fileID account:(NSString *)account task:(NSURLSessionDownloadTask *)task serverUrl:(NSString *)serverUrl
  795. {
  796. [self reloadDatasource: serverUrl];
  797. [appDelegate updateApplicationIconBadgeNumber];
  798. }
  799. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  800. {
  801. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  802. if (metadata == nil)
  803. return;
  804. if (errorCode == 0) {
  805. // Synchronized
  806. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  807. [self reloadDatasource:serverUrl];
  808. }
  809. // add Favorite
  810. if ([selector isEqualToString:selectorAddFavorite]) {
  811. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  812. [self reloadDatasource:serverUrl];
  813. }
  814. // open View File
  815. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  816. [self reloadDatasource:serverUrl];
  817. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  818. selector = selectorOpenIn;
  819. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  820. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  821. selector = selectorOpenIn;
  822. } else {
  823. _metadata = metadata;
  824. if ([self shouldPerformSegue])
  825. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  826. }
  827. }
  828. // Open with...
  829. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  830. [self reloadDatasource:serverUrl];
  831. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  832. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  833. _docController.delegate = self;
  834. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  835. }
  836. // Save to Photo Album
  837. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  838. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  839. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  840. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  841. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  842. if (image)
  843. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  844. else
  845. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  846. }
  847. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  848. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  849. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  850. } else {
  851. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  852. }
  853. }
  854. if (status != PHAuthorizationStatusAuthorized) {
  855. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  856. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  857. [alertController addAction:okAction];
  858. [self presentViewController:alertController animated:YES completion:nil];
  859. }
  860. [self reloadDatasource:serverUrl];
  861. }
  862. // Copy File
  863. if ([selector isEqualToString:selectorLoadCopy]) {
  864. [self reloadDatasource:serverUrl];
  865. [self copyFileToPasteboard:metadata];
  866. }
  867. //selectorLoadViewImage
  868. if ([selector isEqualToString:selectorLoadViewImage]) {
  869. // Detail
  870. if (appDelegate.activeDetail)
  871. [appDelegate.activeDetail downloadPhotoBrowserSuccessFailure:metadata selector:selector errorCode:0];
  872. // Photos
  873. if (appDelegate.activePhotos)
  874. [appDelegate.activePhotos downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selector errorMessage:errorMessage errorCode:errorCode];
  875. [self reloadDatasource:serverUrl];
  876. }
  877. // Auto Download Upload
  878. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  879. } else {
  880. // File do not exists on server, remove in local
  881. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  882. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:fileID] error:nil];
  883. if (metadata.directory && serverUrl) {
  884. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  885. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  886. }
  887. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID] clearDateReadDirectoryID:nil];
  888. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  889. }
  890. if ([selector isEqualToString:selectorLoadViewImage]) {
  891. dispatch_async(dispatch_get_main_queue(), ^{
  892. // Updating Detail
  893. if (appDelegate.activeDetail)
  894. [appDelegate.activeDetail downloadPhotoBrowserSuccessFailure:metadata selector:selector errorCode:errorCode];
  895. // Updating Photos
  896. if (appDelegate.activePhotos)
  897. [appDelegate.activePhotos downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selector errorMessage:errorMessage errorCode:errorCode];
  898. });
  899. } else {
  900. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized && errorCode != k_CCErrorFileAlreadyInDownload)
  901. [appDelegate messageNotification:@"_download_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  902. }
  903. [self reloadDatasource:serverUrl];
  904. }
  905. }
  906. - (void)downloadSelectedFilesFolders
  907. {
  908. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  909. return;
  910. NSLog(@"[LOG] Start download selected ...");
  911. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  912. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  913. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  914. for (tableMetadata *metadata in selectedMetadatas) {
  915. if (metadata.directory) {
  916. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  917. if (serverUrl) {
  918. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  919. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  920. }
  921. } else {
  922. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  923. }
  924. }
  925. [_hud hideHud];
  926. });
  927. [self tableViewSelect:NO];
  928. }
  929. #pragma --------------------------------------------------------------------------------------------
  930. #pragma mark ===== Upload new Photos/Videos =====
  931. #pragma --------------------------------------------------------------------------------------------
  932. - (void)uploadStart:(NSString *)fileID account:(NSString *)account task:(NSURLSessionUploadTask *)task serverUrl:(NSString *)serverUrl
  933. {
  934. [self reloadDatasource: serverUrl];
  935. [appDelegate updateApplicationIconBadgeNumber];
  936. }
  937. - (void)uploadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID assetLocalIdentifier:(NSString *)assetLocalIdentifier serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  938. {
  939. if (errorCode == 0) {
  940. // Auto Download Upload
  941. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  942. } else {
  943. // Activity
  944. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:errorMessage type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  945. if (errorCode != -999 && errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  946. [appDelegate messageNotification:@"_upload_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  947. }
  948. [self reloadDatasource:serverUrl];
  949. }
  950. //
  951. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  952. //
  953. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  954. {
  955. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  956. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  957. // if request create the folder for Photos & the subfolders
  958. if ([autoUploadPath isEqualToString:serverUrl])
  959. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderPhotosWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  960. return;
  961. dispatch_async(dispatch_get_main_queue(), ^{
  962. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  963. });
  964. });
  965. }
  966. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  967. {
  968. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  969. if (!directoryID) return;
  970. for (PHAsset *asset in assets) {
  971. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  972. NSDate *assetDate = asset.creationDate;
  973. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  974. // Create serverUrl if use sub folder
  975. if (useSubFolder) {
  976. [formatter setDateFormat:@"yyyy"];
  977. NSString *yearString = [formatter stringFromDate:assetDate];
  978. [formatter setDateFormat:@"MM"];
  979. NSString *monthString = [formatter stringFromDate:assetDate];
  980. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  981. }
  982. // Check if is in upload
  983. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@ AND session != ''", directoryID, fileName];
  984. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  985. if ([isRecordInSessions count] > 0)
  986. continue;
  987. // Prepare record metadata
  988. tableMetadata *metadataForUpload = [tableMetadata new];
  989. metadataForUpload.account = appDelegate.activeAccount;
  990. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  991. metadataForUpload.date = [NSDate new];
  992. metadataForUpload.directoryID = directoryID;
  993. metadataForUpload.fileID = [directoryID stringByAppendingString:fileName];
  994. metadataForUpload.fileName = fileName;
  995. metadataForUpload.fileNameView = fileName;
  996. metadataForUpload.session = session;
  997. metadataForUpload.sessionSelector = selectorUploadFile;
  998. metadataForUpload.status = k_metadataStatusWaitUpload;
  999. // Check il file already exists
  1000. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView == %@", directoryID, fileName]];
  1001. if (metadata) {
  1002. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1003. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1004. // NO OVERWITE
  1005. }];
  1006. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1007. // Add Medtadata for upload
  1008. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1009. // Start upload now
  1010. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1011. }];
  1012. [alertController addAction:cancelAction];
  1013. [alertController addAction:overwriteAction];
  1014. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  1015. alertWindow.rootViewController = [[UIViewController alloc]init];
  1016. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  1017. [alertWindow makeKeyAndVisible];
  1018. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  1019. } else {
  1020. // Add Medtadata for upload
  1021. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1022. }
  1023. }
  1024. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1025. [self reloadDatasource];
  1026. }
  1027. #pragma --------------------------------------------------------------------------------------------
  1028. #pragma mark ==== Read File ====
  1029. #pragma --------------------------------------------------------------------------------------------
  1030. - (void)readFileSuccessFailure:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata message:(NSString *)message errorCode:(NSInteger)errorCode
  1031. {
  1032. // Check Active Account
  1033. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1034. return;
  1035. if (errorCode == 0) {
  1036. // Read Folder
  1037. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1038. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadataNet.account, metadataNet.serverUrl]];
  1039. // Change etag, read folder
  1040. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1041. [self readFolder:metadataNet.serverUrl];
  1042. }
  1043. }
  1044. } else {
  1045. // Unauthorized
  1046. if (errorCode == kOCErrorServerUnauthorized)
  1047. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1048. }
  1049. }
  1050. - (void)readFileReloadFolder
  1051. {
  1052. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1053. return;
  1054. // Load Datasource
  1055. [self reloadDatasource];
  1056. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1057. metadataNet.action = actionReadFile;
  1058. metadataNet.priority = NSOperationQueuePriorityHigh;
  1059. metadataNet.selector = selectorReadFileReloadFolder;
  1060. metadataNet.serverUrl = _serverUrl;
  1061. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1062. }
  1063. #pragma --------------------------------------------------------------------------------------------
  1064. #pragma mark ==== Read Folder ====
  1065. #pragma --------------------------------------------------------------------------------------------
  1066. - (void)readFolderSuccessFailure:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1067. {
  1068. // stoprefresh
  1069. [_refreshControl endRefreshing];
  1070. // Check Active Account
  1071. if (![metadataNet.account isEqualToString:metadataNet.account])
  1072. return;
  1073. // ERROR
  1074. if (errorCode != 0) {
  1075. _loadingFolder = NO;
  1076. // Check Active Account
  1077. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1078. return;
  1079. // Unauthorized
  1080. if (errorCode == kOCErrorServerUnauthorized) {
  1081. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1082. } else {
  1083. [self tableViewReloadData];
  1084. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1085. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1086. [self reloadDatasource:metadataNet.serverUrl];
  1087. }
  1088. return;
  1089. }
  1090. // save metadataFolder
  1091. _metadataFolder = metadataFolder;
  1092. // save father e update permission
  1093. if(!_isSearchMode && metadataFolder)
  1094. _fatherPermission = metadataFolder.permissions;
  1095. if (_isSearchMode == NO) {
  1096. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1097. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND (status == %d OR status == %d)", metadataNet.directoryID, k_metadataStatusNormal, k_metadataStatusHide] clearDateReadDirectoryID:metadataNet.directoryID];
  1098. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1099. }
  1100. NSArray *metadatasInDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", metadataNet.directoryID, k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusDownloadError] sorted:nil ascending:NO];
  1101. // insert in Database
  1102. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas serverUrl:metadataNet.serverUrl];
  1103. // reinsert metadatas in Download
  1104. if (metadatasInDownload) {
  1105. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload serverUrl:metadataNet.serverUrl];
  1106. }
  1107. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1108. // File is changed ??
  1109. if (!_isSearchMode && metadatasToInsertInDB)
  1110. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  1111. });
  1112. // Search Mode
  1113. if (_isSearchMode) {
  1114. // Fix managed -> Unmanaged _searchResultMetadatas
  1115. if (metadatasToInsertInDB)
  1116. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1117. [self reloadDatasource:metadataNet.serverUrl];
  1118. }
  1119. // this is the same directory
  1120. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1121. // reload
  1122. [self reloadDatasource:metadataNet.serverUrl];
  1123. // Enable change user
  1124. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1125. _loadingFolder = NO;
  1126. [self tableViewReloadData];
  1127. }
  1128. // E2EE Is encrypted folder get metadata
  1129. if (_metadataFolder.e2eEncrypted) {
  1130. // Read Metadata
  1131. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1132. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1133. NSString *metadata;
  1134. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:metadataFolder.fileID metadata:&metadata];
  1135. dispatch_async(dispatch_get_main_queue(), ^{
  1136. if (error) {
  1137. if (error.code != 404)
  1138. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1139. } else {
  1140. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  1141. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1142. else
  1143. [self reloadDatasource];
  1144. }
  1145. });
  1146. });
  1147. } else {
  1148. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1149. }
  1150. }
  1151. // rewrite title
  1152. [self setTitle];
  1153. }
  1154. - (void)readFolder:(NSString *)serverUrl
  1155. {
  1156. // init control
  1157. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1158. [_refreshControl endRefreshing];
  1159. return;
  1160. }
  1161. // Search Mode
  1162. if (_isSearchMode) {
  1163. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1164. _searchFileName = @""; // forced reload searchg
  1165. [self updateSearchResultsForSearchController:self.searchController];
  1166. return;
  1167. }
  1168. _loadingFolder = YES;
  1169. [self tableViewReloadData];
  1170. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1171. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1172. metadataNet.action = actionReadFolder;
  1173. metadataNet.date = [NSDate date];
  1174. metadataNet.depth = @"1";
  1175. metadataNet.directoryID = directory.directoryID;
  1176. metadataNet.priority = NSOperationQueuePriorityHigh;
  1177. metadataNet.selector = selectorReadFolder;
  1178. metadataNet.serverUrl = serverUrl;
  1179. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1180. }
  1181. #pragma mark -
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. #pragma mark ===== Search =====
  1184. #pragma --------------------------------------------------------------------------------------------
  1185. - (void)searchEnabled:(BOOL)enabled
  1186. {
  1187. if (enabled) {
  1188. if (self.tableView.tableHeaderView != nil)
  1189. return;
  1190. self.definesPresentationContext = YES;
  1191. self.searchController.searchResultsUpdater = self;
  1192. self.searchController.dimsBackgroundDuringPresentation = NO;
  1193. self.searchController.searchBar.translucent = NO;
  1194. [self.searchController.searchBar sizeToFit];
  1195. self.searchController.searchBar.delegate = self;
  1196. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1197. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1198. self.searchController.searchBar.backgroundImage = [UIImage new];
  1199. // color searchbbar button text (cancel)
  1200. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  1201. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  1202. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  1203. }
  1204. self.tableView.tableHeaderView = self.searchController.searchBar;
  1205. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1206. } else {
  1207. self.tableView.tableHeaderView = nil;
  1208. }
  1209. }
  1210. - (void)searchStartTimer
  1211. {
  1212. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1213. [[CCActions sharedInstance] search:startDirectory fileName:_searchFileName etag:@"" depth:@"infinity" date:nil contenType:nil selector:selectorSearchFiles delegate:self];
  1214. _noFilesSearchTitle = @"";
  1215. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1216. [self.tableView reloadEmptyDataSet];
  1217. }
  1218. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1219. {
  1220. // Color text "Cancel"
  1221. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1222. _isSearchMode = YES;
  1223. [self deleteRefreshControl];
  1224. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1225. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1226. _searchFileName = fileName;
  1227. // First : filter
  1228. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1229. if (!directoryID) return;
  1230. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView CONTAINS[cd] %@", directoryID, fileName];
  1231. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1232. [_searchResultMetadatas removeAllObjects];
  1233. for (tableMetadata *record in records)
  1234. [_searchResultMetadatas addObject:record];
  1235. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1236. metadataNet.account = appDelegate.activeAccount;
  1237. metadataNet.directoryID = directoryID;
  1238. metadataNet.selector = selectorSearchFiles;
  1239. metadataNet.serverUrl = _serverUrl;
  1240. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas message:nil errorCode:0];
  1241. // Version >= 12
  1242. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1243. [_timerWaitInput invalidate];
  1244. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1245. }
  1246. }
  1247. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1248. [self reloadDatasource];
  1249. }
  1250. }
  1251. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1252. {
  1253. [self cancelSearchBar];
  1254. [self readFolder:_serverUrl];
  1255. }
  1256. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1257. {
  1258. // Check Active Account
  1259. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1260. return;
  1261. if (errorCode == 0) {
  1262. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1263. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:metadatas message:nil errorCode:0];
  1264. } else {
  1265. // Unauthorized
  1266. if (errorCode == kOCErrorServerUnauthorized)
  1267. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1268. else
  1269. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1270. _searchFileName = @"";
  1271. }
  1272. }
  1273. - (void)cancelSearchBar
  1274. {
  1275. if (self.searchController.active) {
  1276. [self.searchController setActive:NO];
  1277. [self createRefreshControl];
  1278. _isSearchMode = NO;
  1279. _searchFileName = @"";
  1280. _dateReadDataSource = nil;
  1281. _searchResultMetadatas = [NSMutableArray new];
  1282. [self reloadDatasource];
  1283. }
  1284. //[self setNeedsStatusBarAppearanceUpdate];
  1285. }
  1286. #pragma mark -
  1287. #pragma --------------------------------------------------------------------------------------------
  1288. #pragma mark ===== Delete File or Folder =====
  1289. #pragma --------------------------------------------------------------------------------------------
  1290. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1291. {
  1292. // Unauthorized
  1293. if (errorCode == kOCErrorServerUnauthorized)
  1294. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1295. [_queueSelector removeObject:metadataNet.selector];
  1296. if ([_queueSelector count] == 0) {
  1297. [_hud hideHud];
  1298. // next
  1299. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1300. if ([_selectedFileIDsMetadatas count] > 0) {
  1301. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1302. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1303. } else {
  1304. // End Select Table View
  1305. [self tableViewSelect:NO];
  1306. // Reload
  1307. if (_isSearchMode)
  1308. [self readFolder:metadataNet.serverUrl];
  1309. else
  1310. [self reloadDatasource:metadataNet.serverUrl];
  1311. }
  1312. }
  1313. }
  1314. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1315. {
  1316. [_queueSelector addObject:selectorDelete];
  1317. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  1318. }
  1319. - (void)deleteFile
  1320. {
  1321. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1322. return;
  1323. [_queueSelector removeAllObjects];
  1324. if ([_selectedFileIDsMetadatas count] > 0) {
  1325. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1326. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1327. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1328. } else {
  1329. _numSelectedFileIDsMetadatas = 1;
  1330. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1331. }
  1332. }
  1333. #pragma --------------------------------------------------------------------------------------------
  1334. #pragma mark ===== Rename / Move =====
  1335. #pragma --------------------------------------------------------------------------------------------
  1336. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1337. {
  1338. [self reloadDatasource:metadataNet.serverUrl];
  1339. }
  1340. - (void)renameFile:(NSArray *)arguments
  1341. {
  1342. tableMetadata* metadata = [arguments objectAtIndex:0];
  1343. NSString *fileName = [arguments objectAtIndex:1];
  1344. // E2EE
  1345. if (_metadataFolder.e2eEncrypted) {
  1346. // verify if exists the new fileName
  1347. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1348. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1349. return;
  1350. }
  1351. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1352. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:self.serverUrl account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileNameRename:metadata.fileName fileNameNewRename:fileName];
  1353. if (error) {
  1354. dispatch_async(dispatch_get_main_queue(), ^{
  1355. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1356. });
  1357. } else {
  1358. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1359. // Move file system
  1360. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  1361. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileName];
  1362. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1363. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileName] error:nil];
  1364. }
  1365. // Unlock
  1366. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1367. if (tableLock != nil) {
  1368. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl serverUrl:self.serverUrl fileID:_metadataFolder.fileID token:tableLock.token];
  1369. if (error) {
  1370. dispatch_async(dispatch_get_main_queue(), ^{
  1371. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1372. });
  1373. }
  1374. }
  1375. dispatch_async(dispatch_get_main_queue(), ^{
  1376. [self reloadDatasource];
  1377. });
  1378. });
  1379. } else {
  1380. // Plain
  1381. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1382. }
  1383. }
  1384. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1385. {
  1386. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1387. [_hud hideHud];
  1388. if (message && errorCode != kOCErrorServerUnauthorized)
  1389. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1390. // End Select Table View
  1391. [self tableViewSelect:NO];
  1392. // reload Datasource
  1393. if (_isSearchMode)
  1394. [self readFolder:metadataNet.serverUrl];
  1395. else
  1396. [self reloadDatasource];
  1397. }
  1398. }
  1399. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1400. {
  1401. [_queueSelector removeObject:metadataNet.selector];
  1402. if ([_queueSelector count] == 0) {
  1403. [_hud hideHud];
  1404. NSString *fileName = metadataNet.fileName;
  1405. NSString *directoryID = metadataNet.directoryID;
  1406. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1407. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1408. if (!serverUrlTo) return;
  1409. // FILE -> Metadata
  1410. if (metadataNet.directory == NO)
  1411. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1412. // DIRECTORY -> Directory - CCMetadata
  1413. if (metadataNet.directory == YES) {
  1414. // delete all dir / subdir
  1415. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1416. // move metadata
  1417. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1418. // Add new directory
  1419. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1420. (void) [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:false favorite:false fileID:nil permissions:nil serverUrl:newDirectory];
  1421. }
  1422. // next
  1423. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1424. if ([_selectedFileIDsMetadatas count] > 0) {
  1425. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1426. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1427. } else {
  1428. // End Select Table View
  1429. [self tableViewSelect:NO];
  1430. // reload Datasource
  1431. if (_isSearchMode)
  1432. [self readFolder:metadataNet.serverUrl];
  1433. else
  1434. [self reloadDatasource];
  1435. }
  1436. }
  1437. }
  1438. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1439. {
  1440. tableMetadata *metadata = [arguments objectAtIndex:0];
  1441. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1442. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1443. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1444. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1445. if (!serverUrl) return;
  1446. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1447. if (!directoryIDTo) return;
  1448. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1449. [ocNetworking readFile:metadata.fileName serverUrl:serverUrlTo account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1450. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1451. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1452. }];
  1453. [alert addAction:ok];
  1454. [self presentViewController:alert animated:YES completion:nil];
  1455. // End Select Table View
  1456. [self tableViewSelect:NO];
  1457. // reload Datasource
  1458. [self readFileReloadFolder];
  1459. } failure:^(NSString *message, NSInteger errorCode) {
  1460. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1461. metadataNet.action = actionMoveFileOrFolder;
  1462. metadataNet.directory = metadata.directory;
  1463. metadataNet.fileID = metadata.fileID;
  1464. metadataNet.directoryID = metadata.directoryID;
  1465. metadataNet.directoryIDTo = directoryIDTo;
  1466. metadataNet.fileName = metadata.fileName;
  1467. metadataNet.fileNameView = metadata.fileNameView;
  1468. metadataNet.fileNameTo = metadata.fileName;
  1469. metadataNet.etag = metadata.etag;
  1470. metadataNet.selector = selectorMove;
  1471. metadataNet.serverUrl = serverUrl;
  1472. metadataNet.serverUrlTo = serverUrlTo;
  1473. [_queueSelector addObject:metadataNet.selector];
  1474. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1475. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1476. }];
  1477. }
  1478. // DELEGATE : Move
  1479. - (void)dismissMove
  1480. {
  1481. [self reloadDatasource];
  1482. }
  1483. // DELEGATE : Move
  1484. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1485. {
  1486. [_queueSelector removeAllObjects];
  1487. // E2EE DENIED
  1488. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1489. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1490. return;
  1491. }
  1492. if ([_selectedFileIDsMetadatas count] > 0) {
  1493. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1494. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1495. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1496. } else {
  1497. _numSelectedFileIDsMetadatas = 1;
  1498. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1499. }
  1500. }
  1501. - (void)moveOpenWindow:(NSArray *)indexPaths
  1502. {
  1503. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1504. return;
  1505. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1506. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1507. viewController.delegate = self;
  1508. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1509. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1510. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1511. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1512. viewController.networkingOperationQueue = appDelegate.netQueue;
  1513. // E2EE
  1514. viewController.includeDirectoryE2EEncryption = NO;
  1515. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1516. [self presentViewController:navigationController animated:YES completion:nil];
  1517. }
  1518. #pragma --------------------------------------------------------------------------------------------
  1519. #pragma mark ===== Create folder =====
  1520. #pragma --------------------------------------------------------------------------------------------
  1521. - (void)createFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1522. {
  1523. if (errorCode == 0) {
  1524. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1525. if (_metadataFolder.e2eEncrypted) {
  1526. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1527. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:metadataNet.fileID serverUrl:newDirectory];
  1528. dispatch_async(dispatch_get_main_queue(), ^{
  1529. if (error) {
  1530. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1531. }
  1532. [self readFolder:self.serverUrl];
  1533. });
  1534. });
  1535. } else {
  1536. [self readFolder:self.serverUrl];
  1537. }
  1538. } else {
  1539. // Unauthorized
  1540. if (errorCode == kOCErrorServerUnauthorized)
  1541. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1542. else
  1543. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1544. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1545. [self reloadDatasource];
  1546. // We are in directory fail ?
  1547. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1548. if (vc)
  1549. [vc.navigationController popViewControllerAnimated:YES];
  1550. }
  1551. }
  1552. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1553. {
  1554. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1555. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1556. if (![fileNameFolder length]) return;
  1557. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1558. if (!directoryID) return;
  1559. metadataNet.action = actionCreateFolder;
  1560. metadataNet.directoryID = directoryID;
  1561. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1562. metadataNet.fileName = fileNameFolder;
  1563. metadataNet.selector = selectorCreateFolder;
  1564. metadataNet.serverUrl = serverUrl;
  1565. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1566. // Create Directory on metadata
  1567. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1568. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1569. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1570. [self reloadDatasource];
  1571. }
  1572. #pragma --------------------------------------------------------------------------------------------
  1573. #pragma mark ===== Progress & Task Button =====
  1574. #pragma --------------------------------------------------------------------------------------------
  1575. - (void)triggerProgressTask:(NSNotification *)notification
  1576. {
  1577. NSDictionary *dict = notification.userInfo;
  1578. NSString *fileID = [dict valueForKey:@"fileID"];
  1579. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1580. float progress = [[dict valueForKey:@"progress"] floatValue];
  1581. long long totalBytes = [[dict valueForKey:@"totalBytes"] longLongValue];
  1582. long long totalBytesExpected = [[dict valueForKey:@"totalBytesExpected"] longLongValue];
  1583. // Check
  1584. if (!fileID || [fileID isEqualToString: @""])
  1585. return;
  1586. [appDelegate.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1587. if (![serverUrl isEqualToString:_serverUrl])
  1588. return;
  1589. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1590. if ([self indexPathIsValid:indexPath]) {
  1591. CCCellMainTransfer *cell = (CCCellMainTransfer *)[self.tableView cellForRowAtIndexPath:indexPath];
  1592. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ - %@", [CCUtility transformedSize:totalBytesExpected], [CCUtility transformedSize:totalBytes]];
  1593. cell.transferButton.progress = progress;
  1594. }
  1595. }
  1596. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1597. {
  1598. UITouch *touch = [[event allTouches] anyObject];
  1599. CGPoint location = [touch locationInView:self.tableView];
  1600. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1601. if ([self indexPathIsValid:indexPath]) {
  1602. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1603. if (metadataSection) {
  1604. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1605. if (metadata)
  1606. [self cancelTaskButton:metadata reloadTable:YES];
  1607. }
  1608. }
  1609. }
  1610. - (void)cancelAllTask:(id)sender
  1611. {
  1612. CGPoint location = [sender locationInView:self.tableView];
  1613. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1614. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1615. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1616. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  1617. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError] clearDateReadDirectoryID:nil];
  1618. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status != %d AND status != %d", appDelegate.activeAccount, k_metadataStatusNormal, k_metadataStatusHide] sorted:@"fileName" ascending:true];
  1619. for (tableMetadata *metadata in metadatas) {
  1620. // Modify
  1621. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  1622. metadata.session = @"";
  1623. metadata.sessionSelector = @"";
  1624. metadata.status = k_metadataStatusNormal;
  1625. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1626. }
  1627. // Cancel Task
  1628. if (metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading) {
  1629. [self cancelTaskButton:metadata reloadTable:NO];
  1630. }
  1631. }
  1632. [self reloadDatasource];
  1633. }]];
  1634. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1635. alertController.popoverPresentationController.sourceView = self.view;
  1636. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1637. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1638. [alertController.view layoutIfNeeded];
  1639. [self presentViewController:alertController animated:YES completion:nil];
  1640. }
  1641. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1642. {
  1643. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1644. __block NSURLSessionTask *findTask;
  1645. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1646. NSString *fileID = metadata.fileID;
  1647. // DOWNLOAD
  1648. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1649. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1650. for (NSURLSessionTask *task in downloadTasks)
  1651. if (task.taskIdentifier == sessionTaskIdentifier) {
  1652. findTask = task;
  1653. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1654. [task cancel];
  1655. }
  1656. if (!findTask) {
  1657. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1658. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1659. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1660. }
  1661. }];
  1662. }
  1663. // UPLOAD
  1664. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1665. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1666. for (NSURLSessionUploadTask *task in uploadTasks)
  1667. if (task.taskIdentifier == sessionTaskIdentifier) {
  1668. findTask = task;
  1669. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1670. [task cancel];
  1671. }
  1672. if (!findTask) {
  1673. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1674. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1675. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1676. }
  1677. }];
  1678. }
  1679. }
  1680. #pragma --------------------------------------------------------------------------------------------
  1681. #pragma mark ===== Shared =====
  1682. #pragma --------------------------------------------------------------------------------------------
  1683. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1684. {
  1685. [_hud hideHud];
  1686. // Check Active Account
  1687. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1688. return;
  1689. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1690. if (result) {
  1691. appDelegate.sharesLink = result[0];
  1692. appDelegate.sharesUserAndGroup = result[1];
  1693. }
  1694. // Notify Shares View
  1695. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1696. if (openWindow) {
  1697. if (_shareOC) {
  1698. [_shareOC reloadData];
  1699. } else {
  1700. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1701. // Apriamo la view
  1702. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1703. _shareOC.delegate = self;
  1704. _shareOC.metadata = metadata;
  1705. _shareOC.serverUrl = metadataNet.serverUrl;
  1706. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1707. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1708. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1709. [self presentViewController:_shareOC animated:YES completion:nil];
  1710. }
  1711. }
  1712. [self tableViewReloadData];
  1713. }
  1714. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1715. {
  1716. [_hud hideHud];
  1717. // Check Active Account
  1718. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1719. return;
  1720. // Unauthorized
  1721. if (errorCode == kOCErrorServerUnauthorized)
  1722. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1723. else
  1724. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1725. if (_shareOC)
  1726. [_shareOC reloadData];
  1727. [self tableViewReloadData];
  1728. }
  1729. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1730. {
  1731. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1732. metadataNet.action = actionShare;
  1733. metadataNet.fileID = metadata.fileID;
  1734. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1735. metadataNet.fileNameView = metadata.fileNameView;
  1736. metadataNet.password = password;
  1737. metadataNet.selector = selectorShare;
  1738. metadataNet.serverUrl = serverUrl;
  1739. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1740. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1741. }
  1742. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1743. {
  1744. [_hud hideHud];
  1745. // Check Active Account
  1746. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1747. return;
  1748. // rimuoviamo la condivisione da db
  1749. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1750. if (result) {
  1751. appDelegate.sharesLink = result[0];
  1752. appDelegate.sharesUserAndGroup = result[1];
  1753. }
  1754. if (_shareOC)
  1755. [_shareOC reloadData];
  1756. [self tableViewReloadData];
  1757. }
  1758. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1759. {
  1760. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1761. metadataNet.action = actionUnShare;
  1762. metadataNet.fileID = metadata.fileID;
  1763. metadataNet.fileName = metadata.fileName;
  1764. metadataNet.fileNameView = metadata.fileNameView;
  1765. metadataNet.selector = selectorUnshare;
  1766. metadataNet.serverUrl = serverUrl;
  1767. metadataNet.share = share;
  1768. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1769. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1770. }
  1771. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1772. {
  1773. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1774. metadataNet.action = actionUpdateShare;
  1775. metadataNet.fileID = metadata.fileID;
  1776. metadataNet.expirationTime = expirationTime;
  1777. metadataNet.password = password;
  1778. metadataNet.selector = selectorUpdateShare;
  1779. metadataNet.serverUrl = serverUrl;
  1780. metadataNet.share = share;
  1781. metadataNet.sharePermission = permission;
  1782. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1783. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1784. }
  1785. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1786. {
  1787. [_hud hideHud];
  1788. // Check Active Account
  1789. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1790. return;
  1791. if (_shareOC)
  1792. [_shareOC reloadUserAndGroup:items];
  1793. }
  1794. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1795. {
  1796. [_hud hideHud];
  1797. // Check Active Account
  1798. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1799. return;
  1800. // Unauthorized
  1801. if (errorCode == kOCErrorServerUnauthorized)
  1802. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1803. else
  1804. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1805. }
  1806. - (void)getUserAndGroup:(NSString *)find
  1807. {
  1808. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1809. metadataNet.action = actionGetUserAndGroup;
  1810. metadataNet.optionAny = find;
  1811. metadataNet.selector = selectorGetUserAndGroup;
  1812. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1813. [_hud visibleIndeterminateHud];
  1814. }
  1815. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1816. {
  1817. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1818. metadataNet.action = actionShareWith;
  1819. metadataNet.fileID = metadata.fileID;
  1820. metadataNet.directoryID = directoryID;
  1821. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1822. metadataNet.fileNameView = metadata.fileNameView;
  1823. metadataNet.serverUrl = serverUrl;
  1824. metadataNet.selector = selectorShare;
  1825. metadataNet.share = user;
  1826. metadataNet.shareeType = shareeType;
  1827. metadataNet.sharePermission = permission;
  1828. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1829. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1830. }
  1831. - (void)openWindowShare:(tableMetadata *)metadata
  1832. {
  1833. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1834. if (!serverUrl) return;
  1835. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1836. metadataNet.action = actionReadShareServer;
  1837. metadataNet.fileID = metadata.fileID;
  1838. metadataNet.fileName = metadata.fileName;
  1839. metadataNet.fileNameView = metadata.fileNameView;
  1840. metadataNet.selector = selectorOpenWindowShare;
  1841. metadataNet.serverUrl = serverUrl;
  1842. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1843. [_hud visibleIndeterminateHud];
  1844. }
  1845. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1846. {
  1847. CGPoint location = [tapGesture locationInView:self.tableView];
  1848. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1849. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1850. if (metadata)
  1851. [self openWindowShare:metadata];
  1852. }
  1853. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1854. {
  1855. CGPoint location = [tapGesture locationInView:self.tableView];
  1856. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1857. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1858. if (metadata) {
  1859. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1860. vc.metadata = metadata;
  1861. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1862. [self presentViewController:vc animated:YES completion:nil];
  1863. }
  1864. }
  1865. #pragma --------------------------------------------------------------------------------------------
  1866. #pragma mark ===== Favorite =====
  1867. #pragma --------------------------------------------------------------------------------------------
  1868. - (void)settingFavoriteSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1869. {
  1870. // Check Active Account
  1871. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1872. return;
  1873. if (errorCode == 0) {
  1874. _dateReadDataSource = nil;
  1875. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.optionAny boolValue]];
  1876. if (_isSearchMode)
  1877. [self readFolder:metadataNet.serverUrl];
  1878. else
  1879. [self reloadDatasource:metadataNet.serverUrl];
  1880. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1881. if (metadata.directory && metadata.favorite) {
  1882. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  1883. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1884. }
  1885. } else {
  1886. if (errorCode == kOCErrorServerUnauthorized)
  1887. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1888. NSLog(@"[LOG] Setting Favorite failure error %d, %@", (int)errorCode, message);
  1889. }
  1890. }
  1891. - (void)addFavorite:(tableMetadata *)metadata
  1892. {
  1893. if (metadata.directory) {
  1894. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1895. } else {
  1896. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1897. if (serverUrl) {
  1898. metadata.session = k_download_session;
  1899. metadata.sessionError = @"";
  1900. metadata.sessionSelector = selectorAddFavorite;
  1901. metadata.status = k_metadataStatusWaitDownload;
  1902. // Add Metadata for Download
  1903. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1904. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1905. }
  1906. }
  1907. }
  1908. - (void)removeFavorite:(tableMetadata *)metadata
  1909. {
  1910. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  1911. }
  1912. #pragma --------------------------------------------------------------------------------------------
  1913. #pragma mark ===== Open in... =====
  1914. #pragma --------------------------------------------------------------------------------------------
  1915. - (void)openIn:(tableMetadata *)metadata
  1916. {
  1917. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1918. if (!serverUrl) return;
  1919. metadata.session = k_download_session;
  1920. metadata.sessionError = @"";
  1921. metadata.sessionSelector = selectorOpenIn;
  1922. metadata.status = k_metadataStatusWaitDownload;
  1923. // Add Metadata for Download
  1924. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1925. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1926. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1927. if ([self indexPathIsValid:indexPath])
  1928. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  1929. }
  1930. #pragma --------------------------------------------------------------------------------------------
  1931. #pragma mark ===== Remove Local File =====
  1932. #pragma --------------------------------------------------------------------------------------------
  1933. - (void)removeLocalFile:(tableMetadata *)metadata
  1934. {
  1935. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  1936. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  1937. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1938. if (serverUrl)
  1939. [self reloadDatasource:serverUrl];
  1940. }
  1941. #pragma --------------------------------------------------------------------------------------------
  1942. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  1943. #pragma --------------------------------------------------------------------------------------------
  1944. - (void)orderTable:(NSString *)order
  1945. {
  1946. [CCUtility setOrderSettings:order];
  1947. // Clear data-read of DataSource
  1948. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1949. }
  1950. - (void)ascendingTable:(BOOL)ascending
  1951. {
  1952. [CCUtility setAscendingSettings:ascending];
  1953. // Clear data-read of DataSource
  1954. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1955. }
  1956. - (void)directoryOnTop:(BOOL)directoryOnTop
  1957. {
  1958. [CCUtility setDirectoryOnTop:directoryOnTop];
  1959. // Clear data-read of DataSource
  1960. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1961. }
  1962. - (void)tableGroupBy:(NSString *)groupBy
  1963. {
  1964. [CCUtility setGroupBySettings:groupBy];
  1965. // Clear data-read of DataSource
  1966. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1967. }
  1968. #pragma --------------------------------------------------------------------------------------------
  1969. #pragma mark ==== Menu LOGO ====
  1970. #pragma --------------------------------------------------------------------------------------------
  1971. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1972. {
  1973. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1974. return;
  1975. // Brand
  1976. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1977. return;
  1978. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1979. NSMutableArray *menuArray = [NSMutableArray new];
  1980. for (NSString *account in listAccount) {
  1981. CCMenuItem *item = [[CCMenuItem alloc] init];
  1982. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1983. item.argument = account;
  1984. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1985. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-avatar.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url]];
  1986. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1987. if (avatar) {
  1988. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1989. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1990. CGSize imageSize = avatarImageView.bounds.size;
  1991. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1992. CGContextRef context = UIGraphicsGetCurrentContext();
  1993. [avatarImageView.layer renderInContext:context];
  1994. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1995. UIGraphicsEndImageContext();
  1996. } else {
  1997. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1998. }
  1999. item.image = avatar;
  2000. item.target = self;
  2001. if ([account isEqualToString:appDelegate.activeAccount]) {
  2002. item.action = nil;
  2003. [menuArray insertObject:item atIndex:0];
  2004. } else {
  2005. item.action = @selector(changeDefaultAccount:);
  2006. [menuArray addObject:item];
  2007. }
  2008. }
  2009. // Add + new account
  2010. CCMenuItem *item = [[CCMenuItem alloc] init];
  2011. item.title = NSLocalizedString(@"_add_account_", nil);
  2012. item.argument = @"";
  2013. item.image = [UIImage imageNamed:@"add"];
  2014. item.target = self;
  2015. item.action = @selector(addNewAccount:);
  2016. [menuArray addObject:item];
  2017. OptionalConfiguration options;
  2018. Color textColor, backgroundColor;
  2019. textColor.R = 0;
  2020. textColor.G = 0;
  2021. textColor.B = 0;
  2022. backgroundColor.R = 1;
  2023. backgroundColor.G = 1;
  2024. backgroundColor.B = 1;
  2025. options.arrowSize = 9;
  2026. options.marginXSpacing = 7;
  2027. options.marginYSpacing = 10;
  2028. options.intervalSpacing = 20;
  2029. options.menuCornerRadius = 6.5;
  2030. options.maskToBackground = NO;
  2031. options.shadowOfMenu = YES;
  2032. options.hasSeperatorLine = YES;
  2033. options.seperatorLineHasInsets = YES;
  2034. options.textColor = textColor;
  2035. options.menuBackgroundColor = backgroundColor;
  2036. CGRect rect = self.view.frame;
  2037. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2038. CGFloat safeAreaTop = 0;
  2039. CGFloat offsetY = 35;
  2040. if (@available(iOS 11, *)) {
  2041. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2042. }
  2043. rect.origin.y = locationY + safeAreaTop + offsetY;
  2044. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2045. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2046. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2047. }
  2048. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2049. {
  2050. NSInteger transferInprogress = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  2051. if (transferInprogress > 0) {
  2052. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2053. return;
  2054. }
  2055. [appDelegate.netQueue cancelAllOperations];
  2056. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2057. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2058. if (tableAccount) {
  2059. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2060. // go to home sweet home
  2061. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2062. }
  2063. });
  2064. }
  2065. - (void)addNewAccount:(CCMenuItem *)sender
  2066. {
  2067. NSInteger transferInprogress = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  2068. if (transferInprogress > 0) {
  2069. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2070. return;
  2071. }
  2072. [appDelegate.netQueue cancelAllOperations];
  2073. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2074. [appDelegate openLoginView:self loginType:loginAdd];
  2075. });
  2076. }
  2077. #pragma --------------------------------------------------------------------------------------------
  2078. #pragma mark ==== ReMenu ====
  2079. #pragma --------------------------------------------------------------------------------------------
  2080. - (void)createReMenuBackgroundView:(REMenu *)menu
  2081. {
  2082. CGFloat safeAreaBottom = 0;
  2083. CGFloat safeAreaTop = 0;
  2084. CGFloat statusBar = 0;
  2085. if (@available(iOS 11, *)) {
  2086. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2087. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2088. }
  2089. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2090. statusBar = 13;
  2091. }
  2092. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2093. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2094. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2095. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2096. [UIView animateWithDuration:0.2 animations:^{
  2097. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2098. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2099. if (y>minimum) {
  2100. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2101. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2102. }
  2103. }];
  2104. }
  2105. - (void)createReMainMenu
  2106. {
  2107. NSString *ordinamento;
  2108. NSString *groupBy = _directoryGroupBy;
  2109. __block NSString *nuovoOrdinamento;
  2110. NSString *titoloNuovo, *titoloAttuale;
  2111. BOOL ascendente;
  2112. __block BOOL nuovoAscendente;
  2113. UIImage *image;
  2114. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2115. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"select"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2116. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2117. [self tableViewSelect:YES];
  2118. }
  2119. }];
  2120. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2121. ordinamento = _directoryOrder;
  2122. if ([ordinamento isEqualToString:@"fileName"]) {
  2123. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  2124. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2125. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2126. nuovoOrdinamento = @"date";
  2127. }
  2128. if ([ordinamento isEqualToString:@"date"]) {
  2129. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  2130. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2131. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2132. nuovoOrdinamento = @"fileName";
  2133. }
  2134. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2135. [self orderTable:nuovoOrdinamento];
  2136. }];
  2137. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2138. ascendente = [CCUtility getAscendingSettings];
  2139. if (ascendente) {
  2140. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  2141. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2142. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2143. nuovoAscendente = false;
  2144. }
  2145. if (!ascendente) {
  2146. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  2147. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2148. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2149. nuovoAscendente = true;
  2150. }
  2151. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2152. [self ascendingTable:nuovoAscendente];
  2153. }];
  2154. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2155. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2156. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2157. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2158. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2159. else [self tableGroupBy:@"alphabetic"];
  2160. }];
  2161. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2162. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2163. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2164. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2165. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2166. else [self tableGroupBy:@"typefile"];
  2167. }];
  2168. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2169. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2170. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2171. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2172. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2173. else [self tableGroupBy:@"date"];
  2174. }];
  2175. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2176. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2177. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2178. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2179. if ([CCUtility getDirectoryOnTop])
  2180. [self directoryOnTop:NO];
  2181. else
  2182. [self directoryOnTop:YES];
  2183. }];
  2184. // REMENU --------------------------------------------------------------------------------------------------------------
  2185. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2186. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2187. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2188. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2189. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2190. appDelegate.reMainMenu.separatorHeight = 0.5;
  2191. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2192. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2193. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2194. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2195. appDelegate.reMainMenu.textShadowColor = nil;
  2196. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2197. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2198. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2199. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2200. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2201. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2202. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2203. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2204. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2205. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2206. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2207. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2208. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2209. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2210. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2211. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2212. appDelegate.reMainMenu.borderWidth = 0.3;
  2213. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2214. appDelegate.reMainMenu.animationDuration = 0.2;
  2215. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2216. appDelegate.reMainMenu.bounce = NO;
  2217. __weak typeof(self) weakSelf = self;
  2218. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2219. // Backgroun reMenu (Gesture)
  2220. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2221. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2222. }];
  2223. }
  2224. - (void)toggleReMainMenu
  2225. {
  2226. if (appDelegate.reMainMenu.isOpen) {
  2227. [appDelegate.reMainMenu close];
  2228. } else {
  2229. [self createReMainMenu];
  2230. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2231. // Backgroun reMenu & (Gesture)
  2232. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2233. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2234. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2235. }
  2236. }
  2237. - (void)createReSelectMenu
  2238. {
  2239. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2240. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2241. [self deleteFile];
  2242. }];
  2243. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2244. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2245. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2246. }];
  2247. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2248. appDelegate.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2249. [self downloadSelectedFilesFolders];
  2250. }];
  2251. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2252. appDelegate.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2253. [self saveSelectedFiles];
  2254. }];
  2255. // E2EE
  2256. if (_metadataFolder.e2eEncrypted) {
  2257. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.downloadItem, appDelegate.saveItem]];
  2258. } else {
  2259. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2260. }
  2261. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2262. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2263. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2264. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2265. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2266. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2267. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2268. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2269. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2270. appDelegate.reSelectMenu.textShadowColor = nil;
  2271. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2272. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2273. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2274. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2275. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2276. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2277. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2278. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2279. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2280. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2281. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2282. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2283. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2284. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2285. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2286. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2287. appDelegate.reSelectMenu.borderWidth = 0.3;
  2288. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2289. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2290. appDelegate.reSelectMenu.animationDuration = 0.2;
  2291. appDelegate.reSelectMenu.bounce = NO;
  2292. __weak typeof(self) weakSelf = self;
  2293. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2294. // Backgroun reMenu (Gesture)
  2295. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2296. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2297. }];
  2298. }
  2299. - (void)toggleReSelectMenu
  2300. {
  2301. if (appDelegate.reSelectMenu.isOpen) {
  2302. [appDelegate.reSelectMenu close];
  2303. } else {
  2304. [self createReSelectMenu];
  2305. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2306. // Backgroun reMenu & (Gesture)
  2307. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2308. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2309. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2310. }
  2311. }
  2312. #pragma --------------------------------------------------------------------------------------------
  2313. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2314. #pragma --------------------------------------------------------------------------------------------
  2315. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2316. {
  2317. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2318. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2319. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2320. if ([self indexPathIsValid:indexPath])
  2321. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2322. else
  2323. _metadata = nil;
  2324. [self becomeFirstResponder];
  2325. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2326. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2327. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2328. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2329. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2330. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2331. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2332. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2333. [menuController setMenuVisible:YES animated:YES];
  2334. }
  2335. }
  2336. - (BOOL)canBecomeFirstResponder
  2337. {
  2338. return YES;
  2339. }
  2340. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2341. {
  2342. // For copy file, copy files, Open in ... :
  2343. //
  2344. // NO Directory
  2345. // NO Error Passcode
  2346. // NO In Session mode (download/upload)
  2347. // NO Template
  2348. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2349. if (_isSelectedMode == NO && _metadata && !_metadata.directory && _metadata.status == k_metadataStatusNormal) return YES;
  2350. else return NO;
  2351. }
  2352. if (@selector(copyFiles:) == action) {
  2353. if (_isSelectedMode) {
  2354. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2355. for (tableMetadata *metadata in selectedMetadatas) {
  2356. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2357. return YES;
  2358. }
  2359. }
  2360. return NO;
  2361. }
  2362. if (@selector(pasteFile:) == action) {
  2363. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2364. NSArray *items = [pasteboard items];
  2365. if ([items count] == 1) {
  2366. // Value : (NSData) fileID
  2367. NSDictionary *dic = [items objectAtIndex:0];
  2368. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2369. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2370. if (fileID) {
  2371. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2372. if (metadata) {
  2373. return [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView];
  2374. } else {
  2375. return NO;
  2376. }
  2377. }
  2378. }
  2379. return NO;
  2380. }
  2381. if (@selector(pasteFiles:) == action) {
  2382. BOOL isValid = NO;
  2383. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2384. NSArray *items = [pasteboard items];
  2385. if ([items count] <= 1) return NO;
  2386. for (NSDictionary *dic in items) {
  2387. // Value : (NSData) fileID
  2388. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2389. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2390. if (fileID) {
  2391. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2392. if (metadata) {
  2393. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  2394. isValid = YES;
  2395. } else {
  2396. isValid = NO;
  2397. break;
  2398. }
  2399. } else {
  2400. isValid = NO;
  2401. break;
  2402. }
  2403. } else {
  2404. isValid = NO;
  2405. break;
  2406. }
  2407. }
  2408. return isValid;
  2409. }
  2410. return NO;
  2411. }
  2412. /************************************ COPY ************************************/
  2413. - (void)copyFile:(id)sender
  2414. {
  2415. // Remove all item
  2416. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2417. pasteboard.items = [[NSArray alloc] init];
  2418. if ([CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  2419. [self copyFileToPasteboard:_metadata];
  2420. } else {
  2421. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2422. if (serverUrl) {
  2423. _metadata.session = k_download_session;
  2424. _metadata.sessionError = @"";
  2425. _metadata.sessionSelector = selectorLoadCopy;
  2426. _metadata.status = k_metadataStatusWaitDownload;
  2427. // Add Metadata for Download
  2428. (void)[[NCManageDatabase sharedInstance] addMetadata:_metadata];
  2429. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2430. }
  2431. }
  2432. }
  2433. - (void)copyFiles:(id)sender
  2434. {
  2435. // Remove all item
  2436. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2437. pasteboard.items = [[NSArray alloc] init];
  2438. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2439. for (tableMetadata *metadata in selectedMetadatas) {
  2440. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  2441. [self copyFileToPasteboard:metadata];
  2442. } else {
  2443. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2444. if (serverUrl) {
  2445. metadata.session = k_download_session;
  2446. metadata.sessionError = @"";
  2447. metadata.sessionSelector = selectorLoadCopy;
  2448. metadata.status = k_metadataStatusWaitDownload;
  2449. // Add Metadata for Download
  2450. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2451. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2452. }
  2453. }
  2454. }
  2455. [self tableViewSelect:NO];
  2456. }
  2457. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2458. {
  2459. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2460. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2461. // Value : (NSData) fileID
  2462. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2463. [items addObject:item];
  2464. [pasteboard setItems:items];
  2465. }
  2466. /************************************ OPEN IN ... ******************************/
  2467. - (void)openinFile:(id)sender
  2468. {
  2469. [self openIn:_metadata];
  2470. }
  2471. /************************************ PASTE ************************************/
  2472. - (void)pasteFile:(id)sender
  2473. {
  2474. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2475. [self uploadFilePasteArray:[pasteboard items]];
  2476. }
  2477. - (void)pasteFiles:(id)sender
  2478. {
  2479. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2480. [self uploadFilePasteArray:[pasteboard items]];
  2481. }
  2482. - (void)uploadFilePasteArray:(NSArray *)items
  2483. {
  2484. for (NSDictionary *dic in items) {
  2485. // Value : (NSData) fileID
  2486. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2487. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2488. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl];
  2489. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2490. if (metadata) {
  2491. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  2492. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView directoryID:directoryID];
  2493. NSString *fileID = [directoryID stringByAppendingString:fileName];
  2494. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileName:fileName]];
  2495. tableMetadata *metadataForUpload = [tableMetadata new];
  2496. metadataForUpload.account = appDelegate.activeAccount;
  2497. metadataForUpload.date = [NSDate new];
  2498. metadataForUpload.directoryID = directoryID;
  2499. metadataForUpload.fileID = fileID;
  2500. metadataForUpload.fileName = fileName;
  2501. metadataForUpload.fileNameView = fileName;
  2502. metadataForUpload.session = k_upload_session;
  2503. metadataForUpload.sessionSelector = selectorUploadFile;
  2504. metadataForUpload.status = k_metadataStatusWaitUpload;
  2505. // Add Medtadata for upload
  2506. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2507. }
  2508. }
  2509. }
  2510. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2511. [self reloadDatasource];
  2512. }
  2513. #pragma --------------------------------------------------------------------------------------------
  2514. #pragma mark ===== Lock Passcode =====
  2515. #pragma --------------------------------------------------------------------------------------------
  2516. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2517. {
  2518. return _failedAttempts;
  2519. }
  2520. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2521. {
  2522. return _lockUntilDate;
  2523. }
  2524. - (void)passcodeViewCloseButtonPressed:(id)sender
  2525. {
  2526. [self dismissViewControllerAnimated:YES completion:nil];
  2527. }
  2528. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2529. {
  2530. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2531. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2532. _lockUntilDate = nil;
  2533. _failedAttempts = 0;
  2534. aResultHandler(YES);
  2535. } else aResultHandler(NO);
  2536. } else aResultHandler(YES);
  2537. }
  2538. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2539. {
  2540. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2541. switch (aViewController.type) {
  2542. case BKPasscodeViewControllerCheckPasscodeType: {
  2543. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2544. // possiamo procedere alla prossima directory
  2545. [self performSegueDirectoryWithControlPasscode:false];
  2546. // avviamo la sessione Passcode Lock con now
  2547. appDelegate.sessionePasscodeLock = [NSDate date];
  2548. }
  2549. // disattivazione lock cartella
  2550. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2551. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2552. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2553. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2554. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2555. }
  2556. [self tableViewReloadData];
  2557. }
  2558. }
  2559. break;
  2560. default:
  2561. break;
  2562. }
  2563. }
  2564. - (void)comandoLockPassword
  2565. {
  2566. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2567. if (!serverUrl) return;
  2568. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2569. // se non è abilitato il Lock Passcode esci
  2570. if ([[CCUtility getBlockCode] length] == 0) {
  2571. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2572. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2573. [alertController addAction:okAction];
  2574. [self presentViewController:alertController animated:YES completion:nil];
  2575. return;
  2576. }
  2577. // se è richiesta la disattivazione si chiede la password
  2578. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2579. if (directory.lock) {
  2580. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2581. viewController.delegate = self;
  2582. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2583. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2584. viewController.inputViewTitlePassword = YES;
  2585. if ([CCUtility getSimplyBlockCode]) {
  2586. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2587. viewController.passcodeInputView.maximumLength = 6;
  2588. } else {
  2589. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2590. viewController.passcodeInputView.maximumLength = 64;
  2591. }
  2592. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2593. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2594. viewController.touchIDManager = touchIDManager;
  2595. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2596. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2597. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2598. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2599. [self presentViewController:navigationController animated:YES completion:nil];
  2600. return;
  2601. }
  2602. // ---------------- ACTIVATE PASSWORD
  2603. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2604. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2605. if ([self indexPathIsValid:indexPath])
  2606. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2607. } else {
  2608. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2609. }
  2610. }
  2611. #pragma mark -
  2612. #pragma --------------------------------------------------------------------------------------------
  2613. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2614. #pragma --------------------------------------------------------------------------------------------
  2615. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2616. {
  2617. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2618. return NO;
  2619. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2620. return NO;
  2621. // E2EE
  2622. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2623. return NO;
  2624. return YES;
  2625. }
  2626. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2627. {
  2628. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2629. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2630. return [self canOpenMenuAction:metadata];
  2631. }
  2632. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2633. {
  2634. }
  2635. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2636. {
  2637. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2638. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2639. if (direction == MGSwipeDirectionRightToLeft) {
  2640. [self actionDelete:indexPath];
  2641. }
  2642. if (direction == MGSwipeDirectionLeftToRight) {
  2643. if (_metadata.favorite)
  2644. [self removeFavorite:_metadata];
  2645. else
  2646. [self addFavorite:_metadata];
  2647. }
  2648. return YES;
  2649. }
  2650. - (void)actionDelete:(NSIndexPath *)indexPath
  2651. {
  2652. // Directory locked ?
  2653. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2654. if (!lockServerUrl) return;
  2655. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2656. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", _metadata.fileID]];
  2657. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2658. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2659. return;
  2660. }
  2661. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2662. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2663. [self performSelector:@selector(deleteFile) withObject:nil];
  2664. }]];
  2665. if (localFile || [CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  2666. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2667. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  2668. }]];
  2669. }
  2670. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2671. [alertController dismissViewControllerAnimated:YES completion:nil];
  2672. }]];
  2673. alertController.popoverPresentationController.sourceView = self.view;
  2674. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2675. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2676. [alertController.view layoutIfNeeded];
  2677. [self presentViewController:alertController animated:YES completion:nil];
  2678. }
  2679. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2680. {
  2681. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2682. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2683. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2684. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2685. if (!serverUrl) return;
  2686. NSString *titoloLock, *titleFavorite;
  2687. if (_metadata.favorite) {
  2688. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2689. } else {
  2690. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2691. }
  2692. if (_metadata.directory) {
  2693. // calcolo lockServerUrl
  2694. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2695. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2696. if (directory.lock)
  2697. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2698. else
  2699. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2700. }
  2701. // ******************************************* AHKActionSheet *******************************************
  2702. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2703. actionSheet.animationDuration = 0.2;
  2704. actionSheet.buttonHeight = 50.0;
  2705. actionSheet.cancelButtonHeight = 50.0f;
  2706. actionSheet.separatorHeight = 5.0f;
  2707. actionSheet.automaticallyTintButtonImages = @(NO);
  2708. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2709. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2710. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2711. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2712. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2713. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2714. // ******************************************* DIRECTORY *******************************************
  2715. if (_metadata.directory) {
  2716. BOOL lockDirectory = NO;
  2717. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2718. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2719. // Directory bloccata ?
  2720. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2721. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2722. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2723. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2724. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2725. height:50.0
  2726. type:AHKActionSheetButtonTypeDisabled
  2727. handler:nil
  2728. ];
  2729. [actionSheet addButtonWithTitle: titleFavorite
  2730. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2731. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2732. height: 50.0
  2733. type: AHKActionSheetButtonTypeDefault
  2734. handler: ^(AHKActionSheet *as) {
  2735. if (_metadata.favorite) [self removeFavorite:_metadata];
  2736. else [self addFavorite:_metadata];
  2737. }];
  2738. if (!lockDirectory && !isFolderEncrypted) {
  2739. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2740. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2741. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2742. height:50.0
  2743. type:AHKActionSheetButtonTypeDefault
  2744. handler:^(AHKActionSheet *as) {
  2745. [self openWindowShare:_metadata];
  2746. }];
  2747. }
  2748. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2749. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2750. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2751. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2752. height:50.0
  2753. type:AHKActionSheetButtonTypeDefault
  2754. handler:^(AHKActionSheet *as) {
  2755. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2756. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2757. textField.text = _metadata.fileNameView;
  2758. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2759. //textField.delegate = self;
  2760. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2761. }];
  2762. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2763. NSLog(@"[LOG] Cancel action");
  2764. }];
  2765. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2766. UITextField *fileName = alertController.textFields.firstObject;
  2767. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2768. }];
  2769. okAction.enabled = NO;
  2770. [alertController addAction:cancelAction];
  2771. [alertController addAction:okAction];
  2772. [self presentViewController:alertController animated:YES completion:nil];
  2773. }];
  2774. }
  2775. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2776. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2777. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2778. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2779. height:50.0
  2780. type:AHKActionSheetButtonTypeDefault
  2781. handler:^(AHKActionSheet *as) {
  2782. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2783. }];
  2784. }
  2785. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2786. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2787. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2788. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2789. height:50.0
  2790. type:AHKActionSheetButtonTypeDefault
  2791. handler:^(AHKActionSheet *as) {
  2792. // Settings new folder Automatatic upload
  2793. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2794. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2795. // Clear data (old) Auto Upload
  2796. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2797. [self readFolder:serverUrl];
  2798. }];
  2799. }
  2800. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2801. [actionSheet addButtonWithTitle:titoloLock
  2802. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2803. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2804. height:50.0
  2805. type:AHKActionSheetButtonTypeDefault
  2806. handler:^(AHKActionSheet *as) {
  2807. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2808. }];
  2809. }
  2810. if (!_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2811. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2812. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2813. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2814. height:50.0
  2815. type:AHKActionSheetButtonTypeDefault
  2816. handler:^(AHKActionSheet *as) {
  2817. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2818. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]];
  2819. dispatch_async(dispatch_get_main_queue(), ^{
  2820. if (error) {
  2821. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2822. } else {
  2823. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2824. [self readFolder:self.serverUrl];
  2825. }
  2826. });
  2827. });
  2828. }];
  2829. }
  2830. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2831. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2832. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2833. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2834. height:50.0
  2835. type:AHKActionSheetButtonTypeDefault
  2836. handler:^(AHKActionSheet *as) {
  2837. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2838. NSError *error = [[NCNetworkingEndToEnd sharedManager] deletemarkEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]];
  2839. dispatch_async(dispatch_get_main_queue(), ^{
  2840. if (error) {
  2841. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2842. } else {
  2843. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2844. [self readFolder:self.serverUrl];
  2845. }
  2846. });
  2847. });
  2848. }];
  2849. }
  2850. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2851. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2852. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2853. height:50.0
  2854. type:AHKActionSheetButtonTypeDestructive
  2855. handler:^(AHKActionSheet *as) {
  2856. [self actionDelete:indexPath];
  2857. }];
  2858. [actionSheet show];
  2859. }
  2860. // ******************************************* FILE *******************************************
  2861. if (!_metadata.directory) {
  2862. UIImage *iconHeader;
  2863. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2864. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:_metadata.fileID fileNameView:_metadata.fileNameView]])
  2865. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:_metadata.fileID fileNameView:_metadata.fileNameView]];
  2866. else
  2867. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2868. [actionSheet addButtonWithTitle: _metadata.fileNameView
  2869. image: iconHeader
  2870. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2871. height: 50.0
  2872. type: AHKActionSheetButtonTypeDisabled
  2873. handler: nil
  2874. ];
  2875. [actionSheet addButtonWithTitle: titleFavorite
  2876. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2877. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2878. height: 50.0
  2879. type: AHKActionSheetButtonTypeDefault
  2880. handler: ^(AHKActionSheet *as) {
  2881. if (_metadata.favorite) [self removeFavorite:_metadata];
  2882. else [self addFavorite:_metadata];
  2883. }];
  2884. if (!_metadataFolder.e2eEncrypted) {
  2885. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2886. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2887. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2888. height: 50.0
  2889. type:AHKActionSheetButtonTypeDefault
  2890. handler:^(AHKActionSheet *as) {
  2891. [self openWindowShare:_metadata];
  2892. }];
  2893. }
  2894. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2895. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2896. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2897. height: 50.0
  2898. type:AHKActionSheetButtonTypeDefault
  2899. handler:^(AHKActionSheet *as) {
  2900. [self performSelector:@selector(openIn:) withObject:_metadata];
  2901. }];
  2902. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2903. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2904. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2905. height: 50.0
  2906. type:AHKActionSheetButtonTypeDefault
  2907. handler:^(AHKActionSheet *as) {
  2908. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2909. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2910. textField.text = _metadata.fileNameView;
  2911. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2912. }];
  2913. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2914. NSLog(@"[LOG] Cancel action");
  2915. }];
  2916. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2917. UITextField *fileName = alertController.textFields.firstObject;
  2918. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2919. }];
  2920. okAction.enabled = NO;
  2921. [alertController addAction:cancelAction];
  2922. [alertController addAction:okAction];
  2923. [self presentViewController:alertController animated:YES completion:nil];
  2924. }];
  2925. if (!_metadataFolder.e2eEncrypted) {
  2926. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2927. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].gray]
  2928. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2929. height:50.0
  2930. type:AHKActionSheetButtonTypeDefault
  2931. handler:^(AHKActionSheet *as) {
  2932. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2933. }];
  2934. }
  2935. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2936. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2937. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2938. height:50.0
  2939. type:AHKActionSheetButtonTypeDestructive
  2940. handler:^(AHKActionSheet *as) {
  2941. [self actionDelete:indexPath];
  2942. }];
  2943. [actionSheet show];
  2944. }
  2945. }
  2946. #pragma --------------------------------------------------------------------------------------------
  2947. #pragma mark - ==== Datasource ====
  2948. #pragma --------------------------------------------------------------------------------------------
  2949. - (void)clearDateReadDataSource:(NSNotification *)notification
  2950. {
  2951. _dateReadDataSource = Nil;
  2952. [self reloadDatasource];
  2953. }
  2954. - (void)reloadDatasource
  2955. {
  2956. [self reloadDatasource:_serverUrl];
  2957. }
  2958. - (void)reloadDatasource:(NSString *)serverUrl
  2959. {
  2960. // test
  2961. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  2962. return;
  2963. // Search Mode
  2964. if (_isSearchMode) {
  2965. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  2966. [self tableViewReloadData];
  2967. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2968. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2969. _noFilesSearchDescription = @"";
  2970. }
  2971. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2972. _noFilesSearchTitle = @"";
  2973. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2974. }
  2975. [self.tableView reloadEmptyDataSet];
  2976. return;
  2977. }
  2978. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  2979. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  2980. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  2981. if (main) {
  2982. [main reloadDatasource];
  2983. } else {
  2984. [self tableViewReloadData];
  2985. // [appDelegate.activeTransfers reloadDatasource];
  2986. }
  2987. return;
  2988. }
  2989. // [appDelegate.activeTransfers reloadDatasource];
  2990. // Settaggio variabili per le ottimizzazioni
  2991. _directoryGroupBy = [CCUtility getGroupBySettings];
  2992. _directoryOrder = [CCUtility getOrderSettings];
  2993. // Remove optimization for encrypted directory
  2994. if (_metadataFolder.e2eEncrypted)
  2995. _dateReadDataSource = nil;
  2996. // current directoryID
  2997. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  2998. // Controllo data lettura Data Source
  2999. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  3000. // Get MetadataFolder
  3001. if (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  3002. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  3003. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3004. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3005. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3006. _dateReadDataSource = [NSDate date];
  3007. // Data Source
  3008. NSString *sorted = _directoryOrder;
  3009. if ([sorted isEqualToString:@"fileName"])
  3010. sorted = @"fileName";
  3011. if (directoryID) {
  3012. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND status != %i", directoryID, k_metadataStatusHide] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3013. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3014. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3015. // get auto upload folder
  3016. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3017. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3018. }
  3019. } else {
  3020. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3021. }
  3022. [self tableViewReloadData];
  3023. }
  3024. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3025. {
  3026. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3027. if (selectedRows.count > 0) {
  3028. for (NSIndexPath *selectionIndex in selectedRows) {
  3029. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3030. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3031. [metadatas addObject:metadata];
  3032. }
  3033. }
  3034. return metadatas;
  3035. }
  3036. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3037. {
  3038. NSInteger section = indexPath.section + 1;
  3039. NSInteger row = indexPath.row + 1;
  3040. NSInteger totSections = [_sectionDataSource.sections count] ;
  3041. if ((totSections < section) || (section > totSections)) {
  3042. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3043. return nil;
  3044. }
  3045. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3046. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3047. if (fileIDs) {
  3048. NSInteger totRows =[fileIDs count] ;
  3049. if ((totRows < row) || (row > totRows)) {
  3050. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3051. return nil;
  3052. }
  3053. } else {
  3054. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3055. return nil;
  3056. }
  3057. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3058. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3059. return metadata;
  3060. }
  3061. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3062. {
  3063. NSInteger totSections =[_sectionDataSource.sections count] ;
  3064. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3065. return nil;
  3066. }
  3067. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3068. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3069. }
  3070. #pragma --------------------------------------------------------------------------------------------
  3071. #pragma mark - ==== Table ====
  3072. #pragma --------------------------------------------------------------------------------------------
  3073. - (void)tableViewSelect:(BOOL)edit
  3074. {
  3075. // chiudiamo eventuali swipe aperti
  3076. if (edit)
  3077. [self.tableView setEditing:NO animated:NO];
  3078. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3079. [self.tableView setEditing:edit animated:YES];
  3080. _isSelectedMode = edit;
  3081. if (edit)
  3082. [self setUINavigationBarSelected];
  3083. else
  3084. [self setUINavigationBarDefault];
  3085. [_selectedFileIDsMetadatas removeAllObjects];
  3086. [self setTitle];
  3087. }
  3088. - (void)tableViewReloadData
  3089. {
  3090. // store selected cells before relod
  3091. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3092. // reload table view
  3093. [self.tableView reloadData];
  3094. // selected cells stored
  3095. for (NSIndexPath *path in indexPaths)
  3096. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3097. [self setTableViewFooter];
  3098. if (self.tableView.editing)
  3099. [self setTitle];
  3100. }
  3101. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3102. {
  3103. if (tableView.editing == 1) {
  3104. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3105. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3106. return NO;
  3107. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  3108. return NO;
  3109. else
  3110. return YES;
  3111. } else {
  3112. [_selectedFileIDsMetadatas removeAllObjects];
  3113. }
  3114. return YES;
  3115. }
  3116. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3117. {
  3118. return 60;
  3119. }
  3120. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3121. {
  3122. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3123. }
  3124. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3125. {
  3126. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3127. }
  3128. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3129. {
  3130. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3131. NSString *sectionTitle = [sections objectAtIndex:section];
  3132. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3133. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3134. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3135. return 20.f;
  3136. }
  3137. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3138. {
  3139. float shift;
  3140. UIVisualEffectView *visualEffectView;
  3141. NSString *titleSection;
  3142. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3143. return nil;
  3144. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3145. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3146. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3147. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3148. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3149. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3150. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3151. else titleSection = NSLocalizedString(titleSection,nil);
  3152. // Format title
  3153. NSString *currentDevice = [CCUtility currentDevice];
  3154. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3155. visualEffectView = [[UIVisualEffectView alloc] init];
  3156. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3157. } else {
  3158. UIVisualEffect *blurEffect;
  3159. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3160. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3161. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3162. }
  3163. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3164. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3165. shift = - 35;
  3166. else
  3167. shift = - 20;
  3168. } else shift = - 10;
  3169. // Title
  3170. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3171. titleLabel.backgroundColor = [UIColor clearColor];
  3172. titleLabel.textColor = [UIColor blackColor];
  3173. titleLabel.font = [UIFont systemFontOfSize:12];
  3174. titleLabel.textAlignment = NSTextAlignmentLeft;
  3175. titleLabel.text = titleSection;
  3176. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3177. [visualEffectView.contentView addSubview:titleLabel];
  3178. // Elements
  3179. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3180. elementLabel.backgroundColor = [UIColor clearColor];
  3181. elementLabel.textColor = [UIColor blackColor];;
  3182. elementLabel.font = [UIFont systemFontOfSize:12];
  3183. elementLabel.textAlignment = NSTextAlignmentRight;
  3184. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3185. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3186. NSUInteger rowsCount = [metadatas count];
  3187. if (rowsCount == 0) return nil;
  3188. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3189. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3190. [visualEffectView.contentView addSubview:elementLabel];
  3191. return visualEffectView;
  3192. }
  3193. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3194. {
  3195. return [_sectionDataSource.sections indexOfObject:title];
  3196. }
  3197. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3198. {
  3199. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3200. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3201. else
  3202. return nil;
  3203. }
  3204. /*
  3205. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3206. {
  3207. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3208. }
  3209. }
  3210. */
  3211. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3212. {
  3213. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3214. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3215. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3216. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3217. if (serverUrl == nil) {
  3218. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3219. }
  3220. // Create File System
  3221. if (metadata.directory) {
  3222. [CCUtility getDirectoryProviderStorageFileID:metadata.fileID];
  3223. } else {
  3224. [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  3225. }
  3226. // CCCell
  3227. if (metadata.status == k_metadataStatusNormal) {
  3228. // NORMAL
  3229. CCCellMain *cell = (CCCellMain *)[tableView dequeueReusableCellWithIdentifier:@"CellMain" forIndexPath:indexPath];
  3230. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3231. cell.accessoryType = UITableViewCellAccessoryNone;
  3232. cell.file.image = nil;
  3233. cell.status.image = nil;
  3234. cell.favorite.image = nil;
  3235. cell.shared.image = nil;
  3236. cell.local.image = nil;
  3237. cell.imageTitleSegue = nil;
  3238. cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3239. // change color selection
  3240. UIView *selectionColor = [UIView new];
  3241. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3242. cell.selectedBackgroundView = selectionColor;
  3243. cell.tintColor = [NCBrandColor sharedInstance].brandElement;
  3244. cell.delegate = self;
  3245. cell.indexPath = indexPath;
  3246. cell.labelTitle.textColor = [UIColor blackColor];
  3247. cell.labelTitle.text = metadata.fileNameView;
  3248. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3249. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3250. BOOL isShare = [metadata.permissions containsString:k_permission_shared] && ![_fatherPermission containsString:k_permission_shared];
  3251. BOOL isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_fatherPermission containsString:k_permission_mounted];
  3252. if (metadata.directory) {
  3253. // lable Info
  3254. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3255. // File Image & Image Title Segue
  3256. if (metadata.e2eEncrypted) {
  3257. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3258. cell.imageTitleSegue = [UIImage imageNamed:@"lock"];
  3259. } else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory]) {
  3260. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3261. cell.imageTitleSegue = [UIImage imageNamed:@"photos"];
  3262. } else if (isShare) {
  3263. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3264. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3265. } else if (isMounted) {
  3266. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3267. cell.imageTitleSegue = [UIImage imageNamed:@"shareMounted"];
  3268. } else if (shareUserAndGroup != nil) {
  3269. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3270. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3271. } else if (shareLink != nil) {
  3272. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3273. cell.imageTitleSegue = [UIImage imageNamed:@"sharebylink"];
  3274. } else
  3275. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3276. // Image Status Lock Passcode
  3277. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3278. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3279. if ((directory.lock && [[CCUtility getBlockCode] length])) {
  3280. cell.status.image = [UIImage imageNamed:@"passcode"];
  3281. }
  3282. } else {
  3283. BOOL iconFileExists = [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3284. // Lable Info
  3285. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", [CCUtility dateDiff:metadata.date], [CCUtility transformedSize:metadata.size]];
  3286. // File Image
  3287. if (iconFileExists) {
  3288. cell.file.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3289. } else {
  3290. if (metadata.iconName.length > 0) {
  3291. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3292. } else {
  3293. cell.file.image = [UIImage imageNamed:@"file"];
  3294. }
  3295. }
  3296. // Local Image
  3297. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  3298. if (localFile && [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  3299. cell.local.image = [UIImage imageNamed:@"local"];
  3300. } else {
  3301. cell.local.image = nil;
  3302. }
  3303. // Download thumbnail
  3304. if (metadata.thumbnailExists && !iconFileExists && !_metadataFolder.e2eEncrypted) {
  3305. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3306. }
  3307. // Status Image
  3308. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName]];
  3309. if (tableE2eEncryption) {
  3310. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3311. }
  3312. // Share
  3313. if (isShare) {
  3314. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].gray];
  3315. } else if (isMounted) {
  3316. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] multiplier:2 color:[NCBrandColor sharedInstance].gray];
  3317. } else if (shareLink != nil) {
  3318. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sharebylink"] multiplier:2 color:[NCBrandColor sharedInstance].gray];
  3319. } else if (shareUserAndGroup != nil) {
  3320. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].gray];
  3321. }
  3322. }
  3323. //
  3324. // File & Directory
  3325. //
  3326. // Favorite
  3327. if (metadata.favorite) {
  3328. cell.favorite.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite];
  3329. }
  3330. // Share add Tap
  3331. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  3332. if (isShare || isMounted) { // Shared with you
  3333. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3334. [tap setNumberOfTapsRequired:1];
  3335. cell.shared.userInteractionEnabled = YES;
  3336. [cell.shared addGestureRecognizer:tap];
  3337. } else if (shareLink != nil || shareUserAndGroup != nil) { // You share
  3338. if (metadata.directory) {
  3339. cell.shared.userInteractionEnabled = NO;
  3340. } else {
  3341. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3342. [tap setNumberOfTapsRequired:1];
  3343. cell.shared.userInteractionEnabled = YES;
  3344. [cell.shared addGestureRecognizer:tap];
  3345. }
  3346. }
  3347. } else {
  3348. cell.shared.userInteractionEnabled = NO;
  3349. }
  3350. // More Image
  3351. cell.more.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"more"] multiplier:2 color:[NCBrandColor sharedInstance].gray];
  3352. if ([self canOpenMenuAction:metadata]) {
  3353. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3354. [tapMore setNumberOfTapsRequired:1];
  3355. cell.more.userInteractionEnabled = YES;
  3356. [cell.more addGestureRecognizer:tapMore];
  3357. }
  3358. // MGSwipeButton
  3359. // LEFT
  3360. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3361. cell.leftExpansion.buttonIndex = 0;
  3362. cell.leftExpansion.fillOnTrigger = NO;
  3363. //centerIconOverText
  3364. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3365. [favoriteButton centerIconOverText];
  3366. // RIGHT
  3367. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3368. cell.rightExpansion.buttonIndex = 0;
  3369. cell.rightExpansion.fillOnTrigger = NO;
  3370. //centerIconOverText
  3371. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3372. [deleteButton centerIconOverText];
  3373. return cell;
  3374. } else {
  3375. // TRASNFER
  3376. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer" forIndexPath:indexPath];
  3377. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3378. cell.accessoryType = UITableViewCellAccessoryNone;
  3379. cell.file.image = nil;
  3380. cell.status.image = nil;
  3381. cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3382. cell.labelTitle.textColor = [UIColor blackColor];
  3383. cell.labelTitle.text = metadata.fileNameView;
  3384. cell.labelInfoFile.text = [CCUtility transformedSize:metadata.size];
  3385. BOOL iconFileExists = [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3386. if (iconFileExists) {
  3387. cell.file.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3388. } else {
  3389. if (metadata.iconName.length > 0) {
  3390. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3391. } else {
  3392. cell.file.image = [UIImage imageNamed:@"file"];
  3393. }
  3394. }
  3395. // Session Upload Extension
  3396. if ([metadata.session isEqualToString:k_upload_session_extension] && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading)) {
  3397. cell.labelTitle.enabled = NO;
  3398. cell.labelInfoFile.enabled = NO;
  3399. cell.userInteractionEnabled = NO;
  3400. // cell.cancelTaskButton.enabled = NO;
  3401. } else {
  3402. cell.labelTitle.enabled = YES;
  3403. cell.labelInfoFile.enabled = YES;
  3404. cell.userInteractionEnabled = YES;
  3405. // cell.cancelTaskButton.enabled = YES;
  3406. }
  3407. // downloadFile
  3408. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError) {
  3409. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3410. // [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"taskCancelDownload"] forState:UIControlStateNormal];
  3411. // cell.cancelTaskButton.hidden = NO;
  3412. }
  3413. // downloadFile Error
  3414. if (metadata.status == k_metadataStatusDownloadError) {
  3415. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3416. if ([metadata.sessionError length] == 0) {
  3417. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3418. } else {
  3419. cell.labelInfoFile.text = metadata.sessionError;
  3420. }
  3421. }
  3422. // uploadFile
  3423. if (metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError) {
  3424. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3425. // [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"taskCancelUpload"] forState:UIControlStateNormal];
  3426. // cell.cancelTaskButton.hidden = NO;
  3427. if (!iconFileExists) {
  3428. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploadCloud"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  3429. }
  3430. cell.labelTitle.enabled = NO;
  3431. }
  3432. // uploadFileError
  3433. if (metadata.status == k_metadataStatusUploadError) {
  3434. cell.labelTitle.enabled = NO;
  3435. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3436. if (!iconFileExists) {
  3437. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploadCloud"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  3438. }
  3439. if ([metadata.sessionError length] == 0) {
  3440. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3441. } else {
  3442. cell.labelInfoFile.text = metadata.sessionError;
  3443. }
  3444. }
  3445. // gesture Transfer
  3446. [cell.transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3447. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  3448. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3449. [cell.transferButton.stopButton addGestureRecognizer:stopLongGesture];
  3450. return cell;
  3451. }
  3452. }
  3453. - (void)setTableViewFooter
  3454. {
  3455. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3456. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3457. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3458. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3459. UIFont *appFont = [UIFont systemFontOfSize:12];
  3460. footerLabel.font = appFont;
  3461. footerLabel.textColor = [UIColor grayColor];
  3462. footerLabel.backgroundColor = [UIColor clearColor];
  3463. footerLabel.textAlignment = NSTextAlignmentCenter;
  3464. NSString *folders;
  3465. NSString *files;
  3466. NSString *footerText;
  3467. if (_sectionDataSource.directories > 1) {
  3468. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3469. } else if (_sectionDataSource.directories == 1){
  3470. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3471. } else {
  3472. folders = @"";
  3473. }
  3474. if (_sectionDataSource.files > 1) {
  3475. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3476. } else if (_sectionDataSource.files == 1){
  3477. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3478. } else {
  3479. files = @"";
  3480. }
  3481. if ([folders isEqualToString:@""]) {
  3482. footerText = files;
  3483. } else if ([files isEqualToString:@""]) {
  3484. footerText = folders;
  3485. } else {
  3486. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3487. }
  3488. footerLabel.text = footerText;
  3489. [footerView addSubview:footerLabel];
  3490. [self.tableView setTableFooterView:footerView];
  3491. }
  3492. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3493. {
  3494. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3495. // settiamo il record file.
  3496. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3497. if (!_metadata)
  3498. return;
  3499. // se non può essere selezionata deseleziona
  3500. if ([cell isEditing] == NO)
  3501. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3502. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3503. if (self.tableView.editing) {
  3504. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3505. [self setTitle];
  3506. return;
  3507. }
  3508. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3509. if (!serverUrl) return;
  3510. // se è in corso una sessione
  3511. if (_metadata.status != k_metadataStatusNormal)
  3512. return;
  3513. // file
  3514. if (_metadata.directory == NO) {
  3515. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3516. if ([CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  3517. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3518. } else {
  3519. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3520. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3521. } else {
  3522. _metadata.session = k_download_session;
  3523. _metadata.sessionError = @"";
  3524. _metadata.sessionSelector = selectorLoadFileView;
  3525. _metadata.status = k_metadataStatusWaitDownload;
  3526. // Add Metadata for Download
  3527. (void)[[NCManageDatabase sharedInstance] addMetadata:_metadata];
  3528. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3529. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3530. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3531. }
  3532. }
  3533. }
  3534. if (_metadata.directory) {
  3535. imageTitleSegue = cell.imageTitleSegue;
  3536. [self performSegueDirectoryWithControlPasscode:true];
  3537. }
  3538. }
  3539. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3540. {
  3541. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3542. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3543. [self setTitle];
  3544. }
  3545. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3546. {
  3547. if (!indexPath)
  3548. return NO;
  3549. NSInteger section = indexPath.section;
  3550. NSInteger row = indexPath.row;
  3551. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3552. if (section > lastSectionIndex || lastSectionIndex < 0)
  3553. return NO;
  3554. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3555. if (rowCount < 0)
  3556. return NO;
  3557. return row <= rowCount;
  3558. }
  3559. #pragma --------------------------------------------------------------------------------------------
  3560. #pragma mark ===== Navigation ====
  3561. #pragma --------------------------------------------------------------------------------------------
  3562. - (BOOL)shouldPerformSegue
  3563. {
  3564. // if background return
  3565. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3566. if (self.view.window == NO)
  3567. return NO;
  3568. // Collapsed ma siamo già in detail esci
  3569. if (self.splitViewController.isCollapsed)
  3570. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3571. return YES;
  3572. }
  3573. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3574. {
  3575. id viewController = segue.destinationViewController;
  3576. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3577. tableMetadata *metadata;
  3578. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3579. UINavigationController *nav = viewController;
  3580. _detailViewController = (CCDetail *)nav.topViewController;
  3581. } else {
  3582. _detailViewController = segue.destinationViewController;
  3583. }
  3584. if ([sender isKindOfClass:[tableMetadata class]]) {
  3585. metadata = sender;
  3586. [allRecordsDataSourceImagesVideos addObject:sender];
  3587. } else {
  3588. metadata = _metadata;
  3589. for (NSString *fileID in _sectionDataSource.allEtag) {
  3590. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3591. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3592. [allRecordsDataSourceImagesVideos addObject:metadata];
  3593. }
  3594. }
  3595. _detailViewController.metadataDetail = metadata;
  3596. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3597. _detailViewController.dateFilterQuery = nil;
  3598. [_detailViewController setTitle:metadata.fileNameView];
  3599. }
  3600. // can i go to next viewcontroller
  3601. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3602. {
  3603. NSString *nomeDir;
  3604. if (self.tableView.editing == NO) {
  3605. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3606. if (!serverUrl) return;
  3607. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3608. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3609. // 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
  3610. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3611. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3612. viewController.delegate = self;
  3613. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3614. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3615. viewController.inputViewTitlePassword = YES;
  3616. if ([CCUtility getSimplyBlockCode]) {
  3617. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3618. viewController.passcodeInputView.maximumLength = 6;
  3619. } else {
  3620. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3621. viewController.passcodeInputView.maximumLength = 64;
  3622. }
  3623. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3624. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3625. viewController.touchIDManager = touchIDManager;
  3626. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3627. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3628. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3629. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3630. [self presentViewController:navController animated:YES completion:nil];
  3631. return;
  3632. }
  3633. // E2EE Check enable
  3634. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3635. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3636. return;
  3637. }
  3638. nomeDir = _metadata.fileName;
  3639. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3640. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3641. if (!viewController) {
  3642. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3643. viewController.serverUrl = serverUrlPush;
  3644. viewController.titleMain = _metadata.fileName;
  3645. viewController.textBackButton = _titleMain;
  3646. viewController.imageTitle = imageTitleSegue;
  3647. // save self
  3648. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3649. [self.navigationController pushViewController:viewController animated:YES];
  3650. } else {
  3651. if (viewController.isViewLoaded) {
  3652. // Icon Title
  3653. viewController.imageTitle = imageTitleSegue;
  3654. // Fix : Application tried to present modally an active controller
  3655. if ([self.navigationController isBeingPresented]) {
  3656. // being presented
  3657. } else if ([self.navigationController isMovingToParentViewController]) {
  3658. // being pushed
  3659. } else {
  3660. [self.navigationController pushViewController:viewController animated:YES];
  3661. }
  3662. }
  3663. }
  3664. }
  3665. }
  3666. @end