CCMain.m 159 KB

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