CCMain.m 146 KB

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