CCMain.m 121 KB

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