CCMain.m 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702
  1. //
  2. // CCMain.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 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 "NCAutoUpload.h"
  26. #import "NCBridgeSwift.h"
  27. #import "PKDownloadButton.h"
  28. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, NCSelectDelegate, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. BOOL _isRoot;
  32. BOOL _isViewDidLoad;
  33. NSMutableDictionary *_selectedocIdsMetadatas;
  34. UIImageView *_imageTitleHome;
  35. NSUInteger _failedAttempts;
  36. NSDate *_lockUntilDate;
  37. UIRefreshControl *refreshControl;
  38. CCHud *_hud;
  39. // Datasource
  40. CCSectionDataSourceMetadata *sectionDataSource;
  41. // Search
  42. NSString *_searchFileName;
  43. NSMutableArray *_searchResultMetadatas;
  44. NSString *_noFilesSearchTitle;
  45. NSString *_noFilesSearchDescription;
  46. NSTimer *_timerWaitInput;
  47. // Automatic Upload Folder
  48. NSString *_autoUploadFileName;
  49. NSString *_autoUploadDirectory;
  50. // Folder
  51. BOOL _loadingFolder;
  52. tableMetadata *_metadataFolder;
  53. CGFloat heightRichWorkspace;
  54. CGFloat heightSearchBar;
  55. //
  56. NSMutableArray *arrayDeleteMetadata;
  57. NSMutableArray *arrayMoveMetadata;
  58. NSMutableArray *arrayMoveServerUrlTo;
  59. NSMutableArray *arrayCopyMetadata;
  60. NSMutableArray *arrayCopyServerUrlTo;
  61. BOOL livePhoto;
  62. }
  63. @end
  64. @implementation CCMain
  65. #pragma --------------------------------------------------------------------------------------------
  66. #pragma mark ===== Init =====
  67. #pragma --------------------------------------------------------------------------------------------
  68. - (id)initWithCoder:(NSCoder *)aDecoder
  69. {
  70. if (self = [super initWithCoder:aDecoder]) {
  71. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  72. appDelegate.activeMain = self;
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  74. }
  75. return self;
  76. }
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== View =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (void)viewDidLoad
  81. {
  82. [super viewDidLoad];
  83. // init object
  84. self.metadata = [tableMetadata new];
  85. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  86. _selectedocIdsMetadatas = [NSMutableDictionary new];
  87. _isViewDidLoad = YES;
  88. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  89. _searchResultMetadatas = [NSMutableArray new];
  90. _searchFileName = @"";
  91. _noFilesSearchTitle = @"";
  92. _noFilesSearchDescription = @"";
  93. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  94. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  95. arrayDeleteMetadata = [NSMutableArray new];
  96. arrayMoveMetadata = [NSMutableArray new];
  97. arrayMoveServerUrlTo = [NSMutableArray new];
  98. arrayCopyMetadata = [NSMutableArray new];
  99. arrayCopyServerUrlTo = [NSMutableArray new];
  100. // delegate
  101. self.tableView.tableFooterView = [UIView new];
  102. self.tableView.emptyDataSetDelegate = self;
  103. self.tableView.emptyDataSetSource = self;
  104. self.searchController.delegate = self;
  105. self.searchController.searchBar.delegate = self;
  106. // Notification
  107. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasource:) name:k_notificationCenter_reloadDataSource object:nil];
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:k_notificationCenter_setTitleMain object:nil];
  109. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:k_notificationCenter_changeTheming object:nil];
  110. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  111. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(favoriteFile:) name:k_notificationCenter_favoriteFile object:nil];
  112. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  113. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  114. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createFolder:) name:k_notificationCenter_createFolder object:nil];
  115. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_renameFile object:nil];
  116. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_downloadStartFile object:nil];
  117. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_downloadedFile object:nil];
  118. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_downloadCancelFile object:nil];
  119. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_uploadStartFile object:nil];
  120. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_uploadedFile object:nil];
  121. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_uploadCancelFile object:nil];
  122. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:k_notificationCenter_progressTask object:nil];
  123. // Search
  124. self.definesPresentationContext = YES;
  125. self.searchController.searchResultsUpdater = self;
  126. self.searchController.dimsBackgroundDuringPresentation = NO;
  127. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  128. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  129. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  130. }
  131. UITextField *searchTextField = [self.searchController.searchBar valueForKey:@"searchField"];
  132. if (searchTextField && [searchTextField isKindOfClass:[UITextField class]]) {
  133. searchTextField.textColor = NCBrandColor.sharedInstance.textView;
  134. }
  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.richView addGestureRecognizer:viewRichWorkspaceTapped];
  141. self.sortButton = self.viewRichWorkspace.sortButton;
  142. heightSearchBar = self.viewRichWorkspace.topView.frame.size.height;
  143. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  144. [self.sortButton addTarget:self action:@selector(toggleSortMenu) forControlEvents:UIControlEventTouchUpInside];
  145. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height / 4 + heightSearchBar;
  146. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  147. self.navigationItem.searchController = self.searchController;
  148. self.searchController.hidesNavigationBarDuringPresentation = true;
  149. self.navigationController.navigationBar.prefersLargeTitles = true;
  150. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  151. // Table Header View
  152. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  153. // Register cell
  154. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  155. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  156. self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 35, 0);
  157. // long press recognizer TableView
  158. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  159. [self.tableView addGestureRecognizer:longPressRecognizer];
  160. // Pull-to-Refresh
  161. [self createRefreshControl];
  162. // Register for 3D Touch Previewing if available
  163. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  164. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  165. }
  166. // if this is not Main (the Main uses inizializeMain)
  167. if (_isRoot == NO && appDelegate.account.length > 0) {
  168. // Read (File) Folder
  169. [self readFileReloadFolder];
  170. }
  171. // Title
  172. [self setTitle];
  173. // changeTheming
  174. [self changeTheming];
  175. }
  176. - (void)willDismissSearchController:(UISearchController *)searchController
  177. {
  178. [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
  179. }
  180. - (void)willPresentSearchController:(UISearchController *)searchController
  181. {
  182. [self updateNavBarShadow:self.tableView force:true];
  183. }
  184. - (void)viewWillAppear:(BOOL)animated
  185. {
  186. [super viewWillAppear:animated];
  187. [self updateNavBarShadow:self.tableView force:false];
  188. if(_isViewDidLoad && _isRoot) {
  189. self.navigationItem.hidesSearchBarWhenScrolling = false;
  190. [self.navigationController.navigationBar sizeToFit];
  191. }
  192. // test
  193. if (appDelegate.account.length == 0)
  194. return;
  195. if (_isSelectedMode)
  196. [self setUINavigationBarSelected];
  197. else
  198. [self setUINavigationBarDefault];
  199. // If not editing mode remove _selectedocIds
  200. if (!self.tableView.editing)
  201. [_selectedocIdsMetadatas removeAllObjects];
  202. // Check server URL "/"
  203. if (self.navigationController.viewControllers.firstObject == self && self.serverUrl == nil) {
  204. self.serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  205. }
  206. // RichWorkspace
  207. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, self.serverUrl]];
  208. if (![self.richWorkspaceText isEqualToString:directory.richWorkspace]) {
  209. self.richWorkspaceText = directory.richWorkspace;
  210. [self setTableViewHeader];
  211. }
  212. // Query data source
  213. if (self.searchController.isActive == false) {
  214. [self reloadDatasource:self.serverUrl ocId:nil];
  215. }
  216. }
  217. - (void)viewDidAppear:(BOOL)animated
  218. {
  219. [super viewDidAppear:animated];
  220. if(_isViewDidLoad && _isRoot) {
  221. self.navigationItem.hidesSearchBarWhenScrolling = true;
  222. }
  223. // Active Main
  224. appDelegate.activeMain = self;
  225. // Test viewDidLoad
  226. if (_isViewDidLoad) {
  227. _isViewDidLoad = NO;
  228. } else {
  229. if (appDelegate.account.length > 0 && [_selectedocIdsMetadatas count] == 0) {
  230. // Read (file) Folder
  231. [self readFileReloadFolder];
  232. }
  233. }
  234. // Title
  235. [self setTitle];
  236. }
  237. - (void)viewWillDisappear:(BOOL)animated
  238. {
  239. [super viewWillDisappear:animated];
  240. }
  241. - (void) viewDidLayoutSubviews
  242. {
  243. [super viewDidLayoutSubviews];
  244. [self setTableViewHeader];
  245. }
  246. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  247. {
  248. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  249. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  250. [self.tableView beginUpdates];
  251. [self.tableView endUpdates];
  252. [self setTableViewHeader];
  253. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context){
  254. [self updateNavBarShadow:self.tableView force:false];
  255. }];
  256. }
  257. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  258. {
  259. [self viewDidAppear:true];
  260. }
  261. - (BOOL)prefersStatusBarHidden
  262. {
  263. return NO;
  264. }
  265. // detect scroll for remove keyboard in search mode
  266. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  267. {
  268. if (self.searchController.isActive && scrollView == self.tableView) {
  269. [self.searchController.searchBar endEditing:YES];
  270. }
  271. }
  272. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  273. [self updateNavBarShadow:self.tableView force:false];
  274. }
  275. - (void)changeTheming
  276. {
  277. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  278. // Refresh control
  279. refreshControl.tintColor = UIColor.lightGrayColor;
  280. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  281. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  282. // color searchbar
  283. self.searchController.searchBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  284. // color searchbbar button text (cancel)
  285. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  286. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  287. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  288. }
  289. // color textview searchbbar
  290. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  291. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  292. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  293. }
  294. // Rich Workspace
  295. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  296. // Title
  297. [self setTitle];
  298. // Reload Table View
  299. [self tableViewReloadData];
  300. }
  301. #pragma --------------------------------------------------------------------------------------------
  302. #pragma mark ===== Initialization =====
  303. #pragma --------------------------------------------------------------------------------------------
  304. //
  305. // Callers :
  306. //
  307. // ChangeDefaultAccount (delegate)
  308. // Split : inizialize
  309. // Settings Advanced : removeAllFiles
  310. //
  311. - (void)initializeMain:(NSNotification *)notification
  312. {
  313. // test
  314. if (appDelegate.account.length == 0)
  315. return;
  316. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  317. // This is Root home main add list
  318. appDelegate.homeMain = self;
  319. _isRoot = YES;
  320. _serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  321. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  322. // go Home
  323. [self.navigationController popToRootViewControllerAnimated:NO];
  324. // Remove search mode
  325. [self cancelSearchBar];
  326. // Clear error certificate
  327. [CCUtility setCertificateError:appDelegate.account error:NO];
  328. // Setting Theming
  329. [appDelegate settingThemingColorBrand];
  330. // Detail
  331. // If AVPlayer in play -> Stop
  332. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  333. [appDelegate.player pause];
  334. }
  335. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  336. // Not Photos Video in library ? then align and Init Auto Upload
  337. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.account]];
  338. if ([recordsPhotoLibrary count] == 0) {
  339. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  340. }
  341. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  342. [[NCCommunicationCommon shared] writeLog:@"Request Service Server Nextcloud"];
  343. [[NCService shared] startRequestServicesServer];
  344. // Read this folder
  345. [self readFileReloadFolder];
  346. } else {
  347. // reload datasource
  348. [self reloadDatasource:_serverUrl ocId:nil];
  349. }
  350. // Registeration push notification
  351. [appDelegate pushNotification];
  352. // Registeration domain File Provider
  353. if (k_fileProvider_domain) {
  354. [FileProviderDomain.sharedInstance registerDomain];
  355. } else {
  356. [FileProviderDomain.sharedInstance removeAllDomain];
  357. }
  358. }
  359. #pragma --------------------------------------------------------------------------------------------
  360. #pragma mark ==== NotificationCenter ====
  361. #pragma --------------------------------------------------------------------------------------------
  362. - (void)createFolder:(NSNotification *)notification
  363. {
  364. NSDictionary *userInfo = notification.userInfo;
  365. tableMetadata *metadata = userInfo[@"metadata"];
  366. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  367. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:nil account:appDelegate.account urlBase: appDelegate.urlBase];
  368. if (isFolderEncrypted) {
  369. [self readFolder:metadata.serverUrl];
  370. } else {
  371. [self reloadDatasource:self.serverUrl ocId:nil];
  372. }
  373. }
  374. - (void)deleteFile:(NSNotification *)notification
  375. {
  376. NSDictionary *userInfo = notification.userInfo;
  377. tableMetadata *metadata = userInfo[@"metadata"];
  378. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  379. NSString *errorDescription = userInfo[@"errorDescription"];
  380. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  381. if (arrayDeleteMetadata.count > 0) {
  382. tableMetadata *metadata = arrayDeleteMetadata.firstObject;
  383. [arrayDeleteMetadata removeObjectAtIndex:0];
  384. [[NCNetworking shared] deleteMetadata:metadata account:metadata.account urlBase:metadata.urlBase onlyLocal:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  385. }
  386. if (errorCode == 0 ) {
  387. if ([metadata.fileNameView.lowercaseString isEqualToString:k_fileNameRichWorkspace.lowercaseString]) {
  388. [self readFileReloadFolder];
  389. } else {
  390. if (self.searchController.isActive) {
  391. [self readFolder:self.serverUrl];
  392. }
  393. }
  394. }
  395. if (errorCode != 0 && self.view.window != nil) {
  396. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  397. }
  398. [self reloadDatasource:self.serverUrl ocId:nil];
  399. }
  400. - (void)moveFile:(NSNotification *)notification
  401. {
  402. NSDictionary *userInfo = notification.userInfo;
  403. tableMetadata *metadata = userInfo[@"metadata"];
  404. // tableMetadata *metadataNew = userInfo[@"metadataNew"];
  405. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  406. NSString *errorDescription = userInfo[@"errorDescription"];
  407. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  408. if (arrayMoveMetadata.count > 0) {
  409. tableMetadata *metadata = arrayMoveMetadata.firstObject;
  410. NSString *serverUrlTo = arrayMoveServerUrlTo.firstObject;
  411. [arrayMoveMetadata removeObjectAtIndex:0];
  412. [arrayMoveServerUrlTo removeObjectAtIndex:0];
  413. [[NCNetworking shared] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  414. }
  415. if (errorCode != 0 && self.view.window != nil) {
  416. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  417. }
  418. [self reloadDatasource:self.serverUrl ocId:nil];
  419. }
  420. - (void)copyFile:(NSNotification *)notification
  421. {
  422. NSDictionary *userInfo = notification.userInfo;
  423. tableMetadata *metadata = userInfo[@"metadata"];
  424. // NSString *serverUrlTo = userInfo[@"serverUrlTo"];
  425. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  426. NSString *errorDescription = userInfo[@"errorDescription"];
  427. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  428. if (arrayCopyMetadata.count > 0) {
  429. tableMetadata *metadata = arrayCopyMetadata.firstObject;
  430. NSString *serverUrlTo = arrayCopyServerUrlTo.firstObject;
  431. [arrayCopyMetadata removeObjectAtIndex:0];
  432. [arrayCopyServerUrlTo removeObjectAtIndex:0];
  433. [[NCNetworking shared] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  434. }
  435. if (errorCode != 0 && self.view.window != nil) {
  436. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  437. }
  438. }
  439. - (void)favoriteFile:(NSNotification *)notification
  440. {
  441. if (self.view.window == nil) { return; }
  442. NSDictionary *userInfo = notification.userInfo;
  443. tableMetadata *metadata = userInfo[@"metadata"];
  444. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  445. NSString *errorDescription = userInfo[@"errorDescription"];
  446. BOOL favorite = [userInfo[@"favorite"] boolValue];
  447. if (errorCode == 0) {
  448. if (self.searchController.isActive) {
  449. [self readFolder:self.serverUrl];
  450. }
  451. if (favorite) {
  452. if ([CCUtility getFavoriteOffline]) {
  453. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadAllFile];
  454. } else {
  455. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorReadFile];
  456. }
  457. }
  458. } else {
  459. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  460. }
  461. [self reloadDatasource:self.serverUrl ocId:nil];
  462. }
  463. #pragma --------------------------------------------------------------------------------------------
  464. #pragma mark ==== DZNEmptyDataSetSource ====
  465. #pragma --------------------------------------------------------------------------------------------
  466. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  467. {
  468. if (_loadingFolder)
  469. return NO;
  470. else
  471. return YES;
  472. }
  473. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  474. {
  475. CGFloat height = self.tabBarController.tabBar.frame.size.height;
  476. return -height;
  477. }
  478. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  479. {
  480. return NCBrandColor.sharedInstance.backgroundView;
  481. }
  482. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  483. {
  484. if (self.searchController.isActive)
  485. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  486. else
  487. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  488. }
  489. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  490. {
  491. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  492. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  493. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  494. activityView.color = NCBrandColor.sharedInstance.brandElement;
  495. [activityView startAnimating];
  496. return activityView;
  497. }
  498. return nil;
  499. }
  500. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  501. {
  502. NSString *text;
  503. if (self.searchController.isActive) {
  504. text = _noFilesSearchTitle;
  505. } else {
  506. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  507. }
  508. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  509. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  510. }
  511. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  512. {
  513. NSString *text;
  514. if (self.searchController.isActive) {
  515. text = _noFilesSearchDescription;
  516. } else {
  517. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  518. }
  519. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  520. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  521. paragraph.alignment = NSTextAlignmentCenter;
  522. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  523. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  524. }
  525. #pragma --------------------------------------------------------------------------------------------
  526. #pragma mark ===== Text Field =====
  527. #pragma --------------------------------------------------------------------------------------------
  528. - (void)minCharTextFieldDidChange:(UITextField *)sender
  529. {
  530. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  531. if (alertController)
  532. {
  533. UITextField *fileName = alertController.textFields.firstObject;
  534. UIAlertAction *okAction = alertController.actions.lastObject;
  535. okAction.enabled = fileName.text.length > 0;
  536. }
  537. }
  538. - (void)textFieldDidBeginEditing:(UITextField *)textField
  539. {
  540. [CCUtility selectFileNameFrom:textField];
  541. }
  542. #pragma --------------------------------------------------------------------------------------------
  543. #pragma mark ===== Graphic Window =====
  544. #pragma --------------------------------------------------------------------------------------------
  545. - (void)createRefreshControl
  546. {
  547. refreshControl = [NCMainRefreshControl new];
  548. self.tableView.refreshControl = refreshControl;
  549. refreshControl.tintColor = UIColor.lightGrayColor;
  550. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  551. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  552. }
  553. - (void)deleteRefreshControl
  554. {
  555. [refreshControl endRefreshing];
  556. [refreshControl removeFromSuperview];
  557. refreshControl = nil;
  558. }
  559. - (void)refreshControlTarget
  560. {
  561. [self readFolder:_serverUrl];
  562. // Actuate `Peek` feedback (weak boom)
  563. AudioServicesPlaySystemSound(1519);
  564. }
  565. - (void)setTitle
  566. {
  567. if (_isSelectedMode) {
  568. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  569. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  570. self.navigationItem.titleView = nil;
  571. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  572. } else {
  573. if (_isRoot) {
  574. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  575. } else {
  576. self.navigationItem.title = _titleMain;
  577. }
  578. }
  579. NSString *titleButtonMenuSort = [[NCUtility shared] getTitleButtonForViewWithKey:k_layout_view_main];
  580. [self.sortButton setTitle:NSLocalizedString(titleButtonMenuSort, nil) forState:UIControlStateNormal];
  581. }
  582. - (void)setUINavigationBarDefault
  583. {
  584. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  585. self.navigationController.navigationBar.hidden = NO;
  586. self.navigationItem.rightBarButtonItem = buttonSelect;
  587. self.navigationItem.leftBarButtonItem = nil;
  588. }
  589. - (void)setUINavigationBarSelected
  590. {
  591. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleSelectMenu)];
  592. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  593. self.navigationItem.leftBarButtonItem = leftButton;
  594. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  595. }
  596. - (void)cancelSelect
  597. {
  598. [self tableViewSelect:false];
  599. }
  600. #pragma --------------------------------------------------------------------------------------------
  601. #pragma mark ===== Document Picker =====
  602. #pragma --------------------------------------------------------------------------------------------
  603. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  604. {
  605. }
  606. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  607. {
  608. }
  609. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  610. {
  611. documentPicker.delegate = self;
  612. [self presentViewController:documentPicker animated:YES completion:nil];
  613. }
  614. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  615. {
  616. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  617. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  618. __block NSError *error;
  619. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  620. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  621. NSString *fileName = [url lastPathComponent];
  622. NSString *ocId = [[NSUUID UUID] UUIDString];
  623. NSData *data = [NSData dataWithContentsOfURL:newURL];
  624. if (data && error == nil) {
  625. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  626. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  627. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground;
  628. metadataForUpload.sessionSelector = selectorUploadFile;
  629. metadataForUpload.size = data.length;
  630. metadataForUpload.status = k_metadataStatusWaitUpload;
  631. if ([[NCUtility shared] getMetadataConflictWithAccount:appDelegate.account serverUrl:serverUrl fileName:fileName] != nil) {
  632. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  633. conflict.serverUrl = self.serverUrl;
  634. conflict.metadatasUploadInConflict = @[metadataForUpload];
  635. [self presentViewController:conflict animated:YES completion:nil];
  636. } else {
  637. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  638. [[appDelegate networkingAutoUpload] startProcess];
  639. }
  640. } else {
  641. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  642. }
  643. } else {
  644. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  645. }
  646. }];
  647. }
  648. }
  649. - (void)openImportDocumentPicker
  650. {
  651. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  652. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  653. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  654. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  655. documentProviderMenu.delegate = self;
  656. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  657. }
  658. #pragma --------------------------------------------------------------------------------------------
  659. #pragma mark ===== Assets Picker =====
  660. #pragma --------------------------------------------------------------------------------------------
  661. -(void)dismissFormUploadAssets
  662. {
  663. }
  664. - (void)openAssetsPickerController
  665. {
  666. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  667. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets) {
  668. if (assets.count > 0) {
  669. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  670. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  671. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets cryptated:NO session:NCNetworking.shared.sessionIdentifierBackground delegate:self];
  672. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  673. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  674. [self presentViewController:navigationController animated:YES completion:nil];
  675. });
  676. }
  677. }];
  678. }
  679. #pragma --------------------------------------------------------------------------------------------
  680. #pragma mark ===== Save selected File =====
  681. #pragma --------------------------------------------------------------------------------------------
  682. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  683. {
  684. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  685. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  686. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  687. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  688. if (image)
  689. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  690. else
  691. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  692. }
  693. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  694. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  695. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  696. } else {
  697. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  698. }
  699. }
  700. if (status != PHAuthorizationStatusAuthorized) {
  701. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  702. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  703. [alertController addAction:okAction];
  704. [self presentViewController:alertController animated:YES completion:nil];
  705. }
  706. }
  707. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  708. {
  709. if (error) {
  710. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  711. }
  712. }
  713. - (void)saveSelectedFiles
  714. {
  715. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  716. return;
  717. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  718. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  719. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  720. for (tableMetadata *metadata in metadatas) {
  721. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  722. [[NCOperationQueue shared] downloadWithMetadata:metadata selector:selectorSaveAlbum setFavorite:false];
  723. }
  724. }
  725. [_hud hideHud];
  726. });
  727. [self tableViewSelect:false];
  728. }
  729. #pragma mark -
  730. #pragma --------------------------------------------------------------------------------------------
  731. #pragma mark ===== Peek & Pop =====
  732. #pragma --------------------------------------------------------------------------------------------
  733. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  734. {
  735. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  736. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  737. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  738. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  739. if (cell) {
  740. previewingContext.sourceRect = cell.frame;
  741. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  742. viewController.metadata = metadata;
  743. viewController.imageFile = cell.file.image;
  744. viewController.showOpenIn = true;
  745. viewController.showShare = true;
  746. viewController.showOpenQuickLook = [[NCUtility shared] isQuickLookDisplayableWithMetadata:metadata];
  747. return viewController;
  748. }
  749. return nil;
  750. }
  751. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  752. {
  753. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  754. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  755. }
  756. #pragma --------------------------------------------------------------------------------------------
  757. #pragma mark ==== Download ====
  758. #pragma --------------------------------------------------------------------------------------------
  759. - (void)downloadSelectedFilesFolders
  760. {
  761. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  762. return;
  763. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  764. for (tableMetadata *metadata in selectedMetadatas) {
  765. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadFile];
  766. }
  767. [self tableViewSelect:false];
  768. }
  769. #pragma --------------------------------------------------------------------------------------------
  770. #pragma mark ===== Upload new Photos/Videos =====
  771. #pragma --------------------------------------------------------------------------------------------
  772. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  773. {
  774. // if request create the folder for Auto Upload & the subfolders
  775. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  776. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPathWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  777. if ([autoUploadPath isEqualToString:serverUrl]) {
  778. if ([[NCNetworking shared] createFoloderWithAssets:(PHFetchResult *)assets selector:selectorUploadFile useSubFolder:useSubFolder account:appDelegate.account urlBase:appDelegate.urlBase]) {
  779. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError forced:true];
  780. return;
  781. }
  782. }
  783. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  784. });
  785. }
  786. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  787. {
  788. NSMutableArray *metadatasNOConflict = [NSMutableArray new];
  789. NSMutableArray *metadatasMOV = [NSMutableArray new];
  790. NSMutableArray *metadatasUploadInConflict = [NSMutableArray new];
  791. for (PHAsset *asset in assets) {
  792. BOOL livePhoto = false;
  793. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  794. NSDate *assetDate = asset.creationDate;
  795. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  796. // Detect LivePhoto Upload
  797. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto) {
  798. livePhoto = true;
  799. }
  800. // Create serverUrl if use sub folder
  801. if (useSubFolder) {
  802. [formatter setDateFormat:@"yyyy"];
  803. NSString *yearString = [formatter stringFromDate:assetDate];
  804. [formatter setDateFormat:@"MM"];
  805. NSString *monthString = [formatter stringFromDate:assetDate];
  806. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  807. }
  808. // Check if is in upload
  809. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.account, serverUrl, fileName] page:0 limit:0 sorted:@"fileName" ascending:NO];
  810. if ([isRecordInSessions count] > 0)
  811. continue;
  812. // Prepare record metadata
  813. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  814. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  815. metadataForUpload.session = session;
  816. metadataForUpload.sessionSelector = selectorUploadFile;
  817. metadataForUpload.size = [[NCUtilityFileSystem shared] getFileSizeWithAsset:asset];
  818. metadataForUpload.status = k_metadataStatusWaitUpload;
  819. // Add Medtadata MOV LIVE PHOTO for upload
  820. if (livePhoto) {
  821. NSString *fileNameMove = [NSString stringWithFormat:@"%@.mov", fileName.stringByDeletingPathExtension];
  822. NSString *ocId = [[NSUUID UUID] UUIDString];
  823. NSString *filePath = [CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameMove];
  824. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  825. [CCUtility extractLivePhotoAsset:asset filePath:filePath withCompletion:^(NSURL *url) {
  826. if (url != nil) {
  827. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  828. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileNameMove ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  829. metadataForUpload.livePhoto = true;
  830. metadataMOVForUpload.livePhoto = true;
  831. metadataMOVForUpload.session = session;
  832. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  833. metadataMOVForUpload.size = fileSize;
  834. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  835. metadataMOVForUpload.typeFile = k_metadataTypeFile_video;
  836. [metadatasMOV addObject:metadataMOVForUpload];
  837. }
  838. dispatch_semaphore_signal(semaphore);
  839. }];
  840. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER))
  841. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:30]];
  842. }
  843. if ([[NCUtility shared] getMetadataConflictWithAccount:appDelegate.account serverUrl:serverUrl fileName:fileName] != nil) {
  844. [metadatasUploadInConflict addObject:metadataForUpload];
  845. } else {
  846. [metadatasNOConflict addObject:metadataForUpload];
  847. }
  848. }
  849. dispatch_async(dispatch_get_main_queue(), ^{
  850. // Verify if file(s) exists
  851. if (metadatasUploadInConflict.count > 0) {
  852. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  853. conflict.serverUrl = self.serverUrl;
  854. conflict.metadatasNOConflict = metadatasNOConflict;
  855. conflict.metadatasMOV = metadatasMOV;
  856. conflict.metadatasUploadInConflict = metadatasUploadInConflict;
  857. [self presentViewController:conflict animated:YES completion:nil];
  858. } else {
  859. [[NCManageDatabase sharedInstance] addMetadatas:metadatasNOConflict];
  860. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  861. [[appDelegate networkingAutoUpload] startProcess];
  862. }
  863. });
  864. }
  865. #pragma --------------------------------------------------------------------------------------------
  866. #pragma mark ==== Read Folder ====
  867. #pragma --------------------------------------------------------------------------------------------
  868. - (void)readFolder:(NSString *)serverUrl
  869. {
  870. // init control
  871. if (!serverUrl || !appDelegate.account || appDelegate.maintenanceMode) {
  872. [refreshControl endRefreshing];
  873. return;
  874. }
  875. // Search Mode
  876. if (self.searchController.isActive) {
  877. _searchFileName = @""; // forced reload searchg
  878. [self updateSearchResultsForSearchController:self.searchController];
  879. return;
  880. }
  881. _loadingFolder = YES;
  882. [refreshControl endRefreshing];
  883. [self tableViewReloadData];
  884. [[NCNetworking shared] readFolderWithServerUrl:serverUrl account:appDelegate.account completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSArray *metadatasUpdate, NSArray *metadatasLocalUpdate, NSInteger errorCode, NSString *errorDescription) {
  885. if (errorCode == 0 ) {
  886. _metadataFolder = metadataFolder;
  887. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.account urlBase:_metadataFolder.urlBase];
  888. [self setTitle];
  889. for (tableMetadata *metadata in metadatasLocalUpdate) {
  890. if (!metadata.directory) {
  891. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorDownloadFile setFavorite:false completion:^(NSInteger errorCode) { }];
  892. }
  893. }
  894. // E2EE Is encrypted folder get metadata
  895. if (isFolderEncrypted) {
  896. if ([CCUtility isEndToEndEnabled:account]) {
  897. [[NCCommunication shared] getE2EEMetadataWithFileId:metadataFolder.fileId e2eToken:nil customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *e2eMetadata, NSInteger errorCode, NSString *errorDescription) {
  898. if (errorCode == 0 && e2eMetadata != nil) {
  899. BOOL result = [[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eMetadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account urlBase:appDelegate.urlBase];
  900. if (result == false) {
  901. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorDecodeMetadata forced:true];
  902. }
  903. } else if (errorCode != 404) {
  904. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  905. }
  906. [self reloadDatasource:_serverUrl ocId:nil];
  907. }];
  908. } else {
  909. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  910. }
  911. }
  912. } else {
  913. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  914. }
  915. _loadingFolder = NO;
  916. [self reloadDatasource:serverUrl ocId:nil];
  917. }];
  918. }
  919. - (void)readFileReloadFolder
  920. {
  921. if (!_serverUrl || !appDelegate.account || appDelegate.maintenanceMode)
  922. return;
  923. [[NCNetworking shared] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.account completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  924. if (errorCode == 0 && [account isEqualToString:appDelegate.account]) {
  925. // Rich Workspace
  926. [[NCManageDatabase sharedInstance] setDirectoryWithRichWorkspace:metadata.richWorkspace serverUrl:self.serverUrl account:appDelegate.account];
  927. if (![self.richWorkspaceText isEqualToString:metadata.richWorkspace]) {
  928. self.richWorkspaceText = metadata.richWorkspace;
  929. }
  930. [self setTableViewHeader];
  931. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  932. // Read folder: No record, Change etag or BLINK
  933. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  934. [self readFolder:self.serverUrl];
  935. }
  936. } else if (errorCode != 0) {
  937. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  938. }
  939. }];
  940. }
  941. #pragma mark -
  942. #pragma --------------------------------------------------------------------------------------------
  943. #pragma mark ===== Search =====
  944. #pragma --------------------------------------------------------------------------------------------
  945. - (void)searchStartTimer
  946. {
  947. if (self.searchController.isActive == false) {
  948. return;
  949. }
  950. [[NCCommunication shared] searchLiteralWithServerUrl:appDelegate.urlBase depth:@"infinity" literal:_searchFileName showHiddenFiles:[CCUtility getShowHiddenFiles] customUserAgent:nil addCustomHeaders:nil user:appDelegate.user timeout:120 completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *errorDescription) {
  951. if (errorCode == 0 && [account isEqualToString:appDelegate.account] && files != nil) {
  952. [[NCManageDatabase sharedInstance] convertNCCommunicationFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  953. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  954. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  955. _metadataFolder = nil;
  956. [self reloadDatasource:_serverUrl ocId:nil];
  957. [self tableViewReloadData];
  958. [self setTitle];
  959. }];
  960. } else {
  961. if (errorCode != 0) {
  962. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  963. }
  964. _searchFileName = @"";
  965. [self cancelSearchBar];
  966. }
  967. }];
  968. _noFilesSearchTitle = @"";
  969. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  970. [self.tableView reloadEmptyDataSet];
  971. }
  972. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  973. {
  974. // Color text "Cancel"
  975. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandElement];
  976. if (searchController.isActive) {
  977. [self deleteRefreshControl];
  978. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  979. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  980. _searchFileName = fileName;
  981. _metadataFolder = nil;
  982. // First : filter
  983. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.account, _serverUrl, fileName] page:0 limit:0 sorted:@"fileName" ascending:NO];
  984. [_searchResultMetadatas removeAllObjects];
  985. for (tableMetadata *record in records) {
  986. [_searchResultMetadatas addObject:record];
  987. }
  988. // Version >= 12
  989. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  990. if (serverVersionMajor >= 12) {
  991. [_timerWaitInput invalidate];
  992. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  993. }
  994. [self setTitle];
  995. }
  996. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  997. [self reloadDatasource:_serverUrl ocId:nil];
  998. }
  999. } else {
  1000. [self createRefreshControl];
  1001. [self reloadDatasource:_serverUrl ocId:nil];
  1002. }
  1003. }
  1004. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1005. {
  1006. [self cancelSearchBar];
  1007. }
  1008. - (void)cancelSearchBar
  1009. {
  1010. if (self.searchController.active) {
  1011. [self.searchController setActive:NO];
  1012. _searchFileName = @"";
  1013. _searchResultMetadatas = [NSMutableArray new];
  1014. [self reloadDatasource:_serverUrl ocId:nil];
  1015. }
  1016. }
  1017. #pragma mark -
  1018. #pragma --------------------------------------------------------------------------------------------
  1019. #pragma mark ===== Delete File or Folder =====
  1020. #pragma --------------------------------------------------------------------------------------------
  1021. - (void)deleteMetadatas
  1022. {
  1023. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1024. return;
  1025. if ([_selectedocIdsMetadatas count] > 0) {
  1026. [arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1027. } else {
  1028. [arrayDeleteMetadata addObject:self.metadata];
  1029. }
  1030. [[NCNetworking shared] deleteMetadata:arrayDeleteMetadata.firstObject account:appDelegate.account urlBase:appDelegate.urlBase onlyLocal:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1031. [arrayDeleteMetadata removeObjectAtIndex:0];
  1032. // End Select Table View
  1033. [self tableViewSelect:false];
  1034. }
  1035. #pragma --------------------------------------------------------------------------------------------
  1036. #pragma mark ===== Move / Copy =====
  1037. #pragma --------------------------------------------------------------------------------------------
  1038. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1039. {
  1040. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1041. return;
  1042. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1043. if (move) {
  1044. arrayMetadata = arrayMoveMetadata;
  1045. arrayServerUrlTo = arrayMoveServerUrlTo;
  1046. } else {
  1047. arrayMetadata = arrayCopyMetadata;
  1048. arrayServerUrlTo = arrayCopyServerUrlTo;
  1049. }
  1050. if ([_selectedocIdsMetadatas count] > 0) {
  1051. for (NSString *key in _selectedocIdsMetadatas) {
  1052. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1053. [arrayMetadata addObject:metadata];
  1054. [arrayServerUrlTo addObject:serverUrlTo];
  1055. }
  1056. } else {
  1057. [arrayMetadata addObject:metadata];
  1058. [arrayServerUrlTo addObject:serverUrlTo];
  1059. }
  1060. if (move) {
  1061. [[NCNetworking shared] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1062. } else {
  1063. [[NCNetworking shared] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1064. }
  1065. [arrayMetadata removeObjectAtIndex:0];
  1066. [arrayServerUrlTo removeObjectAtIndex:0];
  1067. // End Select Table View
  1068. [self tableViewSelect:false];
  1069. }
  1070. // DELEGATE : Select
  1071. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type array:(NSArray *)array buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1072. {
  1073. if (serverUrl != nil) {
  1074. // E2EE DENIED
  1075. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  1076. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"_e2e_error_not_move_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotMove forced:true];
  1077. return;
  1078. }
  1079. BOOL move = true;
  1080. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1081. if ([_selectedocIdsMetadatas count] > 0) {
  1082. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1083. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1084. } else {
  1085. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1086. }
  1087. }
  1088. }
  1089. - (void)moveOpenWindow:(NSArray *)indexPaths
  1090. {
  1091. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1092. return;
  1093. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1094. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1095. viewController.delegate = self;
  1096. viewController.hideButtonCreateFolder = false;
  1097. viewController.selectFile = false;
  1098. viewController.includeDirectoryE2EEncryption = false;
  1099. viewController.includeImages = false;
  1100. viewController.type = @"";
  1101. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1102. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1103. viewController.isButtonDone1Hide = false;
  1104. viewController.isOverwriteHide = false;
  1105. viewController.keyLayout = k_layout_view_move;
  1106. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1107. [self presentViewController:navigationController animated:YES completion:nil];
  1108. }
  1109. #pragma --------------------------------------------------------------------------------------------
  1110. #pragma mark ===== Create folder =====
  1111. #pragma --------------------------------------------------------------------------------------------
  1112. - (void)createFolder
  1113. {
  1114. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1115. NSString *message;
  1116. UIAlertController *alertController;
  1117. if ([serverUrl isEqualToString:[[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account]]) {
  1118. message = @"/";
  1119. } else {
  1120. message = [serverUrl lastPathComponent];
  1121. }
  1122. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1123. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1124. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1125. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1126. }];
  1127. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }];
  1128. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1129. UITextField *fileName = alertController.textFields.firstObject;
  1130. [[NCNetworking shared] createFolderWithFileName:[fileName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] serverUrl:serverUrl account:appDelegate.account urlBase:appDelegate.urlBase overwrite:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1131. }];
  1132. okAction.enabled = NO;
  1133. [alertController addAction:cancelAction];
  1134. [alertController addAction:okAction];
  1135. [self presentViewController:alertController animated:YES completion:nil];
  1136. }
  1137. #pragma --------------------------------------------------------------------------------------------
  1138. #pragma mark ===== Progress & Task Button =====
  1139. #pragma --------------------------------------------------------------------------------------------
  1140. - (void)triggerProgressTask:(NSNotification *)notification
  1141. {
  1142. if (sectionDataSource.ocIdIndexPath != nil) {
  1143. [[NCMainCommon shared] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1144. }
  1145. }
  1146. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1147. {
  1148. UITouch *touch = [[event allTouches] anyObject];
  1149. CGPoint location = [touch locationInView:self.tableView];
  1150. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1151. if ([self indexPathIsValid:indexPath]) {
  1152. tableMetadata *metadataSection = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1153. if (metadataSection) {
  1154. [[NCMainCommon shared] cancelTransferMetadata:metadataSection uploadStatusForcedStart:false];
  1155. }
  1156. }
  1157. }
  1158. - (void)cancelAllTask:(id)sender
  1159. {
  1160. CGPoint location = [sender locationInView:self.tableView];
  1161. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1162. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1163. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1164. [NCUtility.shared startActivityIndicatorWithView:self.view bottom:0];
  1165. [[NCMainCommon shared] cancelAllTransfer];
  1166. [NCUtility.shared stopActivityIndicator];
  1167. }]];
  1168. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1169. alertController.popoverPresentationController.sourceView = self.tableView;
  1170. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1171. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1172. [alertController.view layoutIfNeeded];
  1173. [self presentViewController:alertController animated:YES completion:nil];
  1174. }
  1175. #pragma --------------------------------------------------------------------------------------------
  1176. #pragma mark ===== Tap =====
  1177. #pragma --------------------------------------------------------------------------------------------
  1178. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1179. {
  1180. CGPoint location = [tapGesture locationInView:self.tableView];
  1181. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1182. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1183. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase: appDelegate.urlBase]) {
  1184. [[NCMainCommon shared] openShareWithViewController:self metadata:metadata indexPage:1];
  1185. }
  1186. }
  1187. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1188. {
  1189. CGPoint location = [tapGesture locationInView:self.tableView];
  1190. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1191. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1192. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  1193. [[NCMainCommon shared] openShareWithViewController:self metadata:metadata indexPage:2];
  1194. }
  1195. }
  1196. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1197. {
  1198. CGPoint location = [tapGesture locationInView:self.tableView];
  1199. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1200. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1201. if (metadata) {
  1202. }
  1203. }
  1204. #pragma --------------------------------------------------------------------------------------------
  1205. #pragma mark ===== Rich Workspace =====
  1206. #pragma --------------------------------------------------------------------------------------------
  1207. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1208. {
  1209. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1210. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1211. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1212. viewerRichWorkspace.serverUrl = self.serverUrl;
  1213. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1214. [self presentViewController:navigationController animated:NO completion:NULL];
  1215. }
  1216. - (void)createRichWorkspace
  1217. {
  1218. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1219. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.account, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1220. if (metadata) {
  1221. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1222. } else {
  1223. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1224. }
  1225. }
  1226. - (void)toggleSortMenu
  1227. {
  1228. NCSortMenu *sortMenu = [NCSortMenu new];
  1229. [sortMenu toggleMenuWithViewController:self key:k_layout_view_main sortButton:self.sortButton serverUrl:self.serverUrl hideDirectoryOnTop:false];
  1230. }
  1231. - (void)toggleSelectMenu
  1232. {
  1233. [self toggleSelectMenuWithViewController:self.navigationController];
  1234. }
  1235. #pragma --------------------------------------------------------------------------------------------
  1236. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1237. #pragma --------------------------------------------------------------------------------------------
  1238. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1239. {
  1240. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1241. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1242. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1243. NSMutableArray *items = [NSMutableArray new];
  1244. if ([self indexPathIsValid:indexPath])
  1245. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1246. [self becomeFirstResponder];
  1247. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1248. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1249. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1250. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1251. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1252. }
  1253. if ([[NCUtility shared] isQuickLookDisplayableWithMetadata:self.metadata]) {
  1254. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  1255. }
  1256. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1257. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1258. [menuController setMenuItems:items];
  1259. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1260. [menuController setMenuVisible:YES animated:YES];
  1261. }
  1262. }
  1263. - (BOOL)canBecomeFirstResponder
  1264. {
  1265. return YES;
  1266. }
  1267. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1268. {
  1269. // For copy file, copy files, Open in ... :
  1270. //
  1271. // NO Directory
  1272. // NO Error Passcode
  1273. // NO In Session mode (download/upload)
  1274. // NO Template
  1275. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  1276. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1277. else return NO;
  1278. }
  1279. if (@selector(copyTouchFiles:) == action) {
  1280. if (_isSelectedMode) {
  1281. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1282. for (tableMetadata *metadata in selectedMetadatas) {
  1283. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1284. return YES;
  1285. }
  1286. }
  1287. return NO;
  1288. }
  1289. if (@selector(pasteTouchFile:) == action) {
  1290. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1291. NSArray *items = [pasteboard items];
  1292. if ([items count] == 1) {
  1293. // Value : (NSData) ocId
  1294. NSDictionary *dic = [items objectAtIndex:0];
  1295. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1296. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1297. if (ocId) {
  1298. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1299. if (metadata) {
  1300. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1301. } else {
  1302. return NO;
  1303. }
  1304. }
  1305. }
  1306. return NO;
  1307. }
  1308. if (@selector(pasteTouchFiles:) == action) {
  1309. BOOL isValid = NO;
  1310. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1311. NSArray *items = [pasteboard items];
  1312. if ([items count] <= 1) return NO;
  1313. for (NSDictionary *dic in items) {
  1314. // Value : (NSData) ocId
  1315. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1316. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1317. if (ocId) {
  1318. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  1319. if (metadata) {
  1320. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1321. isValid = YES;
  1322. } else {
  1323. isValid = NO;
  1324. break;
  1325. }
  1326. } else {
  1327. isValid = NO;
  1328. break;
  1329. }
  1330. } else {
  1331. isValid = NO;
  1332. break;
  1333. }
  1334. }
  1335. return isValid;
  1336. }
  1337. return NO;
  1338. }
  1339. /************************************ COPY ************************************/
  1340. - (void)copyTouchFile:(id)sender
  1341. {
  1342. // Remove all item
  1343. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1344. pasteboard.items = [[NSArray alloc] init];
  1345. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1346. [self copyFileToPasteboard:self.metadata];
  1347. } else {
  1348. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1349. }
  1350. }
  1351. - (void)copyTouchFiles:(id)sender
  1352. {
  1353. // Remove all item
  1354. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1355. pasteboard.items = [[NSArray alloc] init];
  1356. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1357. for (tableMetadata *metadata in selectedMetadatas) {
  1358. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1359. [self copyFileToPasteboard:metadata];
  1360. } else {
  1361. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1362. }
  1363. }
  1364. [self tableViewSelect:false];
  1365. }
  1366. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1367. {
  1368. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1369. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1370. // Value : (NSData) ocId
  1371. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1372. [items addObject:item];
  1373. [pasteboard setItems:items];
  1374. }
  1375. /************************************ OPEN IN ... ******************************/
  1376. - (void)openinTouchFile:(id)sender
  1377. {
  1378. [[NCMainCommon shared] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1379. }
  1380. /************************************ OPEN QUICK LOOK ******************************/
  1381. - (void)openQuickLookTouch:(id)sender
  1382. {
  1383. [[NCMainCommon shared] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1384. }
  1385. /************************************ PASTE ************************************/
  1386. - (void)pasteTouchFile:(id)sender
  1387. {
  1388. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1389. [self uploadFilePasteArray:[pasteboard items]];
  1390. }
  1391. - (void)pasteTouchFiles:(id)sender
  1392. {
  1393. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1394. [self uploadFilePasteArray:[pasteboard items]];
  1395. }
  1396. - (void)uploadFilePasteArray:(NSArray *)items
  1397. {
  1398. for (NSDictionary *dic in items) {
  1399. // Value : (NSData) ocId
  1400. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1401. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1402. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  1403. if (metadata) {
  1404. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1405. NSString *fileName = [[NCUtility shared] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.account];
  1406. NSString *ocId = [[NSUUID UUID] UUIDString];
  1407. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1408. // Prepare record metadata
  1409. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:self.serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  1410. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground;
  1411. metadataForUpload.sessionSelector = selectorUploadFile;
  1412. metadataForUpload.size = metadata.size;
  1413. metadataForUpload.status = k_metadataStatusWaitUpload;
  1414. // Add Medtadata for upload
  1415. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1416. }
  1417. }
  1418. }
  1419. [[appDelegate networkingAutoUpload] startProcess];
  1420. }
  1421. #pragma mark -
  1422. #pragma --------------------------------------------------------------------------------------------
  1423. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1424. #pragma --------------------------------------------------------------------------------------------
  1425. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1426. {
  1427. if (metadata == nil)
  1428. return NO;
  1429. // E2EE
  1430. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO)
  1431. return NO;
  1432. return YES;
  1433. }
  1434. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1435. {
  1436. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1437. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1438. return [self canOpenMenuAction:metadata];
  1439. }
  1440. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1441. {
  1442. }
  1443. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1444. {
  1445. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1446. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1447. if (direction == MGSwipeDirectionRightToLeft) {
  1448. [self actionDelete:indexPath];
  1449. }
  1450. if (direction == MGSwipeDirectionLeftToRight) {
  1451. [[NCNetworking shared] favoriteMetadata:self.metadata urlBase:appDelegate.urlBase completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1452. }
  1453. return YES;
  1454. }
  1455. - (void)actionDelete:(NSIndexPath *)indexPath
  1456. {
  1457. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1458. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1459. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1460. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1461. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1462. }]];
  1463. if (localFile) {
  1464. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1465. tableMetadata *metadataLivePhoto = [[NCManageDatabase sharedInstance] isLivePhotoWithMetadata:metadata];
  1466. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1467. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1468. if (metadataLivePhoto) {
  1469. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1470. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1471. }
  1472. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1473. }]];
  1474. }
  1475. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1476. }]];
  1477. alertController.popoverPresentationController.sourceView = self.tableView;
  1478. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1479. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1480. [alertController.view layoutIfNeeded];
  1481. [self presentViewController:alertController animated:YES completion:nil];
  1482. }
  1483. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1484. {
  1485. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1486. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1487. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1488. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1489. }
  1490. #pragma --------------------------------------------------------------------------------------------
  1491. #pragma mark - ==== Datasource ====
  1492. #pragma --------------------------------------------------------------------------------------------
  1493. - (void)reloadDatasource:(NSNotification *)notification
  1494. {
  1495. NSDictionary *userInfo = notification.userInfo;
  1496. NSString *ocId = userInfo[@"ocId"];
  1497. NSString *serverUrl = userInfo[@"serverUrl"];
  1498. [self reloadDatasource:serverUrl ocId:ocId];
  1499. }
  1500. - (void)reloadDatasourceTransfer:(NSNotification *)notification
  1501. {
  1502. NSDictionary *userInfo = notification.userInfo;
  1503. tableMetadata *metadata = userInfo[@"metadata"];
  1504. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  1505. NSString *errorDescription = userInfo[@"errorDescription"];
  1506. if (errorCode != 0 && self.view.window != nil) {
  1507. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  1508. }
  1509. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1510. }
  1511. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId
  1512. {
  1513. // test
  1514. if (appDelegate.account.length == 0 || serverUrl.length == 0 || serverUrl == nil) // || self.view.window == nil)
  1515. return;
  1516. // Se non siamo nella dir appropriata esci
  1517. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil)
  1518. return;
  1519. // live photo
  1520. livePhoto = [CCUtility getLivePhoto];
  1521. // load share
  1522. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.account];
  1523. // Search Mode
  1524. if (self.searchController.isActive) {
  1525. // Create metadatas
  1526. NSMutableArray *metadatas = [NSMutableArray new];
  1527. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1528. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:resultMetadata.ocId];
  1529. if (metadata) {
  1530. [metadatas addObject:metadata];
  1531. }
  1532. }
  1533. // [CCUtility getGroupBySettings]
  1534. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupBy:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sort:@"fileName" ascending:NO directoryOnTop:NO account:appDelegate.account];
  1535. [self tableViewReloadData];
  1536. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1537. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1538. _noFilesSearchDescription = @"";
  1539. }
  1540. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1541. _noFilesSearchTitle = @"";
  1542. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1543. }
  1544. [self.tableView reloadEmptyDataSet];
  1545. return;
  1546. }
  1547. // Get MetadataFolder
  1548. if ([serverUrl isEqualToString:[[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account]])
  1549. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, k_serverUrl_root]];
  1550. else
  1551. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, serverUrl]];
  1552. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1553. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectoryWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  1554. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1555. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, serverUrl] page:0 limit:0 sorted:@"fileName" ascending:NO];
  1556. // [CCUtility getGroupBySettings]
  1557. NSString *sort = [[NCUtility shared] getSortedForViewWithKey:k_layout_view_main];
  1558. BOOL ascending = [[NCUtility shared] getAscendingForViewWithKey:k_layout_view_main];
  1559. BOOL directoryOnTop = [[NCUtility shared] getDirectoryOnTopForViewWithKey:k_layout_view_main];
  1560. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupBy:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sort:sort ascending:ascending directoryOnTop:directoryOnTop account:appDelegate.account];
  1561. dispatch_async(dispatch_get_main_queue(), ^{
  1562. sectionDataSource = sectionDataSourceTemp;
  1563. [self tableViewReloadData];
  1564. });
  1565. });
  1566. // BLINK
  1567. if (self.blinkFileNamePath != nil) {
  1568. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1569. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1570. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1571. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1572. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1573. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1574. if ([key isEqualToString:metadata.ocId]) {
  1575. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1576. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1577. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1578. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1579. if (cell) {
  1580. self.blinkFileNamePath = nil;
  1581. [[NCUtility shared] blinkWithCell:cell];
  1582. }
  1583. });
  1584. }
  1585. }
  1586. }
  1587. }
  1588. });
  1589. }
  1590. }
  1591. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1592. {
  1593. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1594. if (selectedRows.count > 0) {
  1595. for (NSIndexPath *selectionIndex in selectedRows) {
  1596. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1597. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1598. [metadatas addObject:metadata];
  1599. }
  1600. }
  1601. return metadatas;
  1602. }
  1603. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1604. {
  1605. NSInteger totSections =[sectionDataSource.sections count] ;
  1606. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1607. return nil;
  1608. }
  1609. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1610. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1611. }
  1612. #pragma --------------------------------------------------------------------------------------------
  1613. #pragma mark - ==== Table ====
  1614. #pragma --------------------------------------------------------------------------------------------
  1615. - (void)tableViewToggle
  1616. {
  1617. [self tableViewSelect:!_isSelectedMode];
  1618. }
  1619. - (void)tableViewSelect:(BOOL)toggle
  1620. {
  1621. _isSelectedMode = toggle;
  1622. // chiudiamo eventuali swipe aperti
  1623. if (_isSelectedMode)
  1624. [self.tableView setEditing:NO animated:NO];
  1625. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1626. [self.tableView setEditing:_isSelectedMode animated:YES];
  1627. if (_isSelectedMode)
  1628. [self setUINavigationBarSelected];
  1629. else
  1630. [self setUINavigationBarDefault];
  1631. [_selectedocIdsMetadatas removeAllObjects];
  1632. [self setTitle];
  1633. }
  1634. - (void)tableViewReloadData
  1635. {
  1636. // store selected cells before relod
  1637. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1638. // reload table view
  1639. [self.tableView reloadData];
  1640. // selected cells stored
  1641. for (NSIndexPath *path in indexPaths)
  1642. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1643. [self setTableViewHeader];
  1644. [self setTableViewFooter];
  1645. if (self.tableView.editing)
  1646. [self setTitle];
  1647. [self.tableView reloadEmptyDataSet];
  1648. }
  1649. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  1650. {
  1651. if (tableView.editing == 1) {
  1652. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1653. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  1654. return NO;
  1655. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  1656. return NO;
  1657. else
  1658. return YES;
  1659. } else {
  1660. [_selectedocIdsMetadatas removeAllObjects];
  1661. }
  1662. return YES;
  1663. }
  1664. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1665. {
  1666. return 60;
  1667. }
  1668. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1669. {
  1670. return [[sectionDataSource.sectionArrayRow allKeys] count];
  1671. }
  1672. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1673. {
  1674. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  1675. }
  1676. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  1677. {
  1678. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  1679. NSString *sectionTitle = [sections objectAtIndex:section];
  1680. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  1681. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  1682. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  1683. return 20.f;
  1684. }
  1685. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  1686. {
  1687. float shift;
  1688. UIVisualEffectView *visualEffectView;
  1689. NSString *titleSection;
  1690. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  1691. return nil;
  1692. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  1693. titleSection = [sectionDataSource.sections objectAtIndex:section];
  1694. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  1695. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  1696. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  1697. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  1698. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  1699. else titleSection = NSLocalizedString(titleSection,nil);
  1700. // Format title
  1701. UIVisualEffect *blurEffect;
  1702. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  1703. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  1704. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brandElement colorWithAlphaComponent:0.2];
  1705. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  1706. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1707. shift = - 35;
  1708. else
  1709. shift = - 20;
  1710. } else shift = - 10;
  1711. // Title
  1712. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  1713. titleLabel.backgroundColor = [UIColor clearColor];
  1714. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  1715. titleLabel.font = [UIFont systemFontOfSize:12];
  1716. titleLabel.textAlignment = NSTextAlignmentLeft;
  1717. titleLabel.text = titleSection;
  1718. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1719. [visualEffectView.contentView addSubview:titleLabel];
  1720. // Elements
  1721. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  1722. elementLabel.backgroundColor = [UIColor clearColor];
  1723. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  1724. elementLabel.font = [UIFont systemFontOfSize:12];
  1725. elementLabel.textAlignment = NSTextAlignmentRight;
  1726. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1727. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  1728. NSUInteger rowsCount = [metadatas count];
  1729. if (rowsCount == 0) return nil;
  1730. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  1731. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  1732. [visualEffectView.contentView addSubview:elementLabel];
  1733. return visualEffectView;
  1734. }
  1735. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  1736. {
  1737. return [sectionDataSource.sections indexOfObject:title];
  1738. }
  1739. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  1740. {
  1741. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  1742. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  1743. else
  1744. return nil;
  1745. }
  1746. /*
  1747. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  1748. {
  1749. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  1750. }
  1751. }
  1752. */
  1753. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1754. {
  1755. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1756. tableShare *shareCell;
  1757. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  1758. return [CCCellMain new];
  1759. }
  1760. for (tableShare *share in appDelegate.shares) {
  1761. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  1762. shareCell = share;
  1763. break;
  1764. }
  1765. }
  1766. UITableViewCell *cell = [[NCMainCommon shared] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell livePhoto:livePhoto];
  1767. // NORMAL - > MAIN
  1768. if ([cell isKindOfClass:[CCCellMain class]]) {
  1769. // Comment tap
  1770. if (metadata.commentsUnread) {
  1771. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  1772. [tapComment setNumberOfTapsRequired:1];
  1773. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  1774. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  1775. }
  1776. // Share add Tap
  1777. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  1778. [tapShare setNumberOfTapsRequired:1];
  1779. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  1780. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  1781. // More
  1782. if ([self canOpenMenuAction:metadata]) {
  1783. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  1784. [tapMore setNumberOfTapsRequired:1];
  1785. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  1786. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  1787. }
  1788. // MGSwipeButton
  1789. ((CCCellMain *)cell).delegate = self;
  1790. // LEFT
  1791. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  1792. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  1793. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  1794. //centerIconOverText
  1795. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  1796. [favoriteButton centerIconOverText];
  1797. // RIGHT
  1798. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  1799. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  1800. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  1801. //centerIconOverText
  1802. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  1803. [deleteButton centerIconOverText];
  1804. }
  1805. // TRANSFER
  1806. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1807. // gesture Transfer
  1808. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  1809. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  1810. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  1811. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  1812. }
  1813. return cell;
  1814. }
  1815. - (void)setTableViewHeader
  1816. {
  1817. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  1818. NSString *trimmedRichWorkspaceText = [self.richWorkspaceText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  1819. if (serverVersionMajor < k_nextcloud_version_18_0 || trimmedRichWorkspaceText.length == 0 ) {
  1820. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  1821. } else {
  1822. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  1823. }
  1824. if (self.searchController.isActive == true) {
  1825. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, 0)];
  1826. }
  1827. [self.viewRichWorkspace setNeedsLayout];
  1828. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  1829. }
  1830. - (void)setTableViewFooter
  1831. {
  1832. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1833. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1834. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1835. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1836. UIFont *appFont = [UIFont systemFontOfSize:12];
  1837. footerLabel.font = appFont;
  1838. footerLabel.textColor = [UIColor grayColor];
  1839. footerLabel.backgroundColor = [UIColor clearColor];
  1840. footerLabel.textAlignment = NSTextAlignmentCenter;
  1841. NSString *folders;
  1842. NSString *files;
  1843. NSString *footerText;
  1844. if (sectionDataSource.directories > 1) {
  1845. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  1846. } else if (sectionDataSource.directories == 1){
  1847. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  1848. } else {
  1849. folders = @"";
  1850. }
  1851. if (sectionDataSource.files > 1) {
  1852. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1853. } else if (sectionDataSource.files == 1){
  1854. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1855. } else {
  1856. files = @"";
  1857. }
  1858. if ([folders isEqualToString:@""]) {
  1859. footerText = files;
  1860. } else if ([files isEqualToString:@""]) {
  1861. footerText = folders;
  1862. } else {
  1863. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  1864. }
  1865. footerLabel.text = footerText;
  1866. [footerView addSubview:footerLabel];
  1867. [self.tableView setTableFooterView:footerView];
  1868. }
  1869. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  1870. {
  1871. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  1872. // settiamo il record file.
  1873. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1874. if (!self.metadata)
  1875. return;
  1876. // se non può essere selezionata deseleziona
  1877. if ([cell isEditing] == NO)
  1878. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  1879. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  1880. if (self.tableView.editing) {
  1881. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  1882. [self setTitle];
  1883. return;
  1884. }
  1885. if (self.metadata.status != k_metadataStatusNormal && self.metadata.status != k_metadataStatusDownloadError) {
  1886. return;
  1887. }
  1888. // file
  1889. if (self.metadata.directory == NO) {
  1890. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  1891. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1892. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  1893. } else {
  1894. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.account]) {
  1895. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1896. } else {
  1897. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  1898. [self shouldPerformSegue:self.metadata selector:@""];
  1899. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility shared] isDirectEditingWithAccount:self.metadata.account contentType:self.metadata.contentType] != nil) {
  1900. if (NCCommunication.shared.isNetworkReachable) {
  1901. [self shouldPerformSegue:self.metadata selector:@""];
  1902. } else {
  1903. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1904. }
  1905. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility shared] isRichDocument:self.metadata]) {
  1906. if (NCCommunication.shared.isNetworkReachable) {
  1907. [self shouldPerformSegue:self.metadata selector:@""];
  1908. } else {
  1909. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1910. }
  1911. } else {
  1912. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1913. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  1914. }
  1915. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadFileView setFavorite:false completion:^(NSInteger errorCode) { }];
  1916. }
  1917. }
  1918. }
  1919. }
  1920. if (self.metadata.directory) {
  1921. [self performSegueDirectoryWithMetadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1922. }
  1923. }
  1924. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  1925. {
  1926. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1927. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  1928. [self setTitle];
  1929. }
  1930. - (void)didSelectAll
  1931. {
  1932. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  1933. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  1934. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  1935. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1936. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  1937. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  1938. }
  1939. }
  1940. [self setTitle];
  1941. }
  1942. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  1943. {
  1944. if (!indexPath)
  1945. return NO;
  1946. NSInteger section = indexPath.section;
  1947. NSInteger row = indexPath.row;
  1948. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  1949. if (section > lastSectionIndex || lastSectionIndex < 0)
  1950. return NO;
  1951. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  1952. if (rowCount < 0)
  1953. return NO;
  1954. return row <= rowCount;
  1955. }
  1956. #pragma --------------------------------------------------------------------------------------------
  1957. #pragma mark ===== Navigation ====
  1958. #pragma --------------------------------------------------------------------------------------------
  1959. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  1960. {
  1961. // if background return
  1962. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  1963. if (self.view.window == NO)
  1964. return;
  1965. // Collapsed ma siamo già in detail esci
  1966. if (self.splitViewController.isCollapsed) {
  1967. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  1968. }
  1969. // Metadata for push detail
  1970. self.metadataForPushDetail = metadata;
  1971. self.selectorForPushDetail = selector;
  1972. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1973. }
  1974. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  1975. {
  1976. tableMetadata *metadata;
  1977. NSMutableArray *photoDataSource = [NSMutableArray new];
  1978. UINavigationController *navigationController = segue.destinationViewController;
  1979. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  1980. if ([sender isKindOfClass:[tableMetadata class]]) {
  1981. metadata = sender;
  1982. [photoDataSource addObject:sender];
  1983. } else {
  1984. metadata = self.metadataForPushDetail;
  1985. for (NSString *ocId in sectionDataSource.allOcId) {
  1986. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1987. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1988. [photoDataSource addObject:metadata];
  1989. }
  1990. }
  1991. detailViewController.metadata = metadata;
  1992. detailViewController.selector = self.selectorForPushDetail;
  1993. [detailViewController setTitle:metadata.fileNameView];
  1994. }
  1995. // can i go to next viewcontroller
  1996. - (void)performSegueDirectoryWithMetadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  1997. {
  1998. NSString *nomeDir;
  1999. if (self.tableView.editing == NO) {
  2000. // E2EE Check enable
  2001. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO) {
  2002. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  2003. return;
  2004. }
  2005. nomeDir = metadata.fileName;
  2006. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  2007. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  2008. if (!viewController) {
  2009. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  2010. viewController.serverUrl = serverUrlPush;
  2011. viewController.titleMain = metadata.fileNameView;
  2012. viewController.blinkFileNamePath = blinkFileNamePath;
  2013. // save self
  2014. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  2015. [self.navigationController pushViewController:viewController animated:YES];
  2016. } else {
  2017. if (viewController.isViewLoaded) {
  2018. viewController.titleMain = metadata.fileNameView;
  2019. viewController.blinkFileNamePath = blinkFileNamePath;
  2020. // Fix : Application tried to present modally an active controller
  2021. if ([self.navigationController isBeingPresented]) {
  2022. // being presented
  2023. } else if ([self.navigationController isMovingToParentViewController]) {
  2024. // being pushed
  2025. } else {
  2026. [self.navigationController pushViewController:viewController animated:YES];
  2027. }
  2028. }
  2029. }
  2030. }
  2031. }
  2032. @end