CCMain.m 142 KB

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