CCMain.m 162 KB

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