CCMain.m 145 KB

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