CCMain.m 146 KB

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