CCMain.m 140 KB

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