CCMain.m 157 KB

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