CCMain.m 142 KB

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