CCMain.m 142 KB

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