CCMain.m 159 KB

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