CCMain.m 138 KB

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