CCMain.m 137 KB

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