CCMain.m 157 KB

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