CCMain.m 140 KB

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