CCMain.m 157 KB

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