CCMain.m 157 KB

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