CCMain.m 207 KB

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