CCMain.m 138 KB

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