CCMain.m 160 KB

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