CCMain.m 127 KB

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