CCMain.m 159 KB

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