CCMain.m 214 KB

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