CCMain.m 123 KB

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