CCMain.m 126 KB

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