CCMain.m 140 KB

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