CCMain.m 161 KB

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