CCMain.m 158 KB

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