CCMain.m 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234
  1. //
  2. // CCMain.m
  3. // Nextcloud
  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 "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCSynchronize.h"
  26. #import "OCActivity.h"
  27. #import "OCNotifications.h"
  28. #import "OCNotificationsAction.h"
  29. #import "OCFrameworkConstants.h"
  30. #import "OCCapabilities.h"
  31. #import "NCAutoUpload.h"
  32. #import "NCBridgeSwift.h"
  33. #import "NCNetworkingEndToEnd.h"
  34. #import "PKDownloadButton.h"
  35. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, NCSelectDelegate, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate, NCCreateFormUploadConflictDelegate>
  36. {
  37. AppDelegate *appDelegate;
  38. BOOL _isRoot;
  39. BOOL _isViewDidLoad;
  40. NSMutableDictionary *_selectedocIdsMetadatas;
  41. UIImageView *_imageTitleHome;
  42. NSUInteger _failedAttempts;
  43. NSDate *_lockUntilDate;
  44. UIRefreshControl *refreshControl;
  45. CCHud *_hud;
  46. // Datasource
  47. CCSectionDataSourceMetadata *sectionDataSource;
  48. NSDate *_dateReadDataSource;
  49. // Search
  50. NSString *_searchFileName;
  51. NSMutableArray *_searchResultMetadatas;
  52. NSString *_noFilesSearchTitle;
  53. NSString *_noFilesSearchDescription;
  54. NSTimer *_timerWaitInput;
  55. // Automatic Upload Folder
  56. NSString *_autoUploadFileName;
  57. NSString *_autoUploadDirectory;
  58. // Folder
  59. BOOL _loadingFolder;
  60. tableMetadata *_metadataFolder;
  61. CGFloat heightRichWorkspace;
  62. CGFloat heightSearchBar;
  63. }
  64. @end
  65. @implementation CCMain
  66. #pragma --------------------------------------------------------------------------------------------
  67. #pragma mark ===== Init =====
  68. #pragma --------------------------------------------------------------------------------------------
  69. - (id)initWithCoder:(NSCoder *)aDecoder
  70. {
  71. if (self = [super initWithCoder:aDecoder]) {
  72. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  73. appDelegate.activeMain = self;
  74. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  75. }
  76. return self;
  77. }
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== View =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (void)viewDidLoad
  82. {
  83. [super viewDidLoad];
  84. // init object
  85. self.metadata = [tableMetadata new];
  86. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  87. _selectedocIdsMetadatas = [NSMutableDictionary new];
  88. _isViewDidLoad = YES;
  89. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  90. _searchResultMetadatas = [NSMutableArray new];
  91. _searchFileName = @"";
  92. _noFilesSearchTitle = @"";
  93. _noFilesSearchDescription = @"";
  94. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  95. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  96. // delegate
  97. self.tableView.delegate = self;
  98. self.tableView.tableFooterView = [UIView new];
  99. self.tableView.emptyDataSetDelegate = self;
  100. self.tableView.emptyDataSetSource = self;
  101. self.searchController.delegate = self;
  102. self.searchController.searchBar.delegate = self;
  103. // Notification
  104. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:k_notificationCenter_clearDateReadDataSource object:nil];
  105. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:k_notificationCenter_setTitleMain object:nil];
  106. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:k_notificationCenter_progressTask object:nil];
  107. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(favoriteFile:) name:k_notificationCenter_favoriteFile object:nil];
  109. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(renameFile:) name:k_notificationCenter_renameFile object:nil];
  110. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  111. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  112. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createFolder:) name:k_notificationCenter_createFolder object:nil];
  113. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:k_notificationCenter_changeTheming object:nil];
  114. // Search
  115. self.definesPresentationContext = YES;
  116. self.searchController.searchResultsUpdater = self;
  117. self.searchController.dimsBackgroundDuringPresentation = NO;
  118. self.searchController.searchBar.translucent = NO;
  119. self.automaticallyAdjustsScrollViewInsets = false;
  120. [self.searchController.searchBar sizeToFit];
  121. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  122. self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
  123. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  124. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  125. [searchButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  126. }
  127. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  128. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  129. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  130. }
  131. self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.searchController.searchBar.frame.size.height + 40)];
  132. // Load Rich Workspace
  133. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  134. if (@available(iOS 11, *)) {
  135. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  136. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  137. viewRichWorkspaceTapped.delegate = self;
  138. [self.viewRichWorkspace.richView addGestureRecognizer:viewRichWorkspaceTapped];
  139. }
  140. self.sortButton = self.viewRichWorkspace.sortButton;
  141. heightSearchBar = self.viewRichWorkspace.topView.frame.size.height;
  142. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  143. [self.sortButton setTitle: [NSString stringWithFormat:@"Sorted by %@ ", [CCUtility getOrderSettings]] forState:UIControlStateNormal];
  144. [self.sortButton addTarget:self action:@selector(toggleReMainMenu) forControlEvents:UIControlEventTouchUpInside];
  145. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height / 4 + heightSearchBar;
  146. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  147. [self.viewRichWorkspace.searchViewHolder addSubview:self.searchController.searchBar];
  148. // Table Header View
  149. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  150. // Register cell
  151. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  152. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  153. // long press recognizer TableView
  154. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  155. [self.tableView addGestureRecognizer:longPressRecognizer];
  156. // Pull-to-Refresh
  157. [self createRefreshControl];
  158. // Register for 3D Touch Previewing if available
  159. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  160. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  161. }
  162. // if this is not Main (the Main uses inizializeMain)
  163. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  164. // Read (File) Folder
  165. [self readFileReloadFolder];
  166. }
  167. // Title
  168. [self setTitle];
  169. // changeTheming
  170. [self changeTheming];
  171. }
  172. - (void)viewWillAppear:(BOOL)animated
  173. {
  174. [super viewWillAppear:animated];
  175. // test
  176. if (appDelegate.activeAccount.length == 0)
  177. return;
  178. if (_isSelectedMode)
  179. [self setUINavigationBarSelected];
  180. else
  181. [self setUINavigationBarDefault];
  182. // If not editing mode remove _selectedocIds
  183. if (!self.tableView.editing)
  184. [_selectedocIdsMetadatas removeAllObjects];
  185. // Check server URL "/"
  186. if (self.navigationController.viewControllers.firstObject == self && self.serverUrl == nil) {
  187. self.serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  188. }
  189. // Query data source
  190. if (self.searchController.isActive == false) {
  191. [self queryDatasourceWithReloadData:YES serverUrl:self.serverUrl];
  192. }
  193. }
  194. - (void)viewDidAppear:(BOOL)animated
  195. {
  196. [super viewDidAppear:animated];
  197. // Active Main
  198. appDelegate.activeMain = self;
  199. // Test viewDidLoad
  200. if (_isViewDidLoad) {
  201. _isViewDidLoad = NO;
  202. } else {
  203. if (appDelegate.activeAccount.length > 0 && [_selectedocIdsMetadatas count] == 0) {
  204. // Read (file) Folder
  205. [self readFileReloadFolder];
  206. }
  207. }
  208. if (appDelegate.activeAccount.length > 0 && self.serverUrl != nil) {
  209. // Get Shares
  210. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.activeAccount serverUrl:self.serverUrl];
  211. // Get RichWorkspace
  212. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  213. self.richWorkspaceText = directory.richWorkspace;
  214. }
  215. // Title
  216. [self setTitle];
  217. }
  218. - (void)viewWillDisappear:(BOOL)animated
  219. {
  220. [super viewWillDisappear:animated];
  221. }
  222. - (void) viewDidLayoutSubviews
  223. {
  224. [super viewDidLayoutSubviews];
  225. [self setTableViewHeader];
  226. }
  227. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  228. {
  229. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  230. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  231. 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))) {
  232. // Portrait
  233. } else {
  234. // Landscape
  235. }
  236. [self setTableViewHeader];
  237. }];
  238. }
  239. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  240. {
  241. [self viewDidAppear:true];
  242. }
  243. - (BOOL)prefersStatusBarHidden
  244. {
  245. return NO;
  246. }
  247. // detect scroll for remove keyboard in search mode
  248. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  249. {
  250. if (self.searchController.isActive && scrollView == self.tableView) {
  251. [self.searchController.searchBar endEditing:YES];
  252. }
  253. }
  254. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  255. [self updateNavBarShadow:scrollView.contentOffset.y > 0];
  256. }
  257. - (void)changeTheming
  258. {
  259. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  260. // createImagesThemingColor
  261. [[NCMainCommon sharedInstance] createImagesThemingColor];
  262. // Refresh control
  263. refreshControl.tintColor = UIColor.lightGrayColor;
  264. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  265. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  266. // color searchbar
  267. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  268. self.searchController.searchBar.tintColor = NCBrandColor.sharedInstance.brand;
  269. // color searchbbar button text (cancel)
  270. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  271. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  272. [searchButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  273. }
  274. // color textview searchbbar
  275. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  276. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  277. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  278. }
  279. // Rich Workspace
  280. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  281. // Title
  282. [self setTitle];
  283. // Reload Table View
  284. [self tableViewReloadData];
  285. }
  286. #pragma --------------------------------------------------------------------------------------------
  287. #pragma mark ===== Initialization =====
  288. #pragma --------------------------------------------------------------------------------------------
  289. //
  290. // Callers :
  291. //
  292. // ChangeDefaultAccount (delegate)
  293. // Split : inizialize
  294. // Settings Advanced : removeAllFiles
  295. //
  296. - (void)initializeMain:(NSNotification *)notification
  297. {
  298. _dateReadDataSource = nil;
  299. // test
  300. if (appDelegate.activeAccount.length == 0)
  301. return;
  302. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  303. // This is Root home main add list
  304. appDelegate.homeMain = self;
  305. _isRoot = YES;
  306. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  307. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  308. // go Home
  309. [self.navigationController popToRootViewControllerAnimated:NO];
  310. // Remove search mode
  311. [self cancelSearchBar];
  312. // Clear error certificate
  313. [CCUtility setCertificateError:appDelegate.activeAccount error:NO];
  314. // Setting Theming
  315. [appDelegate settingThemingColorBrand];
  316. // Detail
  317. // If AVPlayer in play -> Stop
  318. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  319. [appDelegate.player pause];
  320. }
  321. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  322. // remove all Notification Messages
  323. [appDelegate.listOfNotifications removeAllObjects];
  324. // Not Photos Video in library ? then align and Init Auto Upload
  325. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  326. if ([recordsPhotoLibrary count] == 0) {
  327. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  328. }
  329. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  330. NSLog(@"[LOG] Request Service Server Nextcloud");
  331. [[NCService sharedInstance] startRequestServicesServer];
  332. // Clear datasorce
  333. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  334. // Read this folder
  335. [self readFileReloadFolder];
  336. } else {
  337. // reload datasource
  338. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  339. }
  340. // Registeration push notification
  341. [appDelegate pushNotification];
  342. // Registeration domain File Provider
  343. if (@available(iOS 11, *) ) {
  344. if (k_fileProvider_domain) {
  345. [FileProviderDomain.sharedInstance registerDomain];
  346. } else {
  347. [FileProviderDomain.sharedInstance removeAllDomain];
  348. }
  349. }
  350. }
  351. #pragma --------------------------------------------------------------------------------------------
  352. #pragma mark ==== NotificationCenter ====
  353. #pragma --------------------------------------------------------------------------------------------
  354. - (void)deleteFile:(NSNotification *)notification
  355. {
  356. if (self.view.window == nil) { return; }
  357. NSDictionary *userInfo = notification.userInfo;
  358. tableMetadata *metadata = userInfo[@"metadata"];
  359. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  360. NSString *errorDescription = userInfo[@"errorDescription"];
  361. if (errorCode == 0 && metadata) {
  362. if ([metadata.serverUrl isEqualToString:self.serverUrl]) {
  363. if ([metadata.fileNameView.lowercaseString isEqualToString:k_fileNameRichWorkspace.lowercaseString]) {
  364. [self readFileReloadFolder];
  365. } else {
  366. if (self.searchController.isActive) {
  367. [self readFolder:self.serverUrl];
  368. } else {
  369. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  370. }
  371. }
  372. }
  373. } else {
  374. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  375. }
  376. }
  377. - (void)moveFile:(NSNotification *)notification
  378. {
  379. if (self.view.window == nil) { return; }
  380. NSDictionary *userInfo = notification.userInfo;
  381. tableMetadata *metadata = userInfo[@"metadata"];
  382. tableMetadata *metadataNew = userInfo[@"metadataNew"];
  383. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  384. NSString *errorDescription = userInfo[@"errorDescription"];
  385. if (errorCode == 0) {
  386. if ([metadata.serverUrl isEqualToString:self.serverUrl] || [metadataNew.serverUrl isEqualToString:self.serverUrl]) {
  387. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  388. }
  389. } else {
  390. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  391. }
  392. }
  393. - (void)copyFile:(NSNotification *)notification
  394. {
  395. if (self.view.window == nil) { return; }
  396. NSDictionary *userInfo = notification.userInfo;
  397. tableMetadata *metadata = userInfo[@"metadata"];
  398. NSString *serverUrlTo = userInfo[@"serverUrlTo"];
  399. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  400. NSString *errorDescription = userInfo[@"errorDescription"];
  401. if (errorCode == 0) {
  402. if ([metadata.serverUrl isEqualToString:self.serverUrl] || [serverUrlTo isEqualToString:self.serverUrl]) {
  403. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  404. }
  405. } else {
  406. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  407. }
  408. }
  409. - (void)favoriteFile:(NSNotification *)notification
  410. {
  411. if (self.view.window == nil) { return; }
  412. NSDictionary *userInfo = notification.userInfo;
  413. tableMetadata *metadata = userInfo[@"metadata"];
  414. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  415. NSString *errorDescription = userInfo[@"errorDescription"];
  416. BOOL favorite = [userInfo[@"favorite"] boolValue];
  417. if (errorCode == 0) {
  418. _dateReadDataSource = nil;
  419. if (self.searchController.isActive) {
  420. [self readFolder:self.serverUrl];
  421. } else {
  422. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  423. }
  424. if (metadata.directory && favorite) {
  425. NSString *selector;
  426. if ([CCUtility getFavoriteOffline])
  427. selector = selectorReadFolderWithDownload;
  428. else
  429. selector = selectorReadFolder;
  430. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector account:appDelegate.activeAccount];
  431. }
  432. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  433. metadata.favorite = favorite;
  434. metadata.session = k_download_session;
  435. metadata.sessionError = @"";
  436. metadata.sessionSelector = selectorDownloadSynchronize;
  437. metadata.status = k_metadataStatusWaitDownload;
  438. // Add Metadata for Download
  439. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  440. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  441. [appDelegate startLoadAutoDownloadUpload];
  442. }
  443. } else {
  444. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  445. }
  446. }
  447. - (void)renameFile:(NSNotification *)notification {
  448. if (self.view.window == nil) { return; }
  449. NSDictionary *userInfo = notification.userInfo;
  450. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  451. NSString *errorDescription = userInfo[@"errorDescription"];
  452. if (errorCode == 0) {
  453. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  454. } else {
  455. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  456. }
  457. }
  458. - (void)createFolder:(NSNotification *)notification {
  459. if (self.view.window == nil) { return; }
  460. NSDictionary *userInfo = notification.userInfo;
  461. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  462. NSString *errorDescription = userInfo[@"errorDescription"];
  463. if (errorCode == 0) {
  464. [self readFolder:self.serverUrl];
  465. } else {
  466. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  467. }
  468. }
  469. #pragma --------------------------------------------------------------------------------------------
  470. #pragma mark ==== DZNEmptyDataSetSource ====
  471. #pragma --------------------------------------------------------------------------------------------
  472. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  473. {
  474. if (_loadingFolder)
  475. return NO;
  476. else
  477. return YES;
  478. }
  479. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  480. {
  481. return NCBrandColor.sharedInstance.backgroundView;
  482. }
  483. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  484. {
  485. if (self.searchController.isActive)
  486. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  487. else
  488. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  489. }
  490. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  491. {
  492. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  493. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  494. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  495. activityView.color = NCBrandColor.sharedInstance.brandElement;
  496. [activityView startAnimating];
  497. return activityView;
  498. }
  499. return nil;
  500. }
  501. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  502. {
  503. NSString *text;
  504. if (self.searchController.isActive) {
  505. text = _noFilesSearchTitle;
  506. } else {
  507. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  508. }
  509. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  510. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  511. }
  512. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  513. {
  514. NSString *text;
  515. if (self.searchController.isActive) {
  516. text = _noFilesSearchDescription;
  517. } else {
  518. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  519. }
  520. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  521. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  522. paragraph.alignment = NSTextAlignmentCenter;
  523. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  524. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  525. }
  526. #pragma --------------------------------------------------------------------------------------------
  527. #pragma mark ===== Text Field =====
  528. #pragma --------------------------------------------------------------------------------------------
  529. - (void)minCharTextFieldDidChange:(UITextField *)sender
  530. {
  531. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  532. if (alertController)
  533. {
  534. UITextField *fileName = alertController.textFields.firstObject;
  535. UIAlertAction *okAction = alertController.actions.lastObject;
  536. okAction.enabled = fileName.text.length > 0;
  537. }
  538. }
  539. - (void)textFieldDidBeginEditing:(UITextField *)textField
  540. {
  541. [CCUtility selectFileNameFrom:textField];
  542. }
  543. #pragma --------------------------------------------------------------------------------------------
  544. #pragma mark ===== Graphic Window =====
  545. #pragma --------------------------------------------------------------------------------------------
  546. - (void)createRefreshControl
  547. {
  548. refreshControl = [NCMainRefreshControl new];
  549. self.tableView.refreshControl = refreshControl;
  550. refreshControl.tintColor = UIColor.lightGrayColor;
  551. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  552. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  553. }
  554. - (void)deleteRefreshControl
  555. {
  556. [refreshControl endRefreshing];
  557. for (UIView *subview in [_tableView subviews]) {
  558. if (subview == refreshControl)
  559. [subview removeFromSuperview];
  560. }
  561. if (@available(iOS 10, *)) {
  562. self.tableView.refreshControl = nil;
  563. }
  564. refreshControl = nil;
  565. }
  566. - (void)refreshControlTarget
  567. {
  568. [self readFolder:_serverUrl];
  569. // Actuate `Peek` feedback (weak boom)
  570. AudioServicesPlaySystemSound(1519);
  571. }
  572. - (void)setTitle
  573. {
  574. if (_isSelectedMode) {
  575. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  576. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  577. self.navigationItem.titleView = nil;
  578. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  579. } else {
  580. if (@available(iOS 11.0, *)) {
  581. if (_isRoot) {
  582. self.navigationController.navigationBar.prefersLargeTitles = true;
  583. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  584. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  585. } else {
  586. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
  587. }
  588. }
  589. }
  590. }
  591. - (UIImage *)getImageLogoHome
  592. {
  593. UIImage *image = [UIImage imageNamed:@"themingLogo"];
  594. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  595. if ([NCBrandOptions sharedInstance].use_themingColor && [capabilities.themingColorText isEqualToString:@"#000000"] && [UIImage imageNamed:@"themingLogoBlack"]) {
  596. image = [UIImage imageNamed:@"themingLogoBlack"];
  597. }
  598. if ([NCBrandOptions sharedInstance].use_themingLogo) {
  599. image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@-themingLogo.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl]]];
  600. if (image == nil) image = [UIImage imageNamed:@"themingLogo"];
  601. }
  602. if ([appDelegate.reachability isReachable] == NO) {
  603. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"nonetwork"] width:50 height:50 color:NCBrandColor.sharedInstance.icon];
  604. } else {
  605. return image;
  606. }
  607. }
  608. - (void)setUINavigationBarDefault
  609. {
  610. UIBarButtonItem *buttonNotification, *buttonSelect;
  611. buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  612. buttonSelect.enabled = true;
  613. // <
  614. self.navigationController.navigationBar.hidden = NO;
  615. // Notification
  616. if ([appDelegate.listOfNotifications count] > 0) {
  617. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  618. buttonNotification.tintColor = NCBrandColor.sharedInstance.brandText;
  619. buttonNotification.enabled = true;
  620. }
  621. if (buttonNotification)
  622. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, buttonNotification, nil];
  623. else
  624. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  625. self.navigationItem.leftBarButtonItem = nil;
  626. }
  627. - (void)setUINavigationBarSelected
  628. {
  629. UIImage *icon = [UIImage imageNamed:@"navigationMore"];
  630. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  631. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  632. self.navigationItem.leftBarButtonItem = leftButton;
  633. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  634. }
  635. - (void)cancelSelect
  636. {
  637. [self tableViewSelect:false];
  638. }
  639. #pragma --------------------------------------------------------------------------------------------
  640. #pragma mark ===== Document Picker =====
  641. #pragma --------------------------------------------------------------------------------------------
  642. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  643. {
  644. NSLog(@"[LOG] Cancelled");
  645. }
  646. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  647. {
  648. NSLog(@"[LOG] Cancelled");
  649. }
  650. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  651. {
  652. documentPicker.delegate = self;
  653. [self presentViewController:documentPicker animated:YES completion:nil];
  654. }
  655. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  656. {
  657. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  658. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  659. __block NSError *error;
  660. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  661. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  662. NSString *fileName = [[NCUtility sharedInstance] createFileName:[url lastPathComponent] serverUrl:serverUrl account:appDelegate.activeAccount];
  663. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  664. NSData *data = [NSData dataWithContentsOfURL:newURL];
  665. if (data && error == nil) {
  666. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  667. tableMetadata *metadataForUpload = [tableMetadata new];
  668. metadataForUpload.account = appDelegate.activeAccount;
  669. metadataForUpload.date = [NSDate new];
  670. metadataForUpload.ocId = ocId;
  671. metadataForUpload.fileName = fileName;
  672. metadataForUpload.fileNameView = fileName;
  673. metadataForUpload.serverUrl = serverUrl;
  674. metadataForUpload.session = k_upload_session;
  675. metadataForUpload.sessionSelector = selectorUploadFile;
  676. metadataForUpload.size = data.length;
  677. metadataForUpload.status = k_metadataStatusWaitUpload;
  678. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  679. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  680. [appDelegate startLoadAutoDownloadUpload];
  681. } else {
  682. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  683. }
  684. } else {
  685. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  686. }
  687. }];
  688. }
  689. }
  690. - (void)openImportDocumentPicker
  691. {
  692. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  693. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  694. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  695. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  696. documentProviderMenu.delegate = self;
  697. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  698. }
  699. #pragma --------------------------------------------------------------------------------------------
  700. #pragma mark ===== Assets Picker =====
  701. #pragma --------------------------------------------------------------------------------------------
  702. -(void)dismissFormUploadAssets
  703. {
  704. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  705. }
  706. - (void)openAssetsPickerController
  707. {
  708. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  709. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets, NSArray<NSURL *> * urls) {
  710. if (assets.count > 0) {
  711. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  712. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  713. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets urls:(NSMutableArray *)urls cryptated:NO session:k_upload_session delegate:self];
  714. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  715. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  716. [self presentViewController:navigationController animated:YES completion:nil];
  717. });
  718. }
  719. }];
  720. }
  721. #pragma --------------------------------------------------------------------------------------------
  722. #pragma mark ===== Save selected File =====
  723. #pragma --------------------------------------------------------------------------------------------
  724. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  725. {
  726. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  727. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  728. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  729. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  730. if (image)
  731. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  732. else
  733. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  734. }
  735. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  736. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  737. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  738. } else {
  739. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  740. }
  741. }
  742. if (status != PHAuthorizationStatusAuthorized) {
  743. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  744. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  745. [alertController addAction:okAction];
  746. [self presentViewController:alertController animated:YES completion:nil];
  747. }
  748. }
  749. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  750. {
  751. if (error) {
  752. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  753. }
  754. }
  755. - (void)saveSelectedFiles
  756. {
  757. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  758. return;
  759. NSLog(@"[LOG] Start download selected files ...");
  760. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  761. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  762. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  763. for (tableMetadata *metadata in metadatas) {
  764. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  765. metadata.session = k_download_session;
  766. metadata.sessionError = @"";
  767. metadata.sessionSelector = selectorSave;
  768. metadata.status = k_metadataStatusWaitDownload;
  769. // Add Metadata for Download
  770. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  771. [appDelegate startLoadAutoDownloadUpload];
  772. }
  773. }
  774. [_hud hideHud];
  775. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  776. });
  777. [self tableViewSelect:false];
  778. }
  779. #pragma --------------------------------------------------------------------------------------------
  780. #pragma mark ==== View Notification ====
  781. #pragma --------------------------------------------------------------------------------------------
  782. - (void)viewNotification
  783. {
  784. if ([appDelegate.listOfNotifications count] > 0) {
  785. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  786. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  787. [self presentViewController:notificationVC animated:YES completion:nil];
  788. }
  789. }
  790. #pragma mark -
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ===== Peek & Pop =====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  795. {
  796. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  797. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  798. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  799. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  800. if (cell) {
  801. previewingContext.sourceRect = cell.frame;
  802. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  803. viewController.metadata = metadata;
  804. viewController.imageFile = cell.file.image;
  805. viewController.showOpenIn = true;
  806. viewController.showShare = true;
  807. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  808. viewController.showOpenInternalViewer = true;
  809. }
  810. return viewController;
  811. }
  812. return nil;
  813. }
  814. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  815. {
  816. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  817. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  818. }
  819. #pragma --------------------------------------------------------------------------------------------
  820. #pragma mark ==== Download ====
  821. #pragma --------------------------------------------------------------------------------------------
  822. - (void)downloadSelectedFilesFolders
  823. {
  824. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  825. return;
  826. NSLog(@"[LOG] Start download selected ...");
  827. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  828. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  829. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  830. for (tableMetadata *metadata in selectedMetadatas) {
  831. if (metadata.directory) {
  832. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  833. } else {
  834. [[CCSynchronize sharedSynchronize] readFile:metadata.ocId fileName:metadata.fileName serverUrl:metadata.serverUrl selector:selectorReadFileWithDownload account:appDelegate.activeAccount];
  835. }
  836. }
  837. [_hud hideHud];
  838. });
  839. [self tableViewSelect:false];
  840. }
  841. #pragma --------------------------------------------------------------------------------------------
  842. #pragma mark ===== Upload new Photos/Videos =====
  843. #pragma --------------------------------------------------------------------------------------------
  844. //
  845. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  846. //
  847. - (void)uploadFileAsset:(NSMutableArray *)assets urls:(NSMutableArray *)urls serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  848. {
  849. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  850. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  851. // if request create the folder for Auto Upload & the subfolders
  852. if ([autoUploadPath isEqualToString:serverUrl])
  853. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  854. return;
  855. dispatch_async(dispatch_get_main_queue(), ^{
  856. [self uploadFileAsset:assets urls:urls serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  857. });
  858. });
  859. }
  860. - (void)uploadFileAsset:(NSArray *)assets urls:(NSArray *)urls serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  861. {
  862. NSMutableArray *metadatas = [NSMutableArray new];
  863. NSMutableArray *metadatasMOV = [NSMutableArray new];
  864. NSMutableArray *metadatasConflict = [NSMutableArray new];
  865. for (PHAsset *asset in assets) {
  866. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  867. NSDate *assetDate = asset.creationDate;
  868. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  869. // Create serverUrl if use sub folder
  870. if (useSubFolder) {
  871. [formatter setDateFormat:@"yyyy"];
  872. NSString *yearString = [formatter stringFromDate:assetDate];
  873. [formatter setDateFormat:@"MM"];
  874. NSString *monthString = [formatter stringFromDate:assetDate];
  875. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  876. }
  877. // Check if is in upload
  878. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] sorted:nil ascending:NO];
  879. if ([isRecordInSessions count] > 0)
  880. continue;
  881. // Prepare record metadata
  882. tableMetadata *metadataForUpload = [tableMetadata new];
  883. metadataForUpload.account = appDelegate.activeAccount;
  884. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  885. metadataForUpload.date = [NSDate new];
  886. metadataForUpload.ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  887. metadataForUpload.fileName = fileName;
  888. metadataForUpload.fileNameView = fileName;
  889. metadataForUpload.serverUrl = serverUrl;
  890. metadataForUpload.session = session;
  891. metadataForUpload.sessionSelector = selectorUploadFile;
  892. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  893. metadataForUpload.status = k_metadataStatusWaitUpload;
  894. [CCUtility insertTypeFileIconName:fileName metadata:metadataForUpload];
  895. // verify exists conflict
  896. NSString *fileNameExtension = [fileName pathExtension].lowercaseString;
  897. NSString *fileNameWithoutExtension = [fileName stringByDeletingPathExtension];
  898. NSString *fileNameConflict = fileName;
  899. if ([fileNameExtension isEqualToString:@"heic"] && [CCUtility getFormatCompatibility]) {
  900. fileNameConflict = [fileNameWithoutExtension stringByAppendingString:@".jpg"];
  901. }
  902. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileNameConflict]];
  903. if (metadata) {
  904. [metadatasConflict addObject:metadataForUpload];
  905. } else {
  906. [metadatas addObject:metadataForUpload];
  907. }
  908. // Add Medtadata MOV LIVE PHOTO for upload
  909. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto && urls.count == assets.count) {
  910. NSUInteger index = [assets indexOfObject:asset];
  911. NSURL *url = [urls objectAtIndex:index];
  912. tableMetadata *metadataMOVForUpload = [tableMetadata new];
  913. NSString *fileNameNoExt = [fileName stringByDeletingPathExtension];
  914. NSString *fileName = [NSString stringWithFormat:@"%@.mov", fileNameNoExt];
  915. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  916. metadataMOVForUpload.account = appDelegate.activeAccount;
  917. metadataMOVForUpload.date = [NSDate new];
  918. metadataMOVForUpload.ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  919. metadataMOVForUpload.fileName = fileName;
  920. metadataMOVForUpload.fileNameView = fileName;
  921. metadataMOVForUpload.serverUrl = serverUrl;
  922. metadataMOVForUpload.session = session;
  923. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  924. metadataMOVForUpload.size = fileSize;
  925. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  926. // Prepare file and directory
  927. [CCUtility moveFileAtPath:url.path toPath:[CCUtility getDirectoryProviderStorageOcId:metadataMOVForUpload.ocId fileNameView:fileName]];
  928. [metadatasMOV addObject:metadataMOVForUpload];
  929. }
  930. }
  931. // Verify if file(s) exists
  932. if (metadatasConflict.count > 0) {
  933. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  934. conflict.delegate = self;
  935. conflict.metadatas = metadatas;
  936. conflict.metadatasMOV = metadatasMOV;
  937. conflict.metadatasConflict = metadatasConflict;
  938. [self presentViewController:conflict animated:YES completion:nil];
  939. } else {
  940. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  941. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  942. [appDelegate startLoadAutoDownloadUpload];
  943. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  944. }
  945. }
  946. #pragma --------------------------------------------------------------------------------------------
  947. #pragma mark ==== NCCreateFormUploadConflictDelegate ====
  948. #pragma --------------------------------------------------------------------------------------------
  949. - (void)dismissCreateFormUploadConflictWithMetadatas:(NSArray *)metadatas
  950. {
  951. if (metadatas.count > 0) {
  952. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  953. [appDelegate startLoadAutoDownloadUpload];
  954. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  955. }
  956. }
  957. #pragma --------------------------------------------------------------------------------------------
  958. #pragma mark ==== Read Folder ====
  959. #pragma --------------------------------------------------------------------------------------------
  960. - (void)readFolder:(NSString *)serverUrl
  961. {
  962. // init control
  963. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  964. [refreshControl endRefreshing];
  965. return;
  966. }
  967. // Search Mode
  968. if (self.searchController.isActive) {
  969. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  970. _searchFileName = @""; // forced reload searchg
  971. [self updateSearchResultsForSearchController:self.searchController];
  972. return;
  973. }
  974. _loadingFolder = YES;
  975. [self tableViewReloadData];
  976. [[NCNetworking sharedInstance] readFolderWithServerUrl:serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSInteger errorCode, NSString *errorDescription) {
  977. [refreshControl endRefreshing];
  978. if (errorCode == 0 ) {
  979. _metadataFolder = metadataFolder;
  980. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.activeAccount];
  981. [self setTitle];
  982. // File is changed ??
  983. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  984. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:serverUrl account:account withDownload:NO];
  985. });
  986. // E2EE Is encrypted folder get metadata
  987. if (isFolderEncrypted) {
  988. NSString *metadataFolderFileId = metadataFolder.fileId;
  989. // Read Metadata
  990. if ([CCUtility isEndToEndEnabled:account]) {
  991. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  992. NSString *metadata;
  993. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileId:metadataFolderFileId user:appDelegate.activeUser userID:appDelegate.activeUserID password:[CCUtility getPassword:appDelegate.activeAccount] url:appDelegate.activeUrl];
  994. dispatch_async(dispatch_get_main_queue(), ^{
  995. if (error) {
  996. if (error.code != kOCErrorServerPathNotFound)
  997. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  998. } else {
  999. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:appDelegate.activeUrl] == false)
  1000. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1001. else
  1002. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  1003. }
  1004. });
  1005. });
  1006. } else {
  1007. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1008. }
  1009. }
  1010. if ([serverUrl isEqualToString:_serverUrl]) {
  1011. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  1012. [self tableViewReloadData];
  1013. }
  1014. } else {
  1015. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1016. }
  1017. _loadingFolder = NO;
  1018. }];
  1019. }
  1020. - (void)readFileReloadFolder
  1021. {
  1022. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1023. return;
  1024. // RichWorkspace
  1025. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  1026. self.richWorkspaceText = directory.richWorkspace;
  1027. [self setTableViewHeader];
  1028. // Load Datasource
  1029. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1030. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1031. });
  1032. [[NCNetworking sharedInstance] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  1033. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1034. // Rich Workspace
  1035. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadata.ocId serverUrl:self.serverUrl richWorkspace:metadata.richWorkspace account:account];
  1036. self.richWorkspaceText = metadata.richWorkspace;
  1037. [self setTableViewHeader];
  1038. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  1039. // Read folder: No record, Change etag or BLINK
  1040. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  1041. [self readFolder:self.serverUrl];
  1042. }
  1043. } else if (errorCode != 0) {
  1044. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1045. }
  1046. }];
  1047. }
  1048. #pragma mark -
  1049. #pragma --------------------------------------------------------------------------------------------
  1050. #pragma mark ===== Search =====
  1051. #pragma --------------------------------------------------------------------------------------------
  1052. - (void)searchStartTimer
  1053. {
  1054. if (self.searchController.isActive == false) {
  1055. return;
  1056. }
  1057. [[NCCommunication sharedInstance] searchLiteralWithServerUrl:appDelegate.activeUrl depth:@"infinity" literal:_searchFileName showHiddenFiles:[CCUtility getShowHiddenFiles] customUserAgent:nil addCustomHeaders:nil user:appDelegate.activeUser account:appDelegate.activeAccount completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *errorDescription) {
  1058. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount] && files != nil) {
  1059. [[NCManageDatabase sharedInstance] convertNCFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  1060. NSMutableArray *metadatasDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  1061. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasDB];
  1062. _metadataFolder = nil;
  1063. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  1064. [self tableViewReloadData];
  1065. [self setTitle];
  1066. }];
  1067. } else {
  1068. if (errorCode != 0) {
  1069. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1070. }
  1071. _searchFileName = @"";
  1072. }
  1073. }];
  1074. _noFilesSearchTitle = @"";
  1075. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1076. [self.tableView reloadEmptyDataSet];
  1077. }
  1078. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1079. {
  1080. // Color text "Cancel"
  1081. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brand];
  1082. if (searchController.isActive) {
  1083. [self deleteRefreshControl];
  1084. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1085. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1086. _searchFileName = fileName;
  1087. _metadataFolder = nil;
  1088. // First : filter
  1089. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1090. [_searchResultMetadatas removeAllObjects];
  1091. for (tableMetadata *record in records) {
  1092. [_searchResultMetadatas addObject:record];
  1093. }
  1094. // Version >= 12
  1095. if ([[NCManageDatabase sharedInstance] getServerVersionWithAccount:appDelegate.activeAccount] >= 12) {
  1096. [_timerWaitInput invalidate];
  1097. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1098. }
  1099. [self setTitle];
  1100. }
  1101. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1102. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1103. }
  1104. } else {
  1105. [self createRefreshControl];
  1106. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1107. }
  1108. }
  1109. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1110. {
  1111. [self cancelSearchBar];
  1112. }
  1113. - (void)cancelSearchBar
  1114. {
  1115. if (self.searchController.active) {
  1116. [self.searchController setActive:NO];
  1117. _searchFileName = @"";
  1118. _dateReadDataSource = nil;
  1119. _searchResultMetadatas = [NSMutableArray new];
  1120. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1121. }
  1122. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1123. [self setTableViewHeader];
  1124. });
  1125. }
  1126. #pragma mark -
  1127. #pragma --------------------------------------------------------------------------------------------
  1128. #pragma mark ===== Delete File or Folder =====
  1129. #pragma --------------------------------------------------------------------------------------------
  1130. - (void)deleteMetadatas
  1131. {
  1132. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1133. return;
  1134. if ([_selectedocIdsMetadatas count] > 0) {
  1135. [appDelegate.arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1136. } else {
  1137. [appDelegate.arrayDeleteMetadata addObject:self.metadata];
  1138. }
  1139. [[NCNetworking sharedInstance] deleteMetadata:appDelegate.arrayDeleteMetadata.firstObject user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1140. [appDelegate.arrayDeleteMetadata removeObjectAtIndex:0];
  1141. // End Select Table View
  1142. [self tableViewSelect:false];
  1143. }
  1144. #pragma --------------------------------------------------------------------------------------------
  1145. #pragma mark ===== Move / Copy =====
  1146. #pragma --------------------------------------------------------------------------------------------
  1147. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1148. {
  1149. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1150. return;
  1151. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1152. if (move) {
  1153. arrayMetadata = appDelegate.arrayMoveMetadata;
  1154. arrayServerUrlTo = appDelegate.arrayMoveServerUrlTo;
  1155. } else {
  1156. arrayMetadata = appDelegate.arrayCopyMetadata;
  1157. arrayServerUrlTo = appDelegate.arrayCopyServerUrlTo;
  1158. }
  1159. if ([_selectedocIdsMetadatas count] > 0) {
  1160. for (NSString *key in _selectedocIdsMetadatas) {
  1161. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1162. [arrayMetadata addObject:metadata];
  1163. [arrayServerUrlTo addObject:serverUrlTo];
  1164. }
  1165. } else {
  1166. [arrayMetadata addObject:metadata];
  1167. [arrayServerUrlTo addObject:serverUrlTo];
  1168. }
  1169. if (move) {
  1170. [[NCNetworking sharedInstance] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1171. } else {
  1172. [[NCNetworking sharedInstance] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1173. }
  1174. [arrayMetadata removeObjectAtIndex:0];
  1175. [arrayServerUrlTo removeObjectAtIndex:0];
  1176. // End Select Table View
  1177. [self tableViewSelect:false];
  1178. }
  1179. // DELEGATE : Select
  1180. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1181. {
  1182. if (serverUrl == nil) {
  1183. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1184. } else {
  1185. // E2EE DENIED
  1186. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1187. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1188. return;
  1189. }
  1190. BOOL move = true;
  1191. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1192. if ([_selectedocIdsMetadatas count] > 0) {
  1193. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1194. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1195. } else {
  1196. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1197. }
  1198. }
  1199. }
  1200. - (void)moveOpenWindow:(NSArray *)indexPaths
  1201. {
  1202. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1203. return;
  1204. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1205. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1206. viewController.delegate = self;
  1207. viewController.hideButtonCreateFolder = false;
  1208. viewController.selectFile = false;
  1209. viewController.includeDirectoryE2EEncryption = false;
  1210. viewController.includeImages = false;
  1211. viewController.type = @"";
  1212. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1213. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1214. viewController.isButtonDone1Hide = false;
  1215. viewController.isOverwriteHide = false;
  1216. viewController.layoutViewSelect = k_layout_view_move;
  1217. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1218. [self presentViewController:navigationController animated:YES completion:nil];
  1219. }
  1220. #pragma --------------------------------------------------------------------------------------------
  1221. #pragma mark ===== Create folder =====
  1222. #pragma --------------------------------------------------------------------------------------------
  1223. - (void)createFolder
  1224. {
  1225. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1226. NSString *message;
  1227. UIAlertController *alertController;
  1228. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1229. message = @"/";
  1230. } else {
  1231. message = [serverUrl lastPathComponent];
  1232. }
  1233. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1234. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1235. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1236. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1237. }];
  1238. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1239. NSLog(@"[LOG] Cancel action");
  1240. }];
  1241. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1242. UITextField *fileName = alertController.textFields.firstObject;
  1243. [[NCNetworking sharedInstance] createFolderWithFileName:fileName.text serverUrl:serverUrl account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1244. }];
  1245. okAction.enabled = NO;
  1246. [alertController addAction:cancelAction];
  1247. [alertController addAction:okAction];
  1248. [self presentViewController:alertController animated:YES completion:nil];
  1249. }
  1250. #pragma --------------------------------------------------------------------------------------------
  1251. #pragma mark ===== Progress & Task Button =====
  1252. #pragma --------------------------------------------------------------------------------------------
  1253. - (void)triggerProgressTask:(NSNotification *)notification
  1254. {
  1255. if (sectionDataSource.ocIdIndexPath != nil) {
  1256. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1257. }
  1258. }
  1259. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1260. {
  1261. UITouch *touch = [[event allTouches] anyObject];
  1262. CGPoint location = [touch locationInView:self.tableView];
  1263. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1264. if ([self indexPathIsValid:indexPath]) {
  1265. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1266. if (metadataSection) {
  1267. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1268. if (metadata)
  1269. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1270. }
  1271. }
  1272. }
  1273. - (void)cancelAllTask:(id)sender
  1274. {
  1275. CGPoint location = [sender locationInView:self.tableView];
  1276. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1277. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1278. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1279. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1280. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1281. [NCUtility.sharedInstance stopActivityIndicator];
  1282. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1283. }]];
  1284. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1285. alertController.popoverPresentationController.sourceView = self.tableView;
  1286. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1287. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1288. [alertController.view layoutIfNeeded];
  1289. [self presentViewController:alertController animated:YES completion:nil];
  1290. }
  1291. #pragma --------------------------------------------------------------------------------------------
  1292. #pragma mark ===== Tap =====
  1293. #pragma --------------------------------------------------------------------------------------------
  1294. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1295. {
  1296. CGPoint location = [tapGesture locationInView:self.tableView];
  1297. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1298. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1299. if (metadata) {
  1300. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1301. }
  1302. }
  1303. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1304. {
  1305. CGPoint location = [tapGesture locationInView:self.tableView];
  1306. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1307. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1308. if (metadata) {
  1309. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1310. }
  1311. }
  1312. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1313. {
  1314. CGPoint location = [tapGesture locationInView:self.tableView];
  1315. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1316. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1317. if (metadata) {
  1318. }
  1319. }
  1320. #pragma --------------------------------------------------------------------------------------------
  1321. #pragma mark ===== Rich Workspace =====
  1322. #pragma --------------------------------------------------------------------------------------------
  1323. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1324. {
  1325. [UIView animateWithDuration:0.5 animations:^{
  1326. [self.tableView setContentOffset:CGPointMake(0, heightSearchBar)];
  1327. } completion:^(BOOL finished) {
  1328. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1329. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1330. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1331. viewerRichWorkspace.serverUrl = self.serverUrl;
  1332. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1333. [self presentViewController:navigationController animated:NO completion:NULL];
  1334. }];
  1335. }
  1336. - (void)createRichWorkspace
  1337. {
  1338. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1339. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1340. if (metadata) {
  1341. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1342. } else {
  1343. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1344. }
  1345. }
  1346. #pragma --------------------------------------------------------------------------------------------
  1347. #pragma mark ==== Menu LOGO ====
  1348. #pragma --------------------------------------------------------------------------------------------
  1349. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1350. {
  1351. // Brand
  1352. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1353. return;
  1354. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1355. NSMutableArray *menuArray = [NSMutableArray new];
  1356. for (NSString *account in listAccount) {
  1357. CCMenuItem *item = [[CCMenuItem alloc] init];
  1358. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1359. item.argument = account;
  1360. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1361. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1362. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1363. if (avatar) {
  1364. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1365. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1366. CGSize imageSize = avatarImageView.bounds.size;
  1367. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1368. CGContextRef context = UIGraphicsGetCurrentContext();
  1369. [avatarImageView.layer renderInContext:context];
  1370. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1371. UIGraphicsEndImageContext();
  1372. } else {
  1373. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1374. }
  1375. item.image = avatar;
  1376. item.target = self;
  1377. if ([account isEqualToString:appDelegate.activeAccount]) {
  1378. item.action = nil;
  1379. [menuArray insertObject:item atIndex:0];
  1380. } else {
  1381. item.action = @selector(changeDefaultAccount:);
  1382. [menuArray addObject:item];
  1383. }
  1384. }
  1385. // Add + new account
  1386. CCMenuItem *item = [[CCMenuItem alloc] init];
  1387. item.title = NSLocalizedString(@"_add_account_", nil);
  1388. item.argument = @"";
  1389. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1390. item.target = self;
  1391. item.action = @selector(addNewAccount:);
  1392. [menuArray addObject:item];
  1393. OptionalConfiguration options;
  1394. Color backgroundColor;
  1395. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1396. backgroundColor.R = componentsBackgroundColor[0];
  1397. backgroundColor.G = componentsBackgroundColor[1];
  1398. backgroundColor.B = componentsBackgroundColor[2];
  1399. options.arrowSize = 9;
  1400. options.marginXSpacing = 7;
  1401. options.marginYSpacing = 10;
  1402. options.intervalSpacing = 20;
  1403. options.menuCornerRadius = 6.5;
  1404. options.maskToBackground = NO;
  1405. options.shadowOfMenu = YES;
  1406. options.hasSeperatorLine = YES;
  1407. options.seperatorLineHasInsets = YES;
  1408. options.textColor = NCBrandColor.sharedInstance.textView;
  1409. options.menuBackgroundColor = backgroundColor;
  1410. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1411. CGRect rect = self.view.frame;
  1412. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1413. CGFloat safeAreaTop = 0;
  1414. CGFloat offsetY = 35;
  1415. if (@available(iOS 11, *)) {
  1416. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1417. }
  1418. rect.origin.y = locationY + safeAreaTop + offsetY;
  1419. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1420. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1421. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1422. }
  1423. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1424. {
  1425. // LOGOUT
  1426. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1427. if (tableAccount) {
  1428. // LOGIN
  1429. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1430. // go to home sweet home
  1431. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1432. }
  1433. }
  1434. - (void)addNewAccount:(CCMenuItem *)sender
  1435. {
  1436. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1437. }
  1438. - (void)toggleReMainMenu
  1439. {
  1440. [self toggleMenuWithViewController:self.navigationController];
  1441. }
  1442. - (void)toggleReSelectMenu
  1443. {
  1444. [self toggleSelectMenuWithViewController:self.navigationController];
  1445. }
  1446. #pragma --------------------------------------------------------------------------------------------
  1447. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1448. #pragma --------------------------------------------------------------------------------------------
  1449. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1450. {
  1451. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1452. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1453. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1454. NSMutableArray *items = [NSMutableArray new];
  1455. if ([self indexPathIsValid:indexPath])
  1456. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1457. else
  1458. self.metadata = nil;
  1459. [self becomeFirstResponder];
  1460. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1461. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1462. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1463. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1464. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1465. }
  1466. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  1467. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_internal_view_", nil) action:@selector(openInternalViewerTouch:)]];
  1468. }
  1469. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1470. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1471. [menuController setMenuItems:items];
  1472. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1473. [menuController setMenuVisible:YES animated:YES];
  1474. }
  1475. }
  1476. - (BOOL)canBecomeFirstResponder
  1477. {
  1478. return YES;
  1479. }
  1480. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1481. {
  1482. // For copy file, copy files, Open in ... :
  1483. //
  1484. // NO Directory
  1485. // NO Error Passcode
  1486. // NO In Session mode (download/upload)
  1487. // NO Template
  1488. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openInternalViewerTouch:) == action) {
  1489. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1490. else return NO;
  1491. }
  1492. if (@selector(copyTouchFiles:) == action) {
  1493. if (_isSelectedMode) {
  1494. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1495. for (tableMetadata *metadata in selectedMetadatas) {
  1496. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1497. return YES;
  1498. }
  1499. }
  1500. return NO;
  1501. }
  1502. if (@selector(pasteTouchFile:) == action) {
  1503. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1504. NSArray *items = [pasteboard items];
  1505. if ([items count] == 1) {
  1506. // Value : (NSData) ocId
  1507. NSDictionary *dic = [items objectAtIndex:0];
  1508. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1509. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1510. if (ocId) {
  1511. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1512. if (metadata) {
  1513. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1514. } else {
  1515. return NO;
  1516. }
  1517. }
  1518. }
  1519. return NO;
  1520. }
  1521. if (@selector(pasteTouchFiles:) == action) {
  1522. BOOL isValid = NO;
  1523. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1524. NSArray *items = [pasteboard items];
  1525. if ([items count] <= 1) return NO;
  1526. for (NSDictionary *dic in items) {
  1527. // Value : (NSData) ocId
  1528. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1529. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1530. if (ocId) {
  1531. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1532. if (metadata) {
  1533. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1534. isValid = YES;
  1535. } else {
  1536. isValid = NO;
  1537. break;
  1538. }
  1539. } else {
  1540. isValid = NO;
  1541. break;
  1542. }
  1543. } else {
  1544. isValid = NO;
  1545. break;
  1546. }
  1547. }
  1548. return isValid;
  1549. }
  1550. return NO;
  1551. }
  1552. /************************************ COPY ************************************/
  1553. - (void)copyTouchFile:(id)sender
  1554. {
  1555. // Remove all item
  1556. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1557. pasteboard.items = [[NSArray alloc] init];
  1558. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1559. [self copyFileToPasteboard:self.metadata];
  1560. } else {
  1561. self.metadata.session = k_download_session;
  1562. self.metadata.sessionError = @"";
  1563. self.metadata.sessionSelector = selectorLoadCopy;
  1564. self.metadata.status = k_metadataStatusWaitDownload;
  1565. // Add Metadata for Download
  1566. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1567. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  1568. [appDelegate startLoadAutoDownloadUpload];
  1569. }
  1570. }
  1571. - (void)copyTouchFiles:(id)sender
  1572. {
  1573. // Remove all item
  1574. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1575. pasteboard.items = [[NSArray alloc] init];
  1576. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1577. for (tableMetadata *metadata in selectedMetadatas) {
  1578. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1579. [self copyFileToPasteboard:metadata];
  1580. } else {
  1581. metadata.session = k_download_session;
  1582. metadata.sessionError = @"";
  1583. metadata.sessionSelector = selectorLoadCopy;
  1584. metadata.status = k_metadataStatusWaitDownload;
  1585. // Add Metadata for Download
  1586. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1587. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1588. [appDelegate startLoadAutoDownloadUpload];
  1589. }
  1590. }
  1591. [self tableViewSelect:false];
  1592. }
  1593. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1594. {
  1595. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1596. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1597. // Value : (NSData) ocId
  1598. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1599. [items addObject:item];
  1600. [pasteboard setItems:items];
  1601. }
  1602. /************************************ OPEN IN ... ******************************/
  1603. - (void)openinTouchFile:(id)sender
  1604. {
  1605. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1606. }
  1607. /************************************ OPEN INTERNAL VIEWER ... ******************************/
  1608. - (void)openInternalViewerTouch:(id)sender
  1609. {
  1610. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileInternalView];
  1611. }
  1612. /************************************ PASTE ************************************/
  1613. - (void)pasteTouchFile:(id)sender
  1614. {
  1615. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1616. [self uploadFilePasteArray:[pasteboard items]];
  1617. }
  1618. - (void)pasteTouchFiles:(id)sender
  1619. {
  1620. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1621. [self uploadFilePasteArray:[pasteboard items]];
  1622. }
  1623. - (void)uploadFilePasteArray:(NSArray *)items
  1624. {
  1625. for (NSDictionary *dic in items) {
  1626. // Value : (NSData) ocId
  1627. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1628. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1629. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1630. if (metadata) {
  1631. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1632. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1633. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  1634. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1635. tableMetadata *metadataForUpload = [tableMetadata new];
  1636. metadataForUpload.account = appDelegate.activeAccount;
  1637. metadataForUpload.date = [NSDate new];
  1638. metadataForUpload.ocId = ocId;
  1639. metadataForUpload.fileName = fileName;
  1640. metadataForUpload.fileNameView = fileName;
  1641. metadataForUpload.serverUrl = self.serverUrl;
  1642. metadataForUpload.session = k_upload_session;
  1643. metadataForUpload.sessionSelector = selectorUploadFile;
  1644. metadataForUpload.size = metadata.size;
  1645. metadataForUpload.status = k_metadataStatusWaitUpload;
  1646. // Add Medtadata for upload
  1647. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1648. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1649. }
  1650. }
  1651. }
  1652. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1653. [appDelegate startLoadAutoDownloadUpload];
  1654. }
  1655. #pragma --------------------------------------------------------------------------------------------
  1656. #pragma mark ===== Lock Passcode =====
  1657. #pragma --------------------------------------------------------------------------------------------
  1658. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  1659. {
  1660. return _failedAttempts;
  1661. }
  1662. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  1663. {
  1664. return _lockUntilDate;
  1665. }
  1666. - (void)passcodeViewCloseButtonPressed:(id)sender
  1667. {
  1668. [self dismissViewControllerAnimated:YES completion:nil];
  1669. }
  1670. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  1671. {
  1672. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  1673. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  1674. _lockUntilDate = nil;
  1675. _failedAttempts = 0;
  1676. aResultHandler(YES);
  1677. } else aResultHandler(NO);
  1678. } else aResultHandler(YES);
  1679. }
  1680. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  1681. {
  1682. [aViewController dismissViewControllerAnimated:YES completion:nil];
  1683. switch (aViewController.type) {
  1684. case BKPasscodeViewControllerCheckPasscodeType: {
  1685. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  1686. // possiamo procedere alla prossima directory
  1687. [self performSegueDirectoryWithControlPasscode:false metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1688. // avviamo la sessione Passcode Lock con now
  1689. appDelegate.sessionePasscodeLock = [NSDate date];
  1690. }
  1691. // disattivazione lock cartella
  1692. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  1693. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  1694. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  1695. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1696. }
  1697. [self tableViewReloadData];
  1698. }
  1699. }
  1700. break;
  1701. default:
  1702. break;
  1703. }
  1704. }
  1705. - (void)comandoLockPassword
  1706. {
  1707. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  1708. // se non è abilitato il Lock Passcode esci
  1709. if ([[CCUtility getBlockCode] length] == 0) {
  1710. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1711. UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_go_to_app_settings_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1712. [self.tabBarController setSelectedIndex:4];
  1713. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1714. NSIndexPath *selectedIndex = [NSIndexPath indexPathForRow:0 inSection:1];
  1715. [appDelegate.activeMore.tableView selectRowAtIndexPath:selectedIndex animated:true scrollPosition: UITableViewScrollPositionNone];
  1716. [appDelegate.activeMore tableView:appDelegate.activeMore.tableView didSelectRowAtIndexPath:selectedIndex];
  1717. });
  1718. }];
  1719. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1720. [alertController addAction:goToSettingsAction];
  1721. [alertController addAction:okAction];
  1722. [self presentViewController:alertController animated:YES completion:nil];
  1723. return;
  1724. }
  1725. // se è richiesta la disattivazione si chiede la password
  1726. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  1727. if (directory.lock) {
  1728. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  1729. viewController.delegate = self;
  1730. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  1731. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  1732. viewController.inputViewTitlePassword = YES;
  1733. if ([CCUtility getSimplyBlockCode]) {
  1734. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  1735. viewController.passcodeInputView.maximumLength = 6;
  1736. } else {
  1737. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  1738. viewController.passcodeInputView.maximumLength = 64;
  1739. }
  1740. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  1741. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  1742. viewController.touchIDManager = touchIDManager;
  1743. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  1744. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  1745. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  1746. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  1747. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1748. [self presentViewController:navigationController animated:YES completion:nil];
  1749. return;
  1750. }
  1751. // ---------------- ACTIVATE PASSWORD
  1752. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  1753. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:self.metadata.ocId];
  1754. if ([self indexPathIsValid:indexPath])
  1755. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  1756. } else {
  1757. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1758. }
  1759. }
  1760. #pragma mark -
  1761. #pragma --------------------------------------------------------------------------------------------
  1762. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1763. #pragma --------------------------------------------------------------------------------------------
  1764. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1765. {
  1766. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  1767. return NO;
  1768. // E2EE
  1769. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  1770. return NO;
  1771. return YES;
  1772. }
  1773. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1774. {
  1775. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1776. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1777. return [self canOpenMenuAction:metadata];
  1778. }
  1779. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1780. {
  1781. }
  1782. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1783. {
  1784. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1785. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1786. if (direction == MGSwipeDirectionRightToLeft) {
  1787. [self actionDelete:indexPath];
  1788. }
  1789. if (direction == MGSwipeDirectionLeftToRight) {
  1790. [[NCNetworking sharedInstance] favoriteMetadata:self.metadata url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1791. }
  1792. return YES;
  1793. }
  1794. - (void)actionDelete:(NSIndexPath *)indexPath
  1795. {
  1796. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1797. // Directory locked ?
  1798. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  1799. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  1800. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1801. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  1802. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_folder_blocked_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1803. return;
  1804. }
  1805. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1806. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1807. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1808. }]];
  1809. if (localFile) {
  1810. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1811. tableMetadata *metadataLivePhoto = [[NCUtility sharedInstance] isLivePhotoWithMetadata:metadata];
  1812. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1813. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1814. if (metadataLivePhoto) {
  1815. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1816. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1817. }
  1818. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1819. }]];
  1820. }
  1821. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1822. }]];
  1823. alertController.popoverPresentationController.sourceView = self.tableView;
  1824. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1825. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1826. [alertController.view layoutIfNeeded];
  1827. [self presentViewController:alertController animated:YES completion:nil];
  1828. }
  1829. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1830. {
  1831. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1832. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1833. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1834. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1835. }
  1836. #pragma --------------------------------------------------------------------------------------------
  1837. #pragma mark - ==== Datasource ====
  1838. #pragma --------------------------------------------------------------------------------------------
  1839. - (void)clearDateReadDataSource:(NSNotification *)notification
  1840. {
  1841. _dateReadDataSource = Nil;
  1842. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1843. }
  1844. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  1845. {
  1846. // test
  1847. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  1848. return;
  1849. // Search Mode
  1850. if (self.searchController.isActive) {
  1851. // Create metadatas
  1852. NSMutableArray *metadatas = [NSMutableArray new];
  1853. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1854. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  1855. if (metadata) {
  1856. [metadatas addObject:metadata];
  1857. }
  1858. }
  1859. // [CCUtility getGroupBySettings]
  1860. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  1861. [self tableViewReloadData];
  1862. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1863. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1864. _noFilesSearchDescription = @"";
  1865. }
  1866. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1867. _noFilesSearchTitle = @"";
  1868. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1869. }
  1870. [self.tableView reloadEmptyDataSet];
  1871. return;
  1872. }
  1873. // Se non siamo nella dir appropriata esci
  1874. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  1875. return;
  1876. }
  1877. // Controllo data lettura Data Source
  1878. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1879. if (tableDirectory == nil) {
  1880. return;
  1881. }
  1882. // Get MetadataFolder
  1883. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  1884. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  1885. else
  1886. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  1887. // Remove optimization for encrypted directory
  1888. if (_metadataFolder.e2eEncrypted)
  1889. _dateReadDataSource = nil;
  1890. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  1891. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  1892. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  1893. _dateReadDataSource = [NSDate date];
  1894. // Data Source
  1895. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1896. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  1897. dispatch_async(dispatch_get_main_queue(), ^{
  1898. sectionDataSource = sectionDataSourceTemp;
  1899. [self tableViewReloadData];
  1900. });
  1901. });
  1902. } else {
  1903. [self tableViewReloadData];
  1904. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  1905. }
  1906. // BLINK
  1907. if (self.blinkFileNamePath != nil) {
  1908. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1909. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1910. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1911. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1912. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1913. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1914. if ([key isEqualToString:metadata.ocId]) {
  1915. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1916. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1917. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1918. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1919. if (cell) {
  1920. self.blinkFileNamePath = nil;
  1921. [[NCUtility sharedInstance] blinkWithCell:cell];
  1922. }
  1923. });
  1924. }
  1925. }
  1926. }
  1927. }
  1928. });
  1929. }
  1930. }
  1931. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  1932. {
  1933. // test
  1934. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  1935. return nil;
  1936. }
  1937. // get auto upload folder
  1938. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1939. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  1940. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  1941. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl] sorted:nil ascending:NO];
  1942. // [CCUtility getGroupBySettings]
  1943. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  1944. if (withReloadData) {
  1945. sectionDataSource = sectionDataSourceTemp;
  1946. [self tableViewReloadData];
  1947. }
  1948. return sectionDataSourceTemp;
  1949. }
  1950. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1951. {
  1952. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1953. if (selectedRows.count > 0) {
  1954. for (NSIndexPath *selectionIndex in selectedRows) {
  1955. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1956. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1957. [metadatas addObject:metadata];
  1958. }
  1959. }
  1960. return metadatas;
  1961. }
  1962. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1963. {
  1964. NSInteger totSections =[sectionDataSource.sections count] ;
  1965. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1966. return nil;
  1967. }
  1968. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1969. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1970. }
  1971. #pragma --------------------------------------------------------------------------------------------
  1972. #pragma mark - ==== Table ====
  1973. #pragma --------------------------------------------------------------------------------------------
  1974. - (void)tableViewToggle
  1975. {
  1976. [self tableViewSelect:!_isSelectedMode];
  1977. }
  1978. - (void)tableViewSelect:(BOOL)toggle
  1979. {
  1980. _isSelectedMode = toggle;
  1981. // chiudiamo eventuali swipe aperti
  1982. if (_isSelectedMode)
  1983. [self.tableView setEditing:NO animated:NO];
  1984. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1985. [self.tableView setEditing:_isSelectedMode animated:YES];
  1986. if (_isSelectedMode)
  1987. [self setUINavigationBarSelected];
  1988. else
  1989. [self setUINavigationBarDefault];
  1990. [_selectedocIdsMetadatas removeAllObjects];
  1991. [self setTitle];
  1992. }
  1993. - (void)tableViewReloadData
  1994. {
  1995. // store selected cells before relod
  1996. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1997. // reload table view
  1998. [self.tableView reloadData];
  1999. // selected cells stored
  2000. for (NSIndexPath *path in indexPaths)
  2001. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2002. [self setTableViewHeader];
  2003. [self setTableViewFooter];
  2004. if (self.tableView.editing)
  2005. [self setTitle];
  2006. [self.tableView reloadEmptyDataSet];
  2007. }
  2008. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2009. {
  2010. if (tableView.editing == 1) {
  2011. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2012. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2013. return NO;
  2014. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2015. return NO;
  2016. else
  2017. return YES;
  2018. } else {
  2019. [_selectedocIdsMetadatas removeAllObjects];
  2020. }
  2021. return YES;
  2022. }
  2023. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2024. {
  2025. return 60;
  2026. }
  2027. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2028. {
  2029. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2030. }
  2031. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2032. {
  2033. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2034. }
  2035. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2036. {
  2037. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2038. NSString *sectionTitle = [sections objectAtIndex:section];
  2039. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2040. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2041. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2042. return 20.f;
  2043. }
  2044. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2045. {
  2046. float shift;
  2047. UIVisualEffectView *visualEffectView;
  2048. NSString *titleSection;
  2049. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2050. return nil;
  2051. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2052. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2053. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2054. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2055. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2056. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2057. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2058. else titleSection = NSLocalizedString(titleSection,nil);
  2059. // Format title
  2060. UIVisualEffect *blurEffect;
  2061. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2062. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2063. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  2064. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2065. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2066. shift = - 35;
  2067. else
  2068. shift = - 20;
  2069. } else shift = - 10;
  2070. // Title
  2071. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2072. titleLabel.backgroundColor = [UIColor clearColor];
  2073. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  2074. titleLabel.font = [UIFont systemFontOfSize:12];
  2075. titleLabel.textAlignment = NSTextAlignmentLeft;
  2076. titleLabel.text = titleSection;
  2077. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2078. [visualEffectView.contentView addSubview:titleLabel];
  2079. // Elements
  2080. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2081. elementLabel.backgroundColor = [UIColor clearColor];
  2082. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  2083. elementLabel.font = [UIFont systemFontOfSize:12];
  2084. elementLabel.textAlignment = NSTextAlignmentRight;
  2085. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2086. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2087. NSUInteger rowsCount = [metadatas count];
  2088. if (rowsCount == 0) return nil;
  2089. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2090. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2091. [visualEffectView.contentView addSubview:elementLabel];
  2092. return visualEffectView;
  2093. }
  2094. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2095. {
  2096. return [sectionDataSource.sections indexOfObject:title];
  2097. }
  2098. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2099. {
  2100. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2101. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2102. else
  2103. return nil;
  2104. }
  2105. /*
  2106. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2107. {
  2108. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2109. }
  2110. }
  2111. */
  2112. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2113. {
  2114. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2115. tableShare *shareCell;
  2116. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  2117. return [CCCellMain new];
  2118. }
  2119. for (tableShare *share in appDelegate.shares) {
  2120. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  2121. shareCell = share;
  2122. break;
  2123. }
  2124. }
  2125. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  2126. // NORMAL - > MAIN
  2127. if ([cell isKindOfClass:[CCCellMain class]]) {
  2128. // Comment tap
  2129. if (metadata.commentsUnread) {
  2130. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  2131. [tapComment setNumberOfTapsRequired:1];
  2132. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  2133. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  2134. }
  2135. // Share add Tap
  2136. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2137. [tapShare setNumberOfTapsRequired:1];
  2138. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  2139. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  2140. // More
  2141. if ([self canOpenMenuAction:metadata]) {
  2142. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2143. [tapMore setNumberOfTapsRequired:1];
  2144. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2145. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2146. }
  2147. // MGSwipeButton
  2148. ((CCCellMain *)cell).delegate = self;
  2149. // LEFT
  2150. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  2151. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2152. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2153. //centerIconOverText
  2154. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2155. [favoriteButton centerIconOverText];
  2156. // RIGHT
  2157. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  2158. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2159. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2160. //centerIconOverText
  2161. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2162. [deleteButton centerIconOverText];
  2163. }
  2164. // TRANSFER
  2165. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2166. // gesture Transfer
  2167. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  2168. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  2169. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  2170. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  2171. }
  2172. return cell;
  2173. }
  2174. - (void)setTableViewHeader
  2175. {
  2176. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  2177. if (capabilities.versionMajor < k_nextcloud_version_18_0 || self.richWorkspaceText.length == 0 || self.searchController.isActive) {
  2178. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  2179. } else {
  2180. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  2181. }
  2182. self.searchController.searchBar.frame = self.viewRichWorkspace.searchViewHolder.frame;
  2183. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  2184. [self.tableView reloadData];
  2185. }
  2186. - (void)setTableViewFooter
  2187. {
  2188. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2189. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2190. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2191. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2192. UIFont *appFont = [UIFont systemFontOfSize:12];
  2193. footerLabel.font = appFont;
  2194. footerLabel.textColor = [UIColor grayColor];
  2195. footerLabel.backgroundColor = [UIColor clearColor];
  2196. footerLabel.textAlignment = NSTextAlignmentCenter;
  2197. NSString *folders;
  2198. NSString *files;
  2199. NSString *footerText;
  2200. if (sectionDataSource.directories > 1) {
  2201. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2202. } else if (sectionDataSource.directories == 1){
  2203. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2204. } else {
  2205. folders = @"";
  2206. }
  2207. if (sectionDataSource.files > 1) {
  2208. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2209. } else if (sectionDataSource.files == 1){
  2210. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2211. } else {
  2212. files = @"";
  2213. }
  2214. if ([folders isEqualToString:@""]) {
  2215. footerText = files;
  2216. } else if ([files isEqualToString:@""]) {
  2217. footerText = folders;
  2218. } else {
  2219. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2220. }
  2221. footerLabel.text = footerText;
  2222. [footerView addSubview:footerLabel];
  2223. [self.tableView setTableFooterView:footerView];
  2224. }
  2225. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2226. {
  2227. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2228. // settiamo il record file.
  2229. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2230. if (!self.metadata)
  2231. return;
  2232. // se non può essere selezionata deseleziona
  2233. if ([cell isEditing] == NO)
  2234. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2235. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2236. if (self.tableView.editing) {
  2237. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2238. [self setTitle];
  2239. return;
  2240. }
  2241. // se è in corso una sessione
  2242. if (self.metadata.status != k_metadataStatusNormal)
  2243. return;
  2244. // file
  2245. if (self.metadata.directory == NO) {
  2246. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2247. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2248. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  2249. } else {
  2250. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2251. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2252. } else {
  2253. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  2254. [self shouldPerformSegue:self.metadata selector:@""];
  2255. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2256. if (appDelegate.reachability.isReachable) {
  2257. [self shouldPerformSegue:self.metadata selector:@""];
  2258. } else {
  2259. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2260. }
  2261. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2262. if (appDelegate.reachability.isReachable) {
  2263. [self shouldPerformSegue:self.metadata selector:@""];
  2264. } else {
  2265. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2266. }
  2267. } else {
  2268. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  2269. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  2270. }
  2271. self.metadata.session = k_download_session;
  2272. self.metadata.sessionError = @"";
  2273. self.metadata.sessionSelector = selectorLoadFileView;
  2274. self.metadata.status = k_metadataStatusWaitDownload;
  2275. // Add Metadata for Download
  2276. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2277. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2278. [appDelegate startLoadAutoDownloadUpload];
  2279. }
  2280. }
  2281. }
  2282. }
  2283. if (self.metadata.directory) {
  2284. [self performSegueDirectoryWithControlPasscode:true metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2285. }
  2286. }
  2287. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  2288. {
  2289. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2290. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  2291. [self setTitle];
  2292. }
  2293. - (void)didSelectAll
  2294. {
  2295. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  2296. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  2297. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  2298. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2299. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  2300. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  2301. }
  2302. }
  2303. [self setTitle];
  2304. }
  2305. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  2306. {
  2307. if (!indexPath)
  2308. return NO;
  2309. NSInteger section = indexPath.section;
  2310. NSInteger row = indexPath.row;
  2311. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  2312. if (section > lastSectionIndex || lastSectionIndex < 0)
  2313. return NO;
  2314. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  2315. if (rowCount < 0)
  2316. return NO;
  2317. return row <= rowCount;
  2318. }
  2319. #pragma --------------------------------------------------------------------------------------------
  2320. #pragma mark ===== Navigation ====
  2321. #pragma --------------------------------------------------------------------------------------------
  2322. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  2323. {
  2324. // if background return
  2325. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  2326. if (self.view.window == NO)
  2327. return;
  2328. // Collapsed ma siamo già in detail esci
  2329. if (self.splitViewController.isCollapsed) {
  2330. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  2331. }
  2332. // Metadata for push detail
  2333. self.metadataForPushDetail = metadata;
  2334. self.selectorForPushDetail = selector;
  2335. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  2336. }
  2337. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  2338. {
  2339. tableMetadata *metadata;
  2340. NSMutableArray *photoDataSource = [NSMutableArray new];
  2341. UINavigationController *navigationController = segue.destinationViewController;
  2342. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  2343. if ([sender isKindOfClass:[tableMetadata class]]) {
  2344. metadata = sender;
  2345. [photoDataSource addObject:sender];
  2346. } else {
  2347. metadata = self.metadataForPushDetail;
  2348. for (NSString *ocId in sectionDataSource.allOcId) {
  2349. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2350. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  2351. [photoDataSource addObject:metadata];
  2352. }
  2353. }
  2354. detailViewController.metadata = metadata;
  2355. detailViewController.selector = self.selectorForPushDetail;
  2356. [detailViewController setTitle:metadata.fileNameView];
  2357. }
  2358. // can i go to next viewcontroller
  2359. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode metadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  2360. {
  2361. NSString *nomeDir;
  2362. if (self.tableView.editing == NO) {
  2363. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  2364. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadata.account, lockServerUrl]];
  2365. // 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
  2366. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  2367. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2368. viewController.delegate = self;
  2369. viewController.fromType = CCBKPasscodeFromLockDirectory;
  2370. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2371. viewController.inputViewTitlePassword = YES;
  2372. if ([CCUtility getSimplyBlockCode]) {
  2373. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2374. viewController.passcodeInputView.maximumLength = 6;
  2375. } else {
  2376. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2377. viewController.passcodeInputView.maximumLength = 64;
  2378. }
  2379. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2380. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2381. viewController.touchIDManager = touchIDManager;
  2382. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  2383. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2384. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2385. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2386. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  2387. [self presentViewController:navigationController animated:YES completion:nil];
  2388. return;
  2389. }
  2390. // E2EE Check enable
  2391. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  2392. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2393. return;
  2394. }
  2395. nomeDir = metadata.fileName;
  2396. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  2397. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  2398. if (!viewController) {
  2399. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  2400. viewController.serverUrl = serverUrlPush;
  2401. viewController.titleMain = metadata.fileNameView;
  2402. viewController.blinkFileNamePath = blinkFileNamePath;
  2403. // save self
  2404. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  2405. [self.navigationController pushViewController:viewController animated:YES];
  2406. } else {
  2407. if (viewController.isViewLoaded) {
  2408. viewController.titleMain = metadata.fileNameView;
  2409. viewController.blinkFileNamePath = blinkFileNamePath;
  2410. // Fix : Application tried to present modally an active controller
  2411. if ([self.navigationController isBeingPresented]) {
  2412. // being presented
  2413. } else if ([self.navigationController isMovingToParentViewController]) {
  2414. // being pushed
  2415. } else {
  2416. [self.navigationController pushViewController:viewController animated:YES];
  2417. }
  2418. }
  2419. }
  2420. }
  2421. }
  2422. @end