CCMain.m 142 KB

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