CCMain.m 120 KB

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