CCMain.m 145 KB

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