CCMain.m 157 KB

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