CCMain.m 140 KB

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