CCMain.m 207 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  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 <JDStatusBarNotification/JDStatusBarNotification.h>
  24. #import "CCMain.h"
  25. #import "AppDelegate.h"
  26. #import "CCSynchronize.h"
  27. #import "OCActivity.h"
  28. #import "OCNotifications.h"
  29. #import "OCNotificationsAction.h"
  30. #import "OCFrameworkConstants.h"
  31. #import "OCCapabilities.h"
  32. #import "NCAutoUpload.h"
  33. #import "NCBridgeSwift.h"
  34. #import "NCNetworkingEndToEnd.h"
  35. #import "PKDownloadButton.h"
  36. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb, NCSelectDelegate, UITextFieldDelegate>
  37. {
  38. AppDelegate *appDelegate;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. NSMutableDictionary *_selectedFileIDsMetadatas;
  42. NSUInteger _numSelectedFileIDsMetadatas;
  43. UIImageView *_imageTitleHome;
  44. NSUInteger _failedAttempts;
  45. NSDate *_lockUntilDate;
  46. UIRefreshControl *refreshControl;
  47. CCHud *_hud;
  48. // Datasource
  49. CCSectionDataSourceMetadata *sectionDataSource;
  50. NSDate *_dateReadDataSource;
  51. // Search
  52. BOOL _isSearchMode;
  53. NSString *_searchFileName;
  54. NSMutableArray *_searchResultMetadatas;
  55. NSString *_noFilesSearchTitle;
  56. NSString *_noFilesSearchDescription;
  57. NSTimer *_timerWaitInput;
  58. // Automatic Upload Folder
  59. NSString *_autoUploadFileName;
  60. NSString *_autoUploadDirectory;
  61. // Folder
  62. BOOL _loadingFolder;
  63. tableMetadata *_metadataFolder;
  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. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  75. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  76. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  77. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  78. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  79. // Active Main
  80. appDelegate.activeMain = self;
  81. }
  82. return self;
  83. }
  84. #pragma --------------------------------------------------------------------------------------------
  85. #pragma mark ===== View =====
  86. #pragma --------------------------------------------------------------------------------------------
  87. - (void)viewDidLoad
  88. {
  89. [super viewDidLoad];
  90. // init object
  91. self.metadata = [tableMetadata new];
  92. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  93. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  94. _isViewDidLoad = YES;
  95. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  96. _searchResultMetadatas = [NSMutableArray new];
  97. _searchFileName = @"";
  98. _noFilesSearchTitle = @"";
  99. _noFilesSearchDescription = @"";
  100. // delegate
  101. self.tableView.delegate = self;
  102. self.tableView.tableFooterView = [UIView new];
  103. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  104. self.tableView.emptyDataSetDelegate = self;
  105. self.tableView.emptyDataSetSource = self;
  106. self.searchController.delegate = self;
  107. self.searchController.searchBar.delegate = self;
  108. // Register cell
  109. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  110. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  111. // long press recognizer TableView
  112. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  113. [self.tableView addGestureRecognizer:longPressRecognizer];
  114. // Pull-to-Refresh
  115. [self createRefreshControl];
  116. // Register for 3D Touch Previewing if available
  117. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  118. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  119. }
  120. // reMenu Background
  121. _reMenuBackgroundView = [UIView new];
  122. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  123. // if this is not Main (the Main uses inizializeMain)
  124. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  125. // Read (File) Folder
  126. [self readFileReloadFolder];
  127. }
  128. // Title
  129. [self setTitle];
  130. }
  131. - (void)viewWillAppear:(BOOL)animated
  132. {
  133. [super viewWillAppear:animated];
  134. // test
  135. if (appDelegate.activeAccount.length == 0)
  136. return;
  137. // Color
  138. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  139. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  140. // Plus Button
  141. [appDelegate plusButtonVisibile:true];
  142. if (_isSelectedMode)
  143. [self setUINavigationBarSelected];
  144. else
  145. [self setUINavigationBarDefault];
  146. // If not editing mode remove _selectedFileIDs
  147. if (!self.tableView.editing)
  148. [_selectedFileIDsMetadatas removeAllObjects];
  149. // Search Bar
  150. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  151. [self searchEnabled:NO];
  152. } else {
  153. [self searchEnabled:YES];
  154. }
  155. // Query data source
  156. if (!_isSearchMode) {
  157. [self queryDatasourceWithReloadData:YES serverUrl:self.serverUrl];
  158. }
  159. }
  160. - (void)viewDidAppear:(BOOL)animated
  161. {
  162. [super viewDidAppear:animated];
  163. // Active Main
  164. appDelegate.activeMain = self;
  165. // Test viewDidLoad
  166. if (_isViewDidLoad) {
  167. _isViewDidLoad = NO;
  168. } else {
  169. if (appDelegate.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  170. // Read (file) Folder
  171. [self readFileReloadFolder];
  172. }
  173. }
  174. // Title
  175. [self setTitle];
  176. }
  177. - (void)viewWillDisappear:(BOOL)animated
  178. {
  179. [super viewWillDisappear:animated];
  180. [self closeAllMenu];
  181. }
  182. - (void)didReceiveMemoryWarning
  183. {
  184. [super didReceiveMemoryWarning];
  185. // Dispose of any resources that can be recreated.
  186. }
  187. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  188. {
  189. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  190. [self closeAllMenu];
  191. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  192. 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))) {
  193. // Portrait
  194. } else {
  195. // Landscape
  196. }
  197. [self.tableView reloadData];
  198. }];
  199. }
  200. - (BOOL)prefersStatusBarHidden
  201. {
  202. return NO;
  203. }
  204. // detect scroll for remove keyboard in search mode
  205. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  206. {
  207. if (_isSearchMode && scrollView == self.tableView) {
  208. [self.searchController.searchBar endEditing:YES];
  209. }
  210. }
  211. - (void)changeTheming
  212. {
  213. if (self.isViewLoaded && self.view.window)
  214. [appDelegate changeTheming:self];
  215. // Refresh control
  216. refreshControl.tintColor = [NCBrandColor sharedInstance].brandText;
  217. refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  218. // color searchbar
  219. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  220. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  221. // color searchbbar button text (cancel)
  222. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  223. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  224. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  225. }
  226. // Title
  227. [self setTitle];
  228. // Reload Table View
  229. [self tableViewReloadData];
  230. }
  231. #pragma --------------------------------------------------------------------------------------------
  232. #pragma mark ===== Initizlize Mail =====
  233. #pragma --------------------------------------------------------------------------------------------
  234. //
  235. // Callers :
  236. //
  237. // loginSuccess (delagate)
  238. // ChangeDefaultAccount (delegate)
  239. // Split : inizialize
  240. // Settings Advanced : removeAllFiles
  241. //
  242. - (void)initializeMain:(NSNotification *)notification
  243. {
  244. _dateReadDataSource = nil;
  245. // test
  246. if (appDelegate.activeAccount.length == 0)
  247. return;
  248. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  249. // This is Root home main add list
  250. appDelegate.homeMain = self;
  251. _isRoot = YES;
  252. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  253. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  254. // go Home
  255. [self.navigationController popToRootViewControllerAnimated:NO];
  256. // Remove search mode
  257. [self cancelSearchBar];
  258. // Clear error certificate
  259. [CCUtility setCertificateError:appDelegate.activeAccount error:NO];
  260. // populate shared Link & User
  261. NSArray *results = [[NCManageDatabase sharedInstance] getSharesWithAccount:appDelegate.activeAccount];
  262. if (results) {
  263. appDelegate.sharesLink = results[0];
  264. appDelegate.sharesUserAndGroup = results[1];
  265. }
  266. // Setting Theming
  267. [appDelegate settingThemingColorBrand];
  268. // Detail
  269. // If AVPlayer in play -> Stop
  270. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  271. [appDelegate.player pause];
  272. }
  273. for (UIView *view in [appDelegate.activeDetail.view subviews]) {
  274. if ([view isKindOfClass:[UIImageView class]] == NO) { // View Image Nextcloud
  275. [view removeFromSuperview];
  276. }
  277. }
  278. appDelegate.activeDetail.title = nil;
  279. // remove all Notification Messages
  280. [appDelegate.listOfNotifications removeAllObjects];
  281. // Not Photos Video in library ? then align and Init Auto Upload
  282. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  283. if ([recordsPhotoLibrary count] == 0) {
  284. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  285. }
  286. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  287. NSLog(@"[LOG] Request Service Server Nextcloud");
  288. [[NCService sharedInstance] startRequestServicesServer];
  289. // Clear datasorce
  290. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl fileID:nil action:k_action_NULL];
  291. // Read this folder
  292. [self readFileReloadFolder];
  293. } else {
  294. // reload datasource
  295. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl fileID:nil action:k_action_NULL];
  296. }
  297. // Registered push notification
  298. [appDelegate pushNotification];
  299. }
  300. #pragma --------------------------------------------------------------------------------------------
  301. #pragma mark ==== DZNEmptyDataSetSource ====
  302. #pragma --------------------------------------------------------------------------------------------
  303. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  304. {
  305. if (_loadingFolder)
  306. return NO;
  307. else
  308. return YES;
  309. }
  310. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  311. {
  312. return [NCBrandColor sharedInstance].backgroundView;
  313. }
  314. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  315. {
  316. if (_isSearchMode)
  317. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:[NCBrandColor sharedInstance].brandElement];
  318. else
  319. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:[NCBrandColor sharedInstance].brandElement];
  320. }
  321. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  322. {
  323. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  324. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  325. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  326. activityView.color = [NCBrandColor sharedInstance].brandElement;
  327. [activityView startAnimating];
  328. return activityView;
  329. }
  330. return nil;
  331. }
  332. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  333. {
  334. NSString *text;
  335. if (_isSearchMode) {
  336. text = _noFilesSearchTitle;
  337. } else {
  338. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  339. }
  340. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  341. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  342. }
  343. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  344. {
  345. NSString *text;
  346. if (_isSearchMode) {
  347. text = _noFilesSearchDescription;
  348. } else {
  349. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  350. }
  351. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  352. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  353. paragraph.alignment = NSTextAlignmentCenter;
  354. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  355. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  356. }
  357. #pragma --------------------------------------------------------------------------------------------
  358. #pragma mark ===== Text Field =====
  359. #pragma --------------------------------------------------------------------------------------------
  360. - (void)minCharTextFieldDidChange:(UITextField *)sender
  361. {
  362. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  363. if (alertController)
  364. {
  365. UITextField *fileName = alertController.textFields.firstObject;
  366. UIAlertAction *okAction = alertController.actions.lastObject;
  367. okAction.enabled = fileName.text.length > 0;
  368. }
  369. }
  370. - (void)textFieldDidBeginEditing:(UITextField *)textField
  371. {
  372. [CCUtility selectFileNameFrom:textField];
  373. }
  374. #pragma --------------------------------------------------------------------------------------------
  375. #pragma mark ===== Graphic Window =====
  376. #pragma --------------------------------------------------------------------------------------------
  377. - (void)createRefreshControl
  378. {
  379. refreshControl = [UIRefreshControl new];
  380. if (@available(iOS 10, *)) {
  381. _tableView.refreshControl = refreshControl;
  382. } else {
  383. [_tableView addSubview:refreshControl];
  384. }
  385. refreshControl.tintColor = [NCBrandColor sharedInstance].brandText;
  386. refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  387. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  388. }
  389. - (void)deleteRefreshControl
  390. {
  391. [refreshControl endRefreshing];
  392. for (UIView *subview in [_tableView subviews]) {
  393. if (subview == refreshControl)
  394. [subview removeFromSuperview];
  395. }
  396. if (@available(iOS 10, *)) {
  397. self.tableView.refreshControl = nil;
  398. }
  399. refreshControl = nil;
  400. }
  401. - (void)refreshControlTarget
  402. {
  403. [self readFolder:_serverUrl];
  404. // Actuate `Peek` feedback (weak boom)
  405. AudioServicesPlaySystemSound(1519);
  406. }
  407. - (void)setTitle
  408. {
  409. // Color text self.navigationItem.title
  410. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  411. if (_isSelectedMode) {
  412. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  413. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  414. self.navigationItem.titleView = nil;
  415. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  416. } else {
  417. // we are in home : LOGO BRAND
  418. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  419. self.navigationItem.title = nil;
  420. UIImage *image = [self getImageLogoHome];
  421. _imageTitleHome = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)]; // IMAGE = 120 x 60
  422. _imageTitleHome.contentMode = UIViewContentModeScaleAspectFill;
  423. _imageTitleHome.translatesAutoresizingMaskIntoConstraints = NO;
  424. _imageTitleHome.image = image;
  425. // backbutton
  426. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:nil action:nil];
  427. [_imageTitleHome setUserInteractionEnabled:YES];
  428. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  429. [singleTap setNumberOfTapsRequired:1];
  430. [_imageTitleHome addGestureRecognizer:singleTap];
  431. self.navigationItem.titleView = _imageTitleHome;
  432. } else {
  433. self.navigationItem.title = _titleMain;
  434. self.navigationItem.titleView = nil;
  435. }
  436. }
  437. }
  438. - (UIImage *)getImageLogoHome
  439. {
  440. if ([NCBrandOptions sharedInstance].use_themingLogo) {
  441. UIImage *imageThemingLogo = [UIImage imageNamed:@"themingLogo"];
  442. NSInteger multiplier = 2;
  443. NSString *fileNameThemingLogo = [NSString stringWithFormat:@"%@/%@-themingLogo.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl]];
  444. UIImage *image = [UIImage imageWithContentsOfFile:fileNameThemingLogo];
  445. if (image != nil) {
  446. imageThemingLogo = image;
  447. multiplier = 1;
  448. }
  449. if ([appDelegate.reachability isReachable] == NO) {
  450. return [CCGraphics changeThemingColorImage:imageThemingLogo multiplier:multiplier color:[NCBrandColor sharedInstance].icon];
  451. } else {
  452. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  453. if ([capabilities.themingColor isEqualToString:@"#FFFFFF"])
  454. return [CCGraphics changeThemingColorImage:imageThemingLogo multiplier:multiplier color:[UIColor blackColor]];
  455. else
  456. return [CCGraphics changeThemingColorImage:imageThemingLogo multiplier:multiplier color:[UIColor whiteColor]];
  457. }
  458. } else {
  459. if ([appDelegate.reachability isReachable] == NO)
  460. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"themingLogo"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  461. else
  462. return [UIImage imageNamed:@"themingLogo"];
  463. }
  464. }
  465. - (void)setUINavigationBarDefault
  466. {
  467. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  468. UIBarButtonItem *buttonMore, *buttonNotification;
  469. // =
  470. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  471. buttonMore.enabled = true;
  472. // <
  473. self.navigationController.navigationBar.hidden = NO;
  474. // Notification
  475. if ([appDelegate.listOfNotifications count] > 0) {
  476. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  477. buttonNotification.tintColor = [NCBrandColor sharedInstance].brandText;
  478. buttonNotification.enabled = true;
  479. }
  480. if (buttonNotification)
  481. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  482. else
  483. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  484. self.navigationItem.leftBarButtonItem = nil;
  485. }
  486. - (void)setUINavigationBarSelected
  487. {
  488. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  489. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  490. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  491. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  492. self.navigationItem.leftBarButtonItem = leftButton;
  493. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  494. }
  495. - (void)cancelSelect
  496. {
  497. [self tableViewSelect:NO];
  498. [appDelegate.reSelectMenu close];
  499. }
  500. - (void)closeAllMenu
  501. {
  502. // close Menu
  503. [appDelegate.reSelectMenu close];
  504. [appDelegate.reMainMenu close];
  505. // Close Menu Logo
  506. [CCMenuAccount dismissMenu];
  507. }
  508. #pragma --------------------------------------------------------------------------------------------
  509. #pragma mark ===== Document Picker =====
  510. #pragma --------------------------------------------------------------------------------------------
  511. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  512. {
  513. NSLog(@"[LOG] Cancelled");
  514. }
  515. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  516. {
  517. NSLog(@"[LOG] Cancelled");
  518. }
  519. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  520. {
  521. documentPicker.delegate = self;
  522. [self presentViewController:documentPicker animated:YES completion:nil];
  523. }
  524. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  525. {
  526. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  527. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  528. __block NSError *error;
  529. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  530. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  531. NSString *fileName = [[NCUtility sharedInstance] createFileName:[url lastPathComponent] serverUrl:serverUrl account:appDelegate.activeAccount];
  532. NSString *fileID = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  533. NSData *data = [NSData dataWithContentsOfURL:newURL];
  534. if (data && error == nil) {
  535. if ([data writeToFile:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  536. tableMetadata *metadataForUpload = [tableMetadata new];
  537. metadataForUpload.account = appDelegate.activeAccount;
  538. metadataForUpload.date = [NSDate new];
  539. metadataForUpload.fileID = fileID;
  540. metadataForUpload.fileName = fileName;
  541. metadataForUpload.fileNameView = fileName;
  542. metadataForUpload.serverUrl = serverUrl;
  543. metadataForUpload.session = k_upload_session;
  544. metadataForUpload.sessionSelector = selectorUploadFile;
  545. metadataForUpload.size = data.length;
  546. metadataForUpload.status = k_metadataStatusWaitUpload;
  547. // Check il file already exists
  548. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileName]];
  549. if (metadata) {
  550. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  551. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  552. // NO OVERWITE
  553. }];
  554. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  555. // Remove record metadata
  556. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  557. // Add Medtadata for upload
  558. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  559. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  560. [appDelegate startLoadAutoDownloadUpload];
  561. }];
  562. [alertController addAction:cancelAction];
  563. [alertController addAction:overwriteAction];
  564. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  565. alertWindow.rootViewController = [[UIViewController alloc]init];
  566. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  567. [alertWindow makeKeyAndVisible];
  568. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  569. } else {
  570. // Add Medtadata for upload
  571. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  572. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  573. [appDelegate startLoadAutoDownloadUpload];
  574. }
  575. } else {
  576. [appDelegate messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  577. }
  578. } else {
  579. [appDelegate messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  580. }
  581. }];
  582. }
  583. }
  584. - (void)openImportDocumentPicker
  585. {
  586. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  587. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  588. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  589. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  590. documentProviderMenu.delegate = self;
  591. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  592. }
  593. #pragma --------------------------------------------------------------------------------------------
  594. #pragma mark ===== Assets Picker =====
  595. #pragma --------------------------------------------------------------------------------------------
  596. -(void)dismissFormUploadAssets
  597. {
  598. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  599. }
  600. - (void)openAssetsPickerController
  601. {
  602. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self];
  603. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nonnull assets) {
  604. if (assets.count > 0) {
  605. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  606. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  607. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets cryptated:NO session:k_upload_session delegate:self];
  608. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  609. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  610. [self presentViewController:navigationController animated:YES completion:nil];
  611. });
  612. }
  613. }];
  614. }
  615. #pragma --------------------------------------------------------------------------------------------
  616. #pragma mark ===== Save selected File =====
  617. #pragma --------------------------------------------------------------------------------------------
  618. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  619. {
  620. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView];
  621. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  622. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  623. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  624. if (image)
  625. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  626. else
  627. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  628. }
  629. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  630. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  631. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  632. } else {
  633. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  634. }
  635. }
  636. if (status != PHAuthorizationStatusAuthorized) {
  637. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  638. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  639. [alertController addAction:okAction];
  640. [self presentViewController:alertController animated:YES completion:nil];
  641. }
  642. }
  643. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  644. {
  645. if (error)
  646. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  647. else
  648. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  649. }
  650. - (void)saveSelectedFiles
  651. {
  652. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  653. return;
  654. NSLog(@"[LOG] Start download selected files ...");
  655. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  656. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  657. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  658. for (tableMetadata *metadata in metadatas) {
  659. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  660. metadata.session = k_download_session;
  661. metadata.sessionError = @"";
  662. metadata.sessionSelector = selectorSave;
  663. metadata.status = k_metadataStatusWaitDownload;
  664. // Add Metadata for Download
  665. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  666. [appDelegate startLoadAutoDownloadUpload];
  667. }
  668. }
  669. [_hud hideHud];
  670. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  671. });
  672. [self tableViewSelect:NO];
  673. }
  674. #pragma --------------------------------------------------------------------------------------------
  675. #pragma mark ==== View Notification ====
  676. #pragma --------------------------------------------------------------------------------------------
  677. - (void)viewNotification
  678. {
  679. if ([appDelegate.listOfNotifications count] > 0) {
  680. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  681. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  682. [self presentViewController:notificationVC animated:YES completion:nil];
  683. }
  684. }
  685. #pragma --------------------------------------------------------------------------------------------
  686. #pragma mark === Delegate Login ===
  687. #pragma --------------------------------------------------------------------------------------------
  688. - (void)loginSuccess:(NSInteger)loginType
  689. {
  690. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  691. // go to home sweet home
  692. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  693. });
  694. }
  695. #pragma mark -
  696. #pragma --------------------------------------------------------------------------------------------
  697. #pragma mark ===== Peek & Pop =====
  698. #pragma --------------------------------------------------------------------------------------------
  699. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  700. {
  701. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  702. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  703. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  704. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  705. if (cell) {
  706. previewingContext.sourceRect = cell.frame;
  707. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  708. viewController.metadata = metadata;
  709. viewController.imageFile = cell.file.image;
  710. viewController.showOpenIn = true;
  711. viewController.showShare = true;
  712. return viewController;
  713. }
  714. return nil;
  715. }
  716. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  717. {
  718. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  719. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  720. }
  721. #pragma --------------------------------------------------------------------------------------------
  722. #pragma mark ==== Download ====
  723. #pragma --------------------------------------------------------------------------------------------
  724. - (void)downloadSelectedFilesFolders
  725. {
  726. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  727. return;
  728. NSLog(@"[LOG] Start download selected ...");
  729. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  730. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  731. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  732. for (tableMetadata *metadata in selectedMetadatas) {
  733. if (metadata.directory) {
  734. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  735. } else {
  736. [[CCSynchronize sharedSynchronize] readFile:metadata.fileID fileName:metadata.fileName serverUrl:metadata.serverUrl selector:selectorReadFileWithDownload account:appDelegate.activeAccount];
  737. }
  738. }
  739. [_hud hideHud];
  740. });
  741. [self tableViewSelect:NO];
  742. }
  743. #pragma --------------------------------------------------------------------------------------------
  744. #pragma mark ===== Upload new Photos/Videos =====
  745. #pragma --------------------------------------------------------------------------------------------
  746. //
  747. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  748. //
  749. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  750. {
  751. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  752. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  753. // if request create the folder for Auto Upload & the subfolders
  754. if ([autoUploadPath isEqualToString:serverUrl])
  755. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  756. return;
  757. dispatch_async(dispatch_get_main_queue(), ^{
  758. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  759. });
  760. });
  761. }
  762. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  763. {
  764. for (PHAsset *asset in assets) {
  765. tableMetadata *metadata;
  766. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  767. NSDate *assetDate = asset.creationDate;
  768. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  769. // Create serverUrl if use sub folder
  770. if (useSubFolder) {
  771. [formatter setDateFormat:@"yyyy"];
  772. NSString *yearString = [formatter stringFromDate:assetDate];
  773. [formatter setDateFormat:@"MM"];
  774. NSString *monthString = [formatter stringFromDate:assetDate];
  775. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  776. }
  777. // Check if is in upload
  778. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] sorted:nil ascending:NO];
  779. if ([isRecordInSessions count] > 0)
  780. continue;
  781. // Prepare record metadata
  782. tableMetadata *metadataForUpload = [tableMetadata new];
  783. metadataForUpload.account = appDelegate.activeAccount;
  784. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  785. metadataForUpload.date = [NSDate new];
  786. metadataForUpload.fileID = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  787. metadataForUpload.fileName = fileName;
  788. metadataForUpload.fileNameView = fileName;
  789. metadataForUpload.serverUrl = serverUrl;
  790. metadataForUpload.session = session;
  791. metadataForUpload.sessionSelector = selectorUploadFile;
  792. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  793. metadataForUpload.status = k_metadataStatusWaitUpload;
  794. NSString *fileNameExtension = [fileName pathExtension];
  795. NSString *fileNameWithoutExtension = [fileName stringByDeletingPathExtension];
  796. if ([[fileNameExtension lowercaseString] isEqualToString:@"heic"] && [CCUtility getFormatCompatibility]) {
  797. NSString *fileNameCompatibility = [fileNameWithoutExtension stringByAppendingString:@".jpg"];
  798. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileNameCompatibility]];
  799. } else {
  800. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileName]];
  801. }
  802. // Check il file already exists
  803. if (metadata) {
  804. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileNameWithoutExtension message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  805. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }];
  806. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  807. // Remove record metadata
  808. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  809. // Add Medtadata for upload
  810. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  811. [appDelegate startLoadAutoDownloadUpload];
  812. }];
  813. [alertController addAction:cancelAction];
  814. [alertController addAction:overwriteAction];
  815. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  816. alertWindow.rootViewController = [[UIViewController alloc]init];
  817. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  818. [alertWindow makeKeyAndVisible];
  819. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  820. } else {
  821. // Add Medtadata for upload
  822. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  823. [appDelegate startLoadAutoDownloadUpload];
  824. }
  825. }
  826. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  827. }
  828. #pragma --------------------------------------------------------------------------------------------
  829. #pragma mark ==== Read File ====
  830. #pragma --------------------------------------------------------------------------------------------
  831. - (void)readFileReloadFolder
  832. {
  833. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  834. return;
  835. // Load Datasource
  836. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  837. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  838. });
  839. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:_serverUrl fileName:nil completion:^(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode) {
  840. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  841. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadata.serverUrl]];
  842. // Change etag, read folder or BLINK
  843. if ([metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  844. [self readFolder:metadata.serverUrl];
  845. }
  846. } else if (errorCode != 0) {
  847. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  848. } else {
  849. NSLog(@"[LOG] It has been changed user during networking process, error.");
  850. }
  851. }];
  852. }
  853. #pragma --------------------------------------------------------------------------------------------
  854. #pragma mark ==== Read Folder ====
  855. #pragma --------------------------------------------------------------------------------------------
  856. - (void)insertMetadatasWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  857. {
  858. // stoprefresh
  859. [refreshControl endRefreshing];
  860. // save metadataFolder
  861. _metadataFolder = metadataFolder;
  862. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  863. if (tableAccount == nil) {
  864. return;
  865. }
  866. if (_isSearchMode == NO) {
  867. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted account:account];
  868. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND (status == %d OR status == %d)", account, serverUrl, k_metadataStatusNormal, k_metadataStatusHide]];
  869. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithServerUrl:serverUrl account:account];
  870. }
  871. 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];
  872. // insert in Database
  873. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  874. // insert in Database the /
  875. if (metadataFolder != nil) {
  876. _metadataFolder = [[NCManageDatabase sharedInstance] addMetadata:metadataFolder];
  877. }
  878. // reinsert metadatas in Download
  879. if (metadatasInDownload) {
  880. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload];
  881. }
  882. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  883. // File is changed ??
  884. if (!_isSearchMode && metadatasToInsertInDB)
  885. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:serverUrl account:account withDownload:NO];
  886. });
  887. // Search Mode
  888. if (_isSearchMode) {
  889. // Fix managed -> Unmanaged _searchResultMetadatas
  890. if (metadatasToInsertInDB)
  891. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  892. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl fileID:nil action:k_action_NULL];
  893. }
  894. // this is the same directory
  895. if ([serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  896. // reload
  897. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl fileID:nil action:k_action_NULL];
  898. [self tableViewReloadData];
  899. }
  900. // E2EE Is encrypted folder get metadata
  901. if (_metadataFolder.e2eEncrypted) {
  902. NSString *metadataFolderFileID = metadataFolder.fileID;
  903. // Read Metadata
  904. if ([CCUtility isEndToEndEnabled:account]) {
  905. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  906. NSString *metadata;
  907. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileID:metadataFolderFileID user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  908. dispatch_async(dispatch_get_main_queue(), ^{
  909. if (error) {
  910. if (error.code != kOCErrorServerPathNotFound)
  911. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  912. } else {
  913. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:tableAccount.url] == false)
  914. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  915. else
  916. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl fileID:nil action:k_action_NULL];
  917. }
  918. });
  919. });
  920. } else {
  921. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  922. }
  923. }
  924. // rewrite title
  925. [self setTitle];
  926. }
  927. - (void)readFolder:(NSString *)serverUrl
  928. {
  929. // init control
  930. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  931. [refreshControl endRefreshing];
  932. return;
  933. }
  934. // Search Mode
  935. if (_isSearchMode) {
  936. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  937. _searchFileName = @""; // forced reload searchg
  938. [self updateSearchResultsForSearchController:self.searchController];
  939. return;
  940. }
  941. _loadingFolder = YES;
  942. [self tableViewReloadData];
  943. [[OCNetworking sharedManager] readFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl depth:@"1" completion:^(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode) {
  944. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  945. [self insertMetadatasWithAccount:account serverUrl:serverUrl metadataFolder:metadataFolder metadatas:metadatas];
  946. } else if (errorCode != 0) {
  947. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  948. } else {
  949. NSLog(@"[LOG] It has been changed user during networking process, error.");
  950. }
  951. _loadingFolder = NO;
  952. }];
  953. }
  954. #pragma mark -
  955. #pragma --------------------------------------------------------------------------------------------
  956. #pragma mark ===== Search =====
  957. #pragma --------------------------------------------------------------------------------------------
  958. - (void)searchEnabled:(BOOL)enabled
  959. {
  960. if (enabled) {
  961. if (self.tableView.tableHeaderView != nil)
  962. return;
  963. self.definesPresentationContext = YES;
  964. self.searchController.searchResultsUpdater = self;
  965. self.searchController.dimsBackgroundDuringPresentation = NO;
  966. self.searchController.searchBar.translucent = NO;
  967. [self.searchController.searchBar sizeToFit];
  968. self.searchController.searchBar.delegate = self;
  969. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  970. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  971. self.searchController.searchBar.backgroundImage = [UIImage new];
  972. // color searchbbar button text (cancel)
  973. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  974. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  975. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  976. }
  977. self.tableView.tableHeaderView = self.searchController.searchBar;
  978. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  979. } else {
  980. self.tableView.tableHeaderView = nil;
  981. }
  982. }
  983. - (void)searchStartTimer
  984. {
  985. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  986. [[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) {
  987. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  988. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  989. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  990. } else {
  991. if (errorCode != 0) {
  992. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  993. } else {
  994. NSLog(@"[LOG] It has been changed user during networking process, error.");
  995. }
  996. _searchFileName = @"";
  997. }
  998. }];
  999. _noFilesSearchTitle = @"";
  1000. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1001. [self.tableView reloadEmptyDataSet];
  1002. }
  1003. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1004. {
  1005. // Color text "Cancel"
  1006. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1007. _isSearchMode = YES;
  1008. [self deleteRefreshControl];
  1009. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1010. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1011. _searchFileName = fileName;
  1012. // First : filter
  1013. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1014. [_searchResultMetadatas removeAllObjects];
  1015. for (tableMetadata *record in records)
  1016. [_searchResultMetadatas addObject:record];
  1017. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  1018. // Version >= 12
  1019. if ([[NCManageDatabase sharedInstance] getServerVersionWithAccount:appDelegate.activeAccount] >= 12) {
  1020. [_timerWaitInput invalidate];
  1021. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1022. }
  1023. }
  1024. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1025. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1026. }
  1027. }
  1028. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1029. {
  1030. [self cancelSearchBar];
  1031. [self readFolder:_serverUrl];
  1032. }
  1033. - (void)cancelSearchBar
  1034. {
  1035. if (self.searchController.active) {
  1036. [self.searchController setActive:NO];
  1037. [self createRefreshControl];
  1038. _isSearchMode = NO;
  1039. _searchFileName = @"";
  1040. _dateReadDataSource = nil;
  1041. _searchResultMetadatas = [NSMutableArray new];
  1042. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1043. }
  1044. //[self setNeedsStatusBarAppearanceUpdate];
  1045. }
  1046. #pragma mark -
  1047. #pragma --------------------------------------------------------------------------------------------
  1048. #pragma mark ===== Delete File or Folder =====
  1049. #pragma --------------------------------------------------------------------------------------------
  1050. - (void)deleteFile
  1051. {
  1052. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1053. return;
  1054. NSArray *metadatas;
  1055. if ([_selectedFileIDsMetadatas count] > 0) {
  1056. metadatas = [_selectedFileIDsMetadatas allValues];
  1057. } else {
  1058. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1059. }
  1060. // remove optimization
  1061. _dateReadDataSource = nil;
  1062. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderFileID:_metadataFolder.fileID completion:^(NSInteger errorCode, NSString *message) {
  1063. // Reload
  1064. if (_isSearchMode)
  1065. [self readFolder:self.serverUrl];
  1066. else
  1067. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1068. }];
  1069. // End Select Table View
  1070. [self tableViewSelect:NO];
  1071. }
  1072. #pragma --------------------------------------------------------------------------------------------
  1073. #pragma mark ===== Rename =====
  1074. #pragma --------------------------------------------------------------------------------------------
  1075. - (void)renameFile:(NSArray *)arguments
  1076. {
  1077. tableMetadata *metadata = [arguments objectAtIndex:0];
  1078. NSString *fileName = [arguments objectAtIndex:1];
  1079. // E2EE
  1080. if (_metadataFolder.e2eEncrypted) {
  1081. // verify if exists the new fileName
  1082. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1083. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1084. return;
  1085. }
  1086. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1087. 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];
  1088. if (error) {
  1089. dispatch_async(dispatch_get_main_queue(), ^{
  1090. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1091. });
  1092. } else {
  1093. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithServerUrl:metadata.serverUrl fileName:metadata.fileName newFileNameView:fileName account:appDelegate.activeAccount];
  1094. // Move file system
  1095. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  1096. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileName];
  1097. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1098. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileName] error:nil];
  1099. }
  1100. // Unlock
  1101. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1102. if (tableLock != nil) {
  1103. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:self.serverUrl fileID:_metadataFolder.fileID token:tableLock.token user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1104. if (error) {
  1105. dispatch_async(dispatch_get_main_queue(), ^{
  1106. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1107. });
  1108. }
  1109. }
  1110. dispatch_async(dispatch_get_main_queue(), ^{
  1111. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1112. });
  1113. });
  1114. } else {
  1115. // Plain
  1116. NSString *fileNameNew = [CCUtility removeForbiddenCharactersServer:fileName];
  1117. if ([fileName length] == 0 || [fileName isEqualToString:metadata.fileNameView]) {
  1118. return;
  1119. }
  1120. // Verify if exists the fileName TO
  1121. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:metadata.serverUrl fileName:fileNameNew completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1122. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1123. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1124. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }];
  1125. [alert addAction:ok];
  1126. [self presentViewController:alert animated:YES completion:nil];
  1127. } else if (errorCode != 0) {
  1128. if (errorCode == kOCErrorServerPathNotFound) {
  1129. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1130. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, fileNameNew];
  1131. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1132. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1133. // Rename metadata
  1134. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:fileNameNew fileID:metadata.fileID];
  1135. if (metadata.directory) {
  1136. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  1137. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:fileNameNew];
  1138. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadata.serverUrl]];
  1139. if (directoryTable == nil) {
  1140. [appDelegate messageNotification:@"_rename_" description:@"Internal error, ServerUrl not found" visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1141. return;
  1142. }
  1143. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:@"" fileID:nil encrypted:directoryTable.e2eEncrypted account:appDelegate.activeAccount];
  1144. } else {
  1145. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:fileNameNew etag:nil];
  1146. // Move file system
  1147. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileName];
  1148. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileNameNew];
  1149. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1150. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileName];
  1151. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileNameNew];
  1152. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1153. }
  1154. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1155. } else if (errorCode != 0) {
  1156. [appDelegate messageNotification:@"_rename_" description:message visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1157. } else {
  1158. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1159. }
  1160. }];
  1161. } else {
  1162. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1163. }
  1164. } else {
  1165. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1166. }
  1167. }];
  1168. }
  1169. }
  1170. #pragma --------------------------------------------------------------------------------------------
  1171. #pragma mark ===== Move =====
  1172. #pragma --------------------------------------------------------------------------------------------
  1173. - (void)moveFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1174. {
  1175. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:serverUrlTo fileName:metadata.fileName completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1176. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1177. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1178. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1179. }];
  1180. [alert addAction:ok];
  1181. [self presentViewController:alert animated:YES completion:nil];
  1182. // End Select Table View
  1183. [self tableViewSelect:NO];
  1184. // reload Datasource
  1185. [self readFileReloadFolder];
  1186. } else if (errorCode != 0) {
  1187. if (errorCode == kOCErrorServerPathNotFound) {
  1188. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1189. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName];
  1190. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1191. [_hud hideHud];
  1192. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1193. if (metadata.directory) {
  1194. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] account:account];
  1195. }
  1196. [[NCManageDatabase sharedInstance] moveMetadataWithFileID:metadata.fileID serverUrlTo:serverUrlTo];
  1197. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:metadata.serverUrl account:account];
  1198. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrlTo account:account];
  1199. // next
  1200. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  1201. if ([_selectedFileIDsMetadatas count] > 0) {
  1202. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1203. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrlTo numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1204. } else {
  1205. // End Select Table View
  1206. [self tableViewSelect:NO];
  1207. // reload Datasource
  1208. if (_isSearchMode)
  1209. [self readFolder:metadata.serverUrl];
  1210. else
  1211. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1212. }
  1213. } else if (errorCode != 0) {
  1214. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1215. // End Select Table View
  1216. [self tableViewSelect:NO];
  1217. // reload Datasource
  1218. if (_isSearchMode)
  1219. [self readFolder:metadata.serverUrl];
  1220. else
  1221. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl fileID:nil action:k_action_NULL];
  1222. } else {
  1223. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1224. }
  1225. }];
  1226. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1227. } else {
  1228. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1229. }
  1230. } else {
  1231. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1232. }
  1233. }];
  1234. }
  1235. // DELEGATE : Select
  1236. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1237. {
  1238. if (serverUrl == nil) {
  1239. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1240. } else {
  1241. // E2EE DENIED
  1242. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1243. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1244. return;
  1245. }
  1246. if ([_selectedFileIDsMetadatas count] > 0) {
  1247. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1248. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1249. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1250. } else {
  1251. _numSelectedFileIDsMetadatas = 1;
  1252. [self moveFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1253. }
  1254. }
  1255. }
  1256. - (void)moveOpenWindow:(NSArray *)indexPaths
  1257. {
  1258. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1259. return;
  1260. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1261. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1262. viewController.delegate = self;
  1263. viewController.hideButtonCreateFolder = false;
  1264. viewController.selectFile = false;
  1265. viewController.includeDirectoryE2EEncryption = false;
  1266. viewController.includeImages = false;
  1267. viewController.type = @"";
  1268. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1269. viewController.layoutViewSelect = k_layout_view_move;
  1270. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1271. [self presentViewController:navigationController animated:YES completion:nil];
  1272. }
  1273. #pragma --------------------------------------------------------------------------------------------
  1274. #pragma mark ===== Create folder =====
  1275. #pragma --------------------------------------------------------------------------------------------
  1276. - (void)createFolder
  1277. {
  1278. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1279. NSString *message;
  1280. UIAlertController *alertController;
  1281. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1282. message = @"/";
  1283. } else {
  1284. message = [serverUrl lastPathComponent];
  1285. }
  1286. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1287. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1288. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1289. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  1290. }];
  1291. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1292. NSLog(@"[LOG] Cancel action");
  1293. }];
  1294. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1295. UITextField *fileName = alertController.textFields.firstObject;
  1296. [self createFolder:fileName.text serverUrl:serverUrl];
  1297. }];
  1298. okAction.enabled = NO;
  1299. [alertController addAction:cancelAction];
  1300. [alertController addAction:okAction];
  1301. [self presentViewController:alertController animated:YES completion:nil];
  1302. }
  1303. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1304. {
  1305. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1306. if (![fileNameFolder length]) return;
  1307. NSString *fileIDTemp = [[NSUUID UUID] UUIDString];
  1308. // Create Directory (temp) on metadata
  1309. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:fileIDTemp serverUrl:serverUrl fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal url:@""];
  1310. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1311. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  1312. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1313. // Creeate folder Networking
  1314. [[OCNetworking sharedManager] createFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileNameFolder completion:^(NSString *account, NSString *fileID, NSDate *date, NSString *message, NSInteger errorCode) {
  1315. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1316. // Delete Temp Dir
  1317. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp]];
  1318. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1319. if (_metadataFolder.e2eEncrypted) {
  1320. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1321. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory fileID:fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1322. dispatch_async(dispatch_get_main_queue(), ^{
  1323. if (error) {
  1324. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1325. }
  1326. [self readFolder:self.serverUrl];
  1327. });
  1328. });
  1329. } else {
  1330. [self readFolder:self.serverUrl];
  1331. }
  1332. } else {
  1333. // Delete Temp Dir
  1334. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp]];
  1335. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1336. if (errorCode != 0) {
  1337. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1338. } else {
  1339. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1340. }
  1341. }
  1342. }];
  1343. }
  1344. #pragma --------------------------------------------------------------------------------------------
  1345. #pragma mark ===== Progress & Task Button =====
  1346. #pragma --------------------------------------------------------------------------------------------
  1347. - (void)triggerProgressTask:(NSNotification *)notification
  1348. {
  1349. if (sectionDataSource.fileIDIndexPath != nil) {
  1350. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceFileIDIndexPath:sectionDataSource.fileIDIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1351. }
  1352. }
  1353. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1354. {
  1355. UITouch *touch = [[event allTouches] anyObject];
  1356. CGPoint location = [touch locationInView:self.tableView];
  1357. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1358. if ([self indexPathIsValid:indexPath]) {
  1359. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1360. if (metadataSection) {
  1361. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1362. if (metadata)
  1363. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1364. }
  1365. }
  1366. }
  1367. - (void)cancelAllTask:(id)sender
  1368. {
  1369. CGPoint location = [sender locationInView:self.tableView];
  1370. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1371. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1372. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1373. [[NCMainCommon sharedInstance] cancelAllTransferWithView:self.view];
  1374. }]];
  1375. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1376. alertController.popoverPresentationController.sourceView = self.tableView;
  1377. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1378. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1379. [alertController.view layoutIfNeeded];
  1380. [self presentViewController:alertController animated:YES completion:nil];
  1381. }
  1382. #pragma --------------------------------------------------------------------------------------------
  1383. #pragma mark ===== Shared =====
  1384. #pragma --------------------------------------------------------------------------------------------
  1385. - (void)readShareWithAccount:(NSString *)account openWindow:(BOOL)openWindow metadata:(tableMetadata *)metadata
  1386. {
  1387. /*
  1388. NSString *path = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1389. [[OCNetworking sharedManager] readShareWithAccount:account path:path completion:^(NSString *account, NSArray *items, NSString *message, NSInteger errorCode) {
  1390. }];
  1391. */
  1392. [[OCNetworking sharedManager] readShareWithAccount:account completion:^(NSString *account, NSArray *items, NSString *message, NSInteger errorCode) {
  1393. [_hud hideHud];
  1394. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1395. [appDelegate.sharesID removeAllObjects];
  1396. for (OCSharedDto *item in items)
  1397. [appDelegate.sharesID setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  1398. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:appDelegate.sharesID activeUrl:appDelegate.activeUrl account:appDelegate.activeAccount];
  1399. if (result) {
  1400. appDelegate.sharesLink = result[0];
  1401. appDelegate.sharesUserAndGroup = result[1];
  1402. }
  1403. // Notify Shares View
  1404. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1405. if (openWindow) {
  1406. if (_shareOC) {
  1407. [_shareOC reloadData];
  1408. } else if (metadata) {
  1409. // Apriamo la view
  1410. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1411. _shareOC.delegate = self;
  1412. _shareOC.metadata = metadata;
  1413. _shareOC.serverUrl = metadata.serverUrl;
  1414. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1415. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1416. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1417. [self presentViewController:_shareOC animated:YES completion:nil];
  1418. }
  1419. }
  1420. [self tableViewReloadData];
  1421. } else if (errorCode != 0) {
  1422. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1423. }
  1424. }];
  1425. if (openWindow) {
  1426. [_hud visibleIndeterminateHud];
  1427. }
  1428. }
  1429. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload
  1430. {
  1431. NSString *fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1432. [[OCNetworking sharedManager] shareWithAccount:appDelegate.activeAccount fileName:fileName password:password permission:permission hideDownload:hideDownload completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1433. [_hud hideHud];
  1434. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1435. [self readShareWithAccount:account openWindow:YES metadata:metadata];
  1436. } else if (errorCode != 0) {
  1437. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1438. }
  1439. if (_shareOC)
  1440. [_shareOC reloadData];
  1441. [self tableViewReloadData];
  1442. }];
  1443. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1444. }
  1445. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1446. {
  1447. [[OCNetworking sharedManager] unshareAccount:appDelegate.activeAccount shareID:[share integerValue] completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1448. [_hud hideHud];
  1449. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1450. // rimuoviamo la condivisione da db
  1451. NSArray *result = [[NCManageDatabase sharedInstance] unShare:share fileName:metadata.fileName serverUrl:metadata.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup account:account];
  1452. if (result) {
  1453. appDelegate.sharesLink = result[0];
  1454. appDelegate.sharesUserAndGroup = result[1];
  1455. }
  1456. [self readShareWithAccount:account openWindow:YES metadata:metadata];
  1457. } else if (errorCode != 0) {
  1458. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1459. }
  1460. if (_shareOC)
  1461. [_shareOC reloadData];
  1462. [self tableViewReloadData];
  1463. }];
  1464. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1465. }
  1466. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission hideDownload:(BOOL)hideDownload
  1467. {
  1468. [[OCNetworking sharedManager] shareUpdateAccount:appDelegate.activeAccount shareID:[share integerValue] password:password permission:permission expirationTime:expirationTime hideDownload:hideDownload completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1469. [_hud hideHud];
  1470. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1471. [self readShareWithAccount:account openWindow:YES metadata:metadata];
  1472. } else if (errorCode != 0) {
  1473. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1474. }
  1475. if (_shareOC)
  1476. [_shareOC reloadData];
  1477. [self tableViewReloadData];
  1478. }];
  1479. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1480. }
  1481. - (void)getUserAndGroup:(NSString *)find
  1482. {
  1483. [[OCNetworking sharedManager] getUserGroupWithAccount:appDelegate.activeAccount searchString:find completion:^(NSString *account, NSArray *item, NSString *message, NSInteger errorCode) {
  1484. [_hud hideHud];
  1485. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1486. if (_shareOC)
  1487. [_shareOC reloadUserAndGroup:item];
  1488. } else if (errorCode != 0) {
  1489. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1490. }
  1491. }];
  1492. [_hud visibleIndeterminateHud];
  1493. }
  1494. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1495. {
  1496. NSString *fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1497. [[OCNetworking sharedManager] shareUserGroupWithAccount:appDelegate.activeAccount userOrGroup:user fileName:fileName permission:permission shareeType:shareeType completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1498. [_hud hideHud];
  1499. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1500. [self readShareWithAccount:account openWindow:YES metadata:metadata];
  1501. } else if (errorCode != 0) {
  1502. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1503. }
  1504. if (_shareOC)
  1505. [_shareOC reloadData];
  1506. [self tableViewReloadData];
  1507. }];
  1508. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1509. }
  1510. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1511. {
  1512. CGPoint location = [tapGesture locationInView:self.tableView];
  1513. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1514. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1515. if (metadata)
  1516. [appDelegate.activeMain readShareWithAccount:appDelegate.activeAccount openWindow:YES metadata:metadata];
  1517. }
  1518. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1519. {
  1520. CGPoint location = [tapGesture locationInView:self.tableView];
  1521. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1522. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1523. if (metadata) {
  1524. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1525. vc.metadata = metadata;
  1526. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1527. [self presentViewController:vc animated:YES completion:nil];
  1528. }
  1529. }
  1530. #pragma --------------------------------------------------------------------------------------------
  1531. #pragma mark ===== Favorite =====
  1532. #pragma --------------------------------------------------------------------------------------------
  1533. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1534. {
  1535. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1536. [[OCNetworking sharedManager] settingFavoriteWithAccount:appDelegate.activeAccount fileName:fileNameServerUrl favorite:favorite completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1537. if (errorCode == 0 && [appDelegate.activeAccount isEqualToString:account]) {
  1538. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  1539. _dateReadDataSource = nil;
  1540. if (_isSearchMode)
  1541. [self readFolder:self.serverUrl];
  1542. else
  1543. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1544. if (metadata.directory && favorite) {
  1545. NSString *selector;
  1546. if ([CCUtility getFavoriteOffline])
  1547. selector = selectorReadFolderWithDownload;
  1548. else
  1549. selector = selectorReadFolder;
  1550. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector account:appDelegate.activeAccount];
  1551. }
  1552. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1553. metadata.favorite = favorite;
  1554. metadata.session = k_download_session;
  1555. metadata.sessionError = @"";
  1556. metadata.sessionSelector = selectorDownloadSynchronize;
  1557. metadata.status = k_metadataStatusWaitDownload;
  1558. // Add Metadata for Download
  1559. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1560. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1561. [appDelegate startLoadAutoDownloadUpload];
  1562. }
  1563. } else if (errorCode != 0) {
  1564. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1565. } else {
  1566. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1567. }
  1568. }];
  1569. }
  1570. #pragma --------------------------------------------------------------------------------------------
  1571. #pragma mark ==== Menu LOGO ====
  1572. #pragma --------------------------------------------------------------------------------------------
  1573. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1574. {
  1575. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1576. return;
  1577. // Brand
  1578. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1579. return;
  1580. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1581. NSMutableArray *menuArray = [NSMutableArray new];
  1582. for (NSString *account in listAccount) {
  1583. CCMenuItem *item = [[CCMenuItem alloc] init];
  1584. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1585. item.argument = account;
  1586. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1587. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1588. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1589. if (avatar) {
  1590. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1591. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1592. CGSize imageSize = avatarImageView.bounds.size;
  1593. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1594. CGContextRef context = UIGraphicsGetCurrentContext();
  1595. [avatarImageView.layer renderInContext:context];
  1596. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1597. UIGraphicsEndImageContext();
  1598. } else {
  1599. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1600. }
  1601. item.image = avatar;
  1602. item.target = self;
  1603. if ([account isEqualToString:appDelegate.activeAccount]) {
  1604. item.action = nil;
  1605. [menuArray insertObject:item atIndex:0];
  1606. } else {
  1607. item.action = @selector(changeDefaultAccount:);
  1608. [menuArray addObject:item];
  1609. }
  1610. }
  1611. // Add + new account
  1612. CCMenuItem *item = [[CCMenuItem alloc] init];
  1613. item.title = NSLocalizedString(@"_add_account_", nil);
  1614. item.argument = @"";
  1615. item.image = [UIImage imageNamed:@"add"];
  1616. item.target = self;
  1617. item.action = @selector(addNewAccount:);
  1618. [menuArray addObject:item];
  1619. OptionalConfiguration options;
  1620. Color textColor, backgroundColor;
  1621. textColor.R = 0;
  1622. textColor.G = 0;
  1623. textColor.B = 0;
  1624. backgroundColor.R = 1;
  1625. backgroundColor.G = 1;
  1626. backgroundColor.B = 1;
  1627. options.arrowSize = 9;
  1628. options.marginXSpacing = 7;
  1629. options.marginYSpacing = 10;
  1630. options.intervalSpacing = 20;
  1631. options.menuCornerRadius = 6.5;
  1632. options.maskToBackground = NO;
  1633. options.shadowOfMenu = YES;
  1634. options.hasSeperatorLine = YES;
  1635. options.seperatorLineHasInsets = YES;
  1636. options.textColor = textColor;
  1637. options.menuBackgroundColor = backgroundColor;
  1638. CGRect rect = self.view.frame;
  1639. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1640. CGFloat safeAreaTop = 0;
  1641. CGFloat offsetY = 35;
  1642. if (@available(iOS 11, *)) {
  1643. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1644. }
  1645. rect.origin.y = locationY + safeAreaTop + offsetY;
  1646. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1647. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1648. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1649. }
  1650. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1651. {
  1652. // LOGOUT
  1653. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1654. if (tableAccount) {
  1655. // LOGIN
  1656. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1657. // go to home sweet home
  1658. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1659. }
  1660. }
  1661. - (void)addNewAccount:(CCMenuItem *)sender
  1662. {
  1663. [appDelegate openLoginView:self delegate:self loginType:k_login_Add selector:k_intro_login];
  1664. }
  1665. #pragma --------------------------------------------------------------------------------------------
  1666. #pragma mark ==== ReMenu ====
  1667. #pragma --------------------------------------------------------------------------------------------
  1668. - (void)createReMenuBackgroundView:(REMenu *)menu
  1669. {
  1670. CGFloat safeAreaBottom = 0;
  1671. CGFloat safeAreaTop = 0;
  1672. CGFloat statusBar = 0;
  1673. if (@available(iOS 11, *)) {
  1674. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1675. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1676. }
  1677. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1678. statusBar = 13;
  1679. }
  1680. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1681. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1682. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1683. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1684. [UIView animateWithDuration:0.2 animations:^{
  1685. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1686. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1687. if (y>minimum) {
  1688. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1689. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1690. }
  1691. }];
  1692. }
  1693. - (void)createReMainMenu
  1694. {
  1695. NSString *title;
  1696. NSString *groupBy = [CCUtility getGroupBySettings];
  1697. NSString *sorted = [CCUtility getOrderSettings];
  1698. BOOL ascending = [CCUtility getAscendingSettings];
  1699. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1700. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"selectLight"] width:50 height:50 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1701. if ([sectionDataSource.allRecordsDataSource count] > 0) [self tableViewSelect:YES];
  1702. }];
  1703. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1704. if ([sorted isEqualToString:@"fileName"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_a_z_", nil)]; }
  1705. else title = NSLocalizedString(@"_order_by_name_a_z_", nil);
  1706. appDelegate.sortFileNameAZItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameAZ"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1707. [CCUtility setOrderSettings:@"fileName"];
  1708. [CCUtility setAscendingSettings:true];
  1709. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1710. }];
  1711. if ([sorted isEqualToString:@"fileName"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_z_a_", nil)]; }
  1712. else title = NSLocalizedString(@"_order_by_name_z_a_", nil);
  1713. appDelegate.sortFileNameZAItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameZA"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1714. [CCUtility setOrderSettings:@"fileName"];
  1715. [CCUtility setAscendingSettings:false];
  1716. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1717. }];
  1718. if ([sorted isEqualToString:@"date"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_more_recent_", nil)]; }
  1719. else title = NSLocalizedString(@"_order_by_date_more_recent_", nil);
  1720. appDelegate.sortDateMoreRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateMoreRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1721. [CCUtility setOrderSettings:@"date"];
  1722. [CCUtility setAscendingSettings:false];
  1723. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1724. }];
  1725. if ([sorted isEqualToString:@"date"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_less_recent_", nil)]; }
  1726. else title = NSLocalizedString(@"_order_by_date_less_recent_", nil);
  1727. appDelegate.sortDateLessRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateLessRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1728. [CCUtility setOrderSettings:@"date"];
  1729. [CCUtility setAscendingSettings:true];
  1730. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1731. }];
  1732. if ([sorted isEqualToString:@"size"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_smallest_", nil)]; }
  1733. else title = NSLocalizedString(@"_order_by_size_smallest_", nil);
  1734. appDelegate.sortSmallestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortSmallest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1735. [CCUtility setOrderSettings:@"size"];
  1736. [CCUtility setAscendingSettings:true];
  1737. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1738. }];
  1739. if ([sorted isEqualToString:@"size"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_largest_", nil)]; }
  1740. else title = NSLocalizedString(@"_order_by_size_largest_", nil);
  1741. appDelegate.sortLargestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortLargest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1742. [CCUtility setOrderSettings:@"size"];
  1743. [CCUtility setAscendingSettings:false];
  1744. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1745. }];
  1746. // ITEM GROUP ALPHABETIC -----------------------------------------------------------------------------------------------------
  1747. if ([groupBy isEqualToString:@"alphabetic"]) { title = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1748. else { title = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1749. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1750. if ([groupBy isEqualToString:@"alphabetic"]) [CCUtility setGroupBySettings:@"none"];
  1751. else [CCUtility setGroupBySettings:@"alphabetic"];
  1752. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1753. }];
  1754. // ITEM GROUP TYPEFILE -------------------------------------------------------------------------------------------------------
  1755. if ([groupBy isEqualToString:@"typefile"]) { title = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1756. else { title = NSLocalizedString(@"_group_typefile_no_", nil); }
  1757. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1758. if ([groupBy isEqualToString:@"typefile"]) [CCUtility setGroupBySettings:@"none"];
  1759. else [CCUtility setGroupBySettings:@"typefile"];
  1760. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1761. }];
  1762. // ITEM GROUP DATE -------------------------------------------------------------------------------------------------------
  1763. if ([groupBy isEqualToString:@"date"]) { title = NSLocalizedString(@"_group_date_yes_", nil); }
  1764. else { title = NSLocalizedString(@"_group_date_no_", nil); }
  1765. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1766. if ([groupBy isEqualToString:@"date"]) [CCUtility setGroupBySettings:@"none"];
  1767. else [CCUtility setGroupBySettings:@"date"];
  1768. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1769. }];
  1770. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1771. if ([CCUtility getDirectoryOnTop]) { title = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1772. else { title = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1773. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"foldersOnTop"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1774. if ([CCUtility getDirectoryOnTop]) [CCUtility setDirectoryOnTop:NO];
  1775. else [CCUtility setDirectoryOnTop:YES];
  1776. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1777. }];
  1778. // REMENU --------------------------------------------------------------------------------------------------------------
  1779. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.sortFileNameAZItem, appDelegate.sortFileNameZAItem, appDelegate.sortDateMoreRecentItem, appDelegate.sortDateLessRecentItem, appDelegate.sortSmallestItem, appDelegate.sortLargestItem,appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  1780. appDelegate.reMainMenu.itemHeight = 40;
  1781. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1782. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1783. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1784. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1785. appDelegate.reMainMenu.separatorHeight = 0.5;
  1786. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1787. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1788. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  1789. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  1790. appDelegate.reMainMenu.textShadowColor = nil;
  1791. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  1792. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  1793. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  1794. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  1795. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  1796. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  1797. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1798. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  1799. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1800. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  1801. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1802. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1803. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1804. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1805. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  1806. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1807. appDelegate.reMainMenu.borderWidth = 0.3;
  1808. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  1809. appDelegate.reMainMenu.animationDuration = 0.2;
  1810. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  1811. appDelegate.reMainMenu.bounce = NO;
  1812. __weak typeof(self) weakSelf = self;
  1813. [appDelegate.reMainMenu setClosePreparationBlock:^{
  1814. // Backgroun reMenu (Gesture)
  1815. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1816. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1817. }];
  1818. }
  1819. - (void)toggleReMainMenu
  1820. {
  1821. if (appDelegate.reMainMenu.isOpen) {
  1822. [appDelegate.reMainMenu close];
  1823. } else {
  1824. [self createReMainMenu];
  1825. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  1826. // Backgroun reMenu & (Gesture)
  1827. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  1828. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  1829. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1830. }
  1831. }
  1832. - (void)createReSelectMenu
  1833. {
  1834. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  1835. appDelegate.selectAllItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_all_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"selectFull"] width:50 height:50 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1836. [self didSelectAll];
  1837. }];
  1838. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  1839. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1840. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  1841. }];
  1842. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  1843. appDelegate.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1844. [self downloadSelectedFilesFolders];
  1845. }];
  1846. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  1847. appDelegate.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1848. [self saveSelectedFiles];
  1849. }];
  1850. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  1851. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1852. [self deleteFile];
  1853. }];
  1854. // E2EE
  1855. if (_metadataFolder.e2eEncrypted) {
  1856. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1857. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1858. } else {
  1859. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1860. }
  1861. } else {
  1862. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1863. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1864. } else {
  1865. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1866. }
  1867. }
  1868. appDelegate.reSelectMenu.itemHeight = 50;
  1869. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  1870. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1871. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  1872. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  1873. appDelegate.reSelectMenu.separatorHeight = 0.5;
  1874. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1875. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1876. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  1877. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  1878. appDelegate.reSelectMenu.textShadowColor = nil;
  1879. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  1880. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  1881. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  1882. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  1883. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  1884. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  1885. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1886. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  1887. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1888. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  1889. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1890. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1891. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1892. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1893. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  1894. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1895. appDelegate.reSelectMenu.borderWidth = 0.3;
  1896. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  1897. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  1898. appDelegate.reSelectMenu.animationDuration = 0.2;
  1899. appDelegate.reSelectMenu.bounce = NO;
  1900. __weak typeof(self) weakSelf = self;
  1901. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  1902. // Backgroun reMenu (Gesture)
  1903. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1904. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1905. }];
  1906. }
  1907. - (void)toggleReSelectMenu
  1908. {
  1909. if (appDelegate.reSelectMenu.isOpen) {
  1910. [appDelegate.reSelectMenu close];
  1911. } else {
  1912. [self createReSelectMenu];
  1913. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  1914. // Backgroun reMenu & (Gesture)
  1915. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  1916. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  1917. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1918. }
  1919. }
  1920. #pragma --------------------------------------------------------------------------------------------
  1921. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1922. #pragma --------------------------------------------------------------------------------------------
  1923. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1924. {
  1925. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1926. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1927. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1928. if ([self indexPathIsValid:indexPath])
  1929. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1930. else
  1931. self.metadata = nil;
  1932. [self becomeFirstResponder];
  1933. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1934. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  1935. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  1936. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  1937. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  1938. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  1939. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1940. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, pasteFileItem, pasteFilesItem, nil]];
  1941. } else {
  1942. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  1943. }
  1944. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1945. [menuController setMenuVisible:YES animated:YES];
  1946. }
  1947. }
  1948. - (BOOL)canBecomeFirstResponder
  1949. {
  1950. return YES;
  1951. }
  1952. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1953. {
  1954. // For copy file, copy files, Open in ... :
  1955. //
  1956. // NO Directory
  1957. // NO Error Passcode
  1958. // NO In Session mode (download/upload)
  1959. // NO Template
  1960. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  1961. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1962. else return NO;
  1963. }
  1964. if (@selector(copyFiles:) == action) {
  1965. if (_isSelectedMode) {
  1966. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1967. for (tableMetadata *metadata in selectedMetadatas) {
  1968. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1969. return YES;
  1970. }
  1971. }
  1972. return NO;
  1973. }
  1974. if (@selector(pasteFile:) == action) {
  1975. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1976. NSArray *items = [pasteboard items];
  1977. if ([items count] == 1) {
  1978. // Value : (NSData) fileID
  1979. NSDictionary *dic = [items objectAtIndex:0];
  1980. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  1981. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  1982. if (fileID) {
  1983. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  1984. if (metadata) {
  1985. return [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView];
  1986. } else {
  1987. return NO;
  1988. }
  1989. }
  1990. }
  1991. return NO;
  1992. }
  1993. if (@selector(pasteFiles:) == action) {
  1994. BOOL isValid = NO;
  1995. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1996. NSArray *items = [pasteboard items];
  1997. if ([items count] <= 1) return NO;
  1998. for (NSDictionary *dic in items) {
  1999. // Value : (NSData) fileID
  2000. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2001. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2002. if (fileID) {
  2003. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2004. if (metadata) {
  2005. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2006. isValid = YES;
  2007. } else {
  2008. isValid = NO;
  2009. break;
  2010. }
  2011. } else {
  2012. isValid = NO;
  2013. break;
  2014. }
  2015. } else {
  2016. isValid = NO;
  2017. break;
  2018. }
  2019. }
  2020. return isValid;
  2021. }
  2022. return NO;
  2023. }
  2024. /************************************ COPY ************************************/
  2025. - (void)copyFile:(id)sender
  2026. {
  2027. // Remove all item
  2028. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2029. pasteboard.items = [[NSArray alloc] init];
  2030. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2031. [self copyFileToPasteboard:self.metadata];
  2032. } else {
  2033. self.metadata.session = k_download_session;
  2034. self.metadata.sessionError = @"";
  2035. self.metadata.sessionSelector = selectorLoadCopy;
  2036. self.metadata.status = k_metadataStatusWaitDownload;
  2037. // Add Metadata for Download
  2038. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2039. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2040. [appDelegate startLoadAutoDownloadUpload];
  2041. }
  2042. }
  2043. - (void)copyFiles:(id)sender
  2044. {
  2045. // Remove all item
  2046. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2047. pasteboard.items = [[NSArray alloc] init];
  2048. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2049. for (tableMetadata *metadata in selectedMetadatas) {
  2050. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2051. [self copyFileToPasteboard:metadata];
  2052. } else {
  2053. metadata.session = k_download_session;
  2054. metadata.sessionError = @"";
  2055. metadata.sessionSelector = selectorLoadCopy;
  2056. metadata.status = k_metadataStatusWaitDownload;
  2057. // Add Metadata for Download
  2058. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2059. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  2060. [appDelegate startLoadAutoDownloadUpload];
  2061. }
  2062. }
  2063. [self tableViewSelect:NO];
  2064. }
  2065. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2066. {
  2067. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2068. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2069. // Value : (NSData) fileID
  2070. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2071. [items addObject:item];
  2072. [pasteboard setItems:items];
  2073. }
  2074. /************************************ OPEN IN ... ******************************/
  2075. - (void)openinFile:(id)sender
  2076. {
  2077. [[NCMainCommon sharedInstance] downloadOpenInMetadata:self.metadata];
  2078. }
  2079. /************************************ PASTE ************************************/
  2080. - (void)pasteFile:(id)sender
  2081. {
  2082. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2083. [self uploadFilePasteArray:[pasteboard items]];
  2084. }
  2085. - (void)pasteFiles:(id)sender
  2086. {
  2087. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2088. [self uploadFilePasteArray:[pasteboard items]];
  2089. }
  2090. - (void)uploadFilePasteArray:(NSArray *)items
  2091. {
  2092. for (NSDictionary *dic in items) {
  2093. // Value : (NSData) fileID
  2094. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2095. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2096. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2097. if (metadata) {
  2098. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2099. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  2100. NSString *fileID = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  2101. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName]];
  2102. tableMetadata *metadataForUpload = [tableMetadata new];
  2103. metadataForUpload.account = appDelegate.activeAccount;
  2104. metadataForUpload.date = [NSDate new];
  2105. metadataForUpload.fileID = fileID;
  2106. metadataForUpload.fileName = fileName;
  2107. metadataForUpload.fileNameView = fileName;
  2108. metadataForUpload.serverUrl = self.serverUrl;
  2109. metadataForUpload.session = k_upload_session;
  2110. metadataForUpload.sessionSelector = selectorUploadFile;
  2111. metadataForUpload.size = metadata.size;
  2112. metadataForUpload.status = k_metadataStatusWaitUpload;
  2113. // Add Medtadata for upload
  2114. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2115. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2116. }
  2117. }
  2118. }
  2119. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2120. [appDelegate startLoadAutoDownloadUpload];
  2121. }
  2122. #pragma --------------------------------------------------------------------------------------------
  2123. #pragma mark ===== Lock Passcode =====
  2124. #pragma --------------------------------------------------------------------------------------------
  2125. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2126. {
  2127. return _failedAttempts;
  2128. }
  2129. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2130. {
  2131. return _lockUntilDate;
  2132. }
  2133. - (void)passcodeViewCloseButtonPressed:(id)sender
  2134. {
  2135. [self dismissViewControllerAnimated:YES completion:nil];
  2136. }
  2137. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2138. {
  2139. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2140. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2141. _lockUntilDate = nil;
  2142. _failedAttempts = 0;
  2143. aResultHandler(YES);
  2144. } else aResultHandler(NO);
  2145. } else aResultHandler(YES);
  2146. }
  2147. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2148. {
  2149. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2150. switch (aViewController.type) {
  2151. case BKPasscodeViewControllerCheckPasscodeType: {
  2152. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2153. // possiamo procedere alla prossima directory
  2154. [self performSegueDirectoryWithControlPasscode:false metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2155. // avviamo la sessione Passcode Lock con now
  2156. appDelegate.sessionePasscodeLock = [NSDate date];
  2157. }
  2158. // disattivazione lock cartella
  2159. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2160. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2161. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  2162. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2163. }
  2164. [self tableViewReloadData];
  2165. }
  2166. }
  2167. break;
  2168. default:
  2169. break;
  2170. }
  2171. }
  2172. - (void)comandoLockPassword
  2173. {
  2174. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2175. // se non è abilitato il Lock Passcode esci
  2176. if ([[CCUtility getBlockCode] length] == 0) {
  2177. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2178. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2179. [alertController addAction:okAction];
  2180. [self presentViewController:alertController animated:YES completion:nil];
  2181. return;
  2182. }
  2183. // se è richiesta la disattivazione si chiede la password
  2184. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2185. if (directory.lock) {
  2186. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2187. viewController.delegate = self;
  2188. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2189. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2190. viewController.inputViewTitlePassword = YES;
  2191. if ([CCUtility getSimplyBlockCode]) {
  2192. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2193. viewController.passcodeInputView.maximumLength = 6;
  2194. } else {
  2195. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2196. viewController.passcodeInputView.maximumLength = 64;
  2197. }
  2198. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2199. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2200. viewController.touchIDManager = touchIDManager;
  2201. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2202. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2203. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2204. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2205. [self presentViewController:navigationController animated:YES completion:nil];
  2206. return;
  2207. }
  2208. // ---------------- ACTIVATE PASSWORD
  2209. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  2210. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:self.metadata.fileID];
  2211. if ([self indexPathIsValid:indexPath])
  2212. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2213. } else {
  2214. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2215. }
  2216. }
  2217. #pragma mark -
  2218. #pragma --------------------------------------------------------------------------------------------
  2219. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2220. #pragma --------------------------------------------------------------------------------------------
  2221. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2222. {
  2223. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  2224. return NO;
  2225. // E2EE
  2226. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2227. return NO;
  2228. return YES;
  2229. }
  2230. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2231. {
  2232. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2233. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2234. return [self canOpenMenuAction:metadata];
  2235. }
  2236. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2237. {
  2238. }
  2239. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2240. {
  2241. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2242. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2243. if (direction == MGSwipeDirectionRightToLeft) {
  2244. [self actionDelete:indexPath];
  2245. }
  2246. if (direction == MGSwipeDirectionLeftToRight) {
  2247. if (self.metadata.favorite)
  2248. [self settingFavorite:self.metadata favorite:NO];
  2249. else
  2250. [self settingFavorite:self.metadata favorite:YES];
  2251. }
  2252. return YES;
  2253. }
  2254. - (void)actionDelete:(NSIndexPath *)indexPath
  2255. {
  2256. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2257. // Directory locked ?
  2258. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  2259. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2260. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2261. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2262. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2263. return;
  2264. }
  2265. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2266. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2267. [self performSelector:@selector(deleteFile) withObject:nil];
  2268. }]];
  2269. if (localFile) {
  2270. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2271. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2272. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  2273. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2274. }]];
  2275. }
  2276. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2277. }]];
  2278. alertController.popoverPresentationController.sourceView = self.tableView;
  2279. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2280. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2281. [alertController.view layoutIfNeeded];
  2282. [self presentViewController:alertController animated:YES completion:nil];
  2283. }
  2284. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2285. {
  2286. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2287. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2288. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2289. NSString *titoloLock, *titleFavorite;
  2290. if (self.metadata.favorite) {
  2291. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2292. } else {
  2293. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2294. }
  2295. if (self.metadata.directory) {
  2296. // calcolo lockServerUrl
  2297. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2298. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2299. if (directory.lock)
  2300. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2301. else
  2302. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2303. }
  2304. // ******************************************* AHKActionSheet *******************************************
  2305. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2306. actionSheet.animationDuration = 0.2;
  2307. actionSheet.buttonHeight = 50.0;
  2308. actionSheet.cancelButtonHeight = 50.0f;
  2309. actionSheet.separatorHeight = 5.0f;
  2310. actionSheet.automaticallyTintButtonImages = @(NO);
  2311. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2312. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2313. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2314. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2315. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2316. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2317. // ******************************************* DIRECTORY *******************************************
  2318. if (self.metadata.directory) {
  2319. BOOL lockDirectory = NO;
  2320. BOOL isOffline = NO;
  2321. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2322. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2323. // Directory bloccata ?
  2324. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2325. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2326. if (directory.offline) isOffline = YES;
  2327. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2328. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2329. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2330. height:50.0
  2331. type:AHKActionSheetButtonTypeDisabled
  2332. handler:nil
  2333. ];
  2334. [actionSheet addButtonWithTitle: titleFavorite
  2335. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2336. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2337. height: 50.0
  2338. type: AHKActionSheetButtonTypeDefault
  2339. handler: ^(AHKActionSheet *as) {
  2340. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2341. else [self settingFavorite:self.metadata favorite:YES];
  2342. }];
  2343. if (!lockDirectory && !isFolderEncrypted) {
  2344. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2345. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2346. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2347. height:50.0
  2348. type:AHKActionSheetButtonTypeDefault
  2349. handler:^(AHKActionSheet *as) {
  2350. [appDelegate.activeMain readShareWithAccount:appDelegate.activeAccount openWindow:YES metadata:self.metadata];
  2351. }];
  2352. }
  2353. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2354. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2355. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2356. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2357. height:50.0
  2358. type:AHKActionSheetButtonTypeDefault
  2359. handler:^(AHKActionSheet *as) {
  2360. __weak __typeof(UIAlertController) *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2361. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2362. textField.text = self.metadata.fileNameView;
  2363. textField.delegate = self;
  2364. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2365. }];
  2366. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2367. NSLog(@"[LOG] Cancel action");
  2368. }];
  2369. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2370. UITextField *fileName = alertController.textFields.firstObject;
  2371. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2372. }];
  2373. okAction.enabled = NO;
  2374. [alertController addAction:cancelAction];
  2375. [alertController addAction:okAction];
  2376. [self presentViewController:alertController animated:YES completion:nil];
  2377. }];
  2378. }
  2379. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2380. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2381. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2382. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2383. height:50.0
  2384. type:AHKActionSheetButtonTypeDefault
  2385. handler:^(AHKActionSheet *as) {
  2386. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2387. }];
  2388. }
  2389. if (!isFolderEncrypted) {
  2390. NSString *title;
  2391. if (isOffline) {
  2392. title = NSLocalizedString(@"_remove_available_offline_", nil);
  2393. } else {
  2394. title = NSLocalizedString(@"_set_available_offline_", nil);
  2395. }
  2396. [actionSheet addButtonWithTitle:title
  2397. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2398. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2399. height:50.0
  2400. type:AHKActionSheetButtonTypeDefault
  2401. handler:^(AHKActionSheet *as) {
  2402. if (isOffline) {
  2403. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:false account:appDelegate.activeAccount];
  2404. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2405. } else {
  2406. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true account:appDelegate.activeAccount];
  2407. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  2408. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2409. }
  2410. }];
  2411. }
  2412. [actionSheet addButtonWithTitle:titoloLock
  2413. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2414. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2415. height:50.0
  2416. type:AHKActionSheetButtonTypeDefault
  2417. handler:^(AHKActionSheet *as) {
  2418. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2419. }];
  2420. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2421. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2422. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] width:50 height:50 color:[NCBrandColor sharedInstance].icon]
  2423. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2424. height:50.0
  2425. type:AHKActionSheetButtonTypeDefault
  2426. handler:^(AHKActionSheet *as) {
  2427. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2428. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] fileID:self.metadata.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2429. dispatch_async(dispatch_get_main_queue(), ^{
  2430. if (error) {
  2431. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2432. } else {
  2433. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2434. [self readFolder:self.serverUrl];
  2435. }
  2436. });
  2437. });
  2438. }];
  2439. }
  2440. if (self.metadata.e2eEncrypted && !_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2441. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2442. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] width:50 height:50 color:[NCBrandColor sharedInstance].icon]
  2443. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2444. height:50.0
  2445. type:AHKActionSheetButtonTypeDefault
  2446. handler:^(AHKActionSheet *as) {
  2447. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2448. NSError *error = [[NCNetworkingEndToEnd sharedManager] deletemarkEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] fileID:self.metadata.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2449. dispatch_async(dispatch_get_main_queue(), ^{
  2450. if (error) {
  2451. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2452. } else {
  2453. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2454. [self readFolder:self.serverUrl];
  2455. }
  2456. });
  2457. });
  2458. }];
  2459. }
  2460. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2461. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor redColor]]
  2462. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2463. height:50.0
  2464. type:AHKActionSheetButtonTypeDestructive
  2465. handler:^(AHKActionSheet *as) {
  2466. [self actionDelete:indexPath];
  2467. }];
  2468. [actionSheet show];
  2469. }
  2470. // ******************************************* FILE *******************************************
  2471. if (!self.metadata.directory) {
  2472. UIImage *iconHeader;
  2473. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2474. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]])
  2475. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]];
  2476. else
  2477. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2478. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2479. image: iconHeader
  2480. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2481. height: 50.0
  2482. type: AHKActionSheetButtonTypeDisabled
  2483. handler: nil
  2484. ];
  2485. [actionSheet addButtonWithTitle: titleFavorite
  2486. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2487. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2488. height: 50.0
  2489. type: AHKActionSheetButtonTypeDefault
  2490. handler: ^(AHKActionSheet *as) {
  2491. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2492. else [self settingFavorite:self.metadata favorite:YES];
  2493. }];
  2494. if (!_metadataFolder.e2eEncrypted) {
  2495. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2496. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2497. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2498. height: 50.0
  2499. type:AHKActionSheetButtonTypeDefault
  2500. handler:^(AHKActionSheet *as) {
  2501. [appDelegate.activeMain readShareWithAccount:appDelegate.activeAccount openWindow:YES metadata:self.metadata];
  2502. }];
  2503. }
  2504. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  2505. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2506. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2507. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2508. height: 50.0
  2509. type:AHKActionSheetButtonTypeDefault
  2510. handler:^(AHKActionSheet *as) {
  2511. [self performSelector:@selector(openinFile:) withObject:nil];
  2512. }];
  2513. }
  2514. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2515. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2516. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2517. height: 50.0
  2518. type:AHKActionSheetButtonTypeDefault
  2519. handler:^(AHKActionSheet *as) {
  2520. __weak __typeof(UIAlertController) *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2521. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2522. textField.text = self.metadata.fileNameView;
  2523. textField.delegate = self;
  2524. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2525. }];
  2526. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2527. NSLog(@"[LOG] Cancel action");
  2528. }];
  2529. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2530. UITextField *fileName = alertController.textFields.firstObject;
  2531. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2532. }];
  2533. okAction.enabled = NO;
  2534. [alertController addAction:cancelAction];
  2535. [alertController addAction:okAction];
  2536. [self presentViewController:alertController animated:YES completion:nil];
  2537. }];
  2538. if (!_metadataFolder.e2eEncrypted) {
  2539. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2540. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2541. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2542. height:50.0
  2543. type:AHKActionSheetButtonTypeDefault
  2544. handler:^(AHKActionSheet *as) {
  2545. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2546. }];
  2547. }
  2548. if ([NCUtility.sharedInstance isEditImage:self.metadata.fileNameView] != nil && !_metadataFolder.e2eEncrypted && self.metadata.status == k_metadataStatusNormal) {
  2549. [actionSheet addButtonWithTitle:NSLocalizedString(@"_modify_photo_", nil)
  2550. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"modifyPhoto"] width:50 height:50 color:[NCBrandColor sharedInstance].icon]
  2551. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2552. height:50.0
  2553. type:AHKActionSheetButtonTypeDefault
  2554. handler:^(AHKActionSheet *as) {
  2555. self.metadata.session = k_download_session;
  2556. self.metadata.sessionError = @"";
  2557. self.metadata.sessionSelector = selectorDownloadEditPhoto;
  2558. self.metadata.status = k_metadataStatusWaitDownload;
  2559. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2560. [appDelegate startLoadAutoDownloadUpload];
  2561. }];
  2562. }
  2563. if (!_metadataFolder.e2eEncrypted) {
  2564. NSString *title;
  2565. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadata.fileID]];
  2566. if (localFile == nil || localFile.offline == false) { title = NSLocalizedString(@"_set_available_offline_", nil); }
  2567. else { title = NSLocalizedString(@"_remove_available_offline_", nil); }
  2568. [actionSheet addButtonWithTitle:title
  2569. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2570. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2571. height:50.0
  2572. type:AHKActionSheetButtonTypeDefault
  2573. handler:^(AHKActionSheet *as) {
  2574. if (localFile == nil || ![CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2575. self.metadata.session = k_download_session;
  2576. self.metadata.sessionError = @"";
  2577. self.metadata.sessionSelector = selectorLoadOffline;
  2578. self.metadata.status = k_metadataStatusWaitDownload;
  2579. // Add Metadata for Download
  2580. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2581. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2582. [appDelegate startLoadAutoDownloadUpload];
  2583. } else if (localFile.offline == false) {
  2584. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:true];
  2585. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2586. } else {
  2587. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:false];
  2588. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2589. }
  2590. }];
  2591. }
  2592. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2593. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor redColor]]
  2594. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2595. height:50.0
  2596. type:AHKActionSheetButtonTypeDestructive
  2597. handler:^(AHKActionSheet *as) {
  2598. [self actionDelete:indexPath];
  2599. }];
  2600. [actionSheet show];
  2601. }
  2602. }
  2603. #pragma --------------------------------------------------------------------------------------------
  2604. #pragma mark - ==== Datasource ====
  2605. #pragma --------------------------------------------------------------------------------------------
  2606. - (void)clearDateReadDataSource:(NSNotification *)notification
  2607. {
  2608. _dateReadDataSource = Nil;
  2609. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2610. }
  2611. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID action:(NSInteger)action
  2612. {
  2613. // test
  2614. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2615. return;
  2616. // Search Mode
  2617. if (_isSearchMode) {
  2618. // Create metadatas
  2619. NSMutableArray *metadatas = [NSMutableArray new];
  2620. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2621. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", resultMetadata.fileID]];
  2622. if (metadata) {
  2623. [metadatas addObject:metadata];
  2624. }
  2625. }
  2626. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  2627. [self tableViewReloadData];
  2628. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2629. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2630. _noFilesSearchDescription = @"";
  2631. }
  2632. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2633. _noFilesSearchTitle = @"";
  2634. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2635. }
  2636. [self.tableView reloadEmptyDataSet];
  2637. return;
  2638. }
  2639. // Se non siamo nella dir appropriata esci
  2640. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2641. return;
  2642. }
  2643. // Controllo data lettura Data Source
  2644. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2645. if (tableDirectory == nil) {
  2646. return;
  2647. }
  2648. // Get MetadataFolder
  2649. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2650. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  2651. else
  2652. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  2653. // Remove optimization for encrypted directory
  2654. if (_metadataFolder.e2eEncrypted)
  2655. _dateReadDataSource = nil;
  2656. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2657. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2658. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2659. _dateReadDataSource = [NSDate date];
  2660. // Data Source
  2661. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2662. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2663. dispatch_async(dispatch_get_main_queue(), ^{
  2664. sectionDataSource = sectionDataSourceTemp;
  2665. [self tableViewReloadData];
  2666. });
  2667. });
  2668. } else {
  2669. [self tableViewReloadData];
  2670. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2671. }
  2672. // BLINK
  2673. if (self.blinkFileNamePath != nil) {
  2674. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2675. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  2676. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  2677. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  2678. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  2679. for (NSString *key in sectionDataSource.fileIDIndexPath) {
  2680. if ([key isEqualToString:metadata.fileID]) {
  2681. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:key];
  2682. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  2683. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2684. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  2685. if (cell) {
  2686. self.blinkFileNamePath = nil;
  2687. [[NCUtility sharedInstance] blinkWithCell:cell];
  2688. }
  2689. });
  2690. }
  2691. }
  2692. }
  2693. }
  2694. });
  2695. }
  2696. }
  2697. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2698. {
  2699. // test
  2700. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2701. return nil;
  2702. }
  2703. // get auto upload folder
  2704. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2705. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2706. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2707. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND status != %i", appDelegate.activeAccount, serverUrl, k_metadataStatusHide] sorted:nil ascending:NO];
  2708. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  2709. if (withReloadData) {
  2710. sectionDataSource = sectionDataSourceTemp;
  2711. [self tableViewReloadData];
  2712. }
  2713. return sectionDataSourceTemp;
  2714. }
  2715. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2716. {
  2717. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2718. if (selectedRows.count > 0) {
  2719. for (NSIndexPath *selectionIndex in selectedRows) {
  2720. NSString *fileID = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2721. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  2722. [metadatas addObject:metadata];
  2723. }
  2724. }
  2725. return metadatas;
  2726. }
  2727. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2728. {
  2729. NSInteger totSections =[sectionDataSource.sections count] ;
  2730. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2731. return nil;
  2732. }
  2733. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2734. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2735. }
  2736. #pragma --------------------------------------------------------------------------------------------
  2737. #pragma mark - ==== Table ====
  2738. #pragma --------------------------------------------------------------------------------------------
  2739. - (void)tableViewSelect:(BOOL)edit
  2740. {
  2741. // chiudiamo eventuali swipe aperti
  2742. if (edit)
  2743. [self.tableView setEditing:NO animated:NO];
  2744. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2745. [self.tableView setEditing:edit animated:YES];
  2746. _isSelectedMode = edit;
  2747. if (edit)
  2748. [self setUINavigationBarSelected];
  2749. else
  2750. [self setUINavigationBarDefault];
  2751. [_selectedFileIDsMetadatas removeAllObjects];
  2752. [self setTitle];
  2753. }
  2754. - (void)tableViewReloadData
  2755. {
  2756. // store selected cells before relod
  2757. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2758. // reload table view
  2759. [self.tableView reloadData];
  2760. // selected cells stored
  2761. for (NSIndexPath *path in indexPaths)
  2762. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2763. [self setTableViewFooter];
  2764. if (self.tableView.editing)
  2765. [self setTitle];
  2766. [self.tableView reloadEmptyDataSet];
  2767. }
  2768. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2769. {
  2770. if (tableView.editing == 1) {
  2771. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2772. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2773. return NO;
  2774. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2775. return NO;
  2776. else
  2777. return YES;
  2778. } else {
  2779. [_selectedFileIDsMetadatas removeAllObjects];
  2780. }
  2781. return YES;
  2782. }
  2783. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2784. {
  2785. return 60;
  2786. }
  2787. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2788. {
  2789. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2790. }
  2791. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2792. {
  2793. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2794. }
  2795. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2796. {
  2797. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2798. NSString *sectionTitle = [sections objectAtIndex:section];
  2799. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2800. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2801. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2802. return 20.f;
  2803. }
  2804. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2805. {
  2806. float shift;
  2807. UIVisualEffectView *visualEffectView;
  2808. NSString *titleSection;
  2809. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2810. return nil;
  2811. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2812. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2813. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2814. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2815. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2816. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2817. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2818. else titleSection = NSLocalizedString(titleSection,nil);
  2819. // Format title
  2820. NSString *currentDevice = [CCUtility currentDevice];
  2821. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  2822. visualEffectView = [[UIVisualEffectView alloc] init];
  2823. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  2824. } else {
  2825. UIVisualEffect *blurEffect;
  2826. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2827. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2828. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  2829. }
  2830. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2831. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2832. shift = - 35;
  2833. else
  2834. shift = - 20;
  2835. } else shift = - 10;
  2836. // Title
  2837. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2838. titleLabel.backgroundColor = [UIColor clearColor];
  2839. titleLabel.textColor = [UIColor blackColor];
  2840. titleLabel.font = [UIFont systemFontOfSize:12];
  2841. titleLabel.textAlignment = NSTextAlignmentLeft;
  2842. titleLabel.text = titleSection;
  2843. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2844. [visualEffectView.contentView addSubview:titleLabel];
  2845. // Elements
  2846. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2847. elementLabel.backgroundColor = [UIColor clearColor];
  2848. elementLabel.textColor = [UIColor blackColor];;
  2849. elementLabel.font = [UIFont systemFontOfSize:12];
  2850. elementLabel.textAlignment = NSTextAlignmentRight;
  2851. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2852. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2853. NSUInteger rowsCount = [metadatas count];
  2854. if (rowsCount == 0) return nil;
  2855. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2856. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2857. [visualEffectView.contentView addSubview:elementLabel];
  2858. return visualEffectView;
  2859. }
  2860. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2861. {
  2862. return [sectionDataSource.sections indexOfObject:title];
  2863. }
  2864. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2865. {
  2866. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2867. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2868. else
  2869. return nil;
  2870. }
  2871. /*
  2872. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2873. {
  2874. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2875. }
  2876. }
  2877. */
  2878. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2879. {
  2880. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2881. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  2882. return [CCCellMain new];
  2883. }
  2884. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory];
  2885. // NORMAL - > MAIN
  2886. if ([cell isKindOfClass:[CCCellMain class]]) {
  2887. NSString *shareLink = [appDelegate.sharesLink objectForKey:[metadata.serverUrl stringByAppendingString:metadata.fileName]];
  2888. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[metadata.serverUrl stringByAppendingString:metadata.fileName]];
  2889. BOOL isShare = false;
  2890. BOOL isMounted = false;
  2891. if (_metadataFolder) {
  2892. isShare = [metadata.permissions containsString:k_permission_shared] && ![_metadataFolder.permissions containsString:k_permission_shared];
  2893. isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_metadataFolder.permissions containsString:k_permission_mounted];
  2894. }
  2895. // Share add Tap
  2896. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  2897. if (isShare || isMounted) {
  2898. // Shared with you
  2899. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  2900. [tap setNumberOfTapsRequired:1];
  2901. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  2902. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  2903. } else if (shareLink != nil || shareUserAndGroup != nil) {
  2904. // You share
  2905. if (metadata.directory) {
  2906. ((CCCellMain *)cell).shared.userInteractionEnabled = NO;
  2907. } else {
  2908. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2909. [tap setNumberOfTapsRequired:1];
  2910. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  2911. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  2912. }
  2913. }
  2914. }
  2915. // More
  2916. if ([self canOpenMenuAction:metadata]) {
  2917. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2918. [tapMore setNumberOfTapsRequired:1];
  2919. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2920. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2921. }
  2922. // MGSwipeButton
  2923. ((CCCellMain *)cell).delegate = self;
  2924. // LEFT
  2925. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  2926. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2927. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2928. //centerIconOverText
  2929. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2930. [favoriteButton centerIconOverText];
  2931. // RIGHT
  2932. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  2933. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2934. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2935. //centerIconOverText
  2936. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2937. [deleteButton centerIconOverText];
  2938. }
  2939. // TRANSFER
  2940. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2941. // gesture Transfer
  2942. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  2943. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  2944. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  2945. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  2946. }
  2947. return cell;
  2948. }
  2949. - (void)setTableViewFooter
  2950. {
  2951. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2952. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2953. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2954. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2955. UIFont *appFont = [UIFont systemFontOfSize:12];
  2956. footerLabel.font = appFont;
  2957. footerLabel.textColor = [UIColor grayColor];
  2958. footerLabel.backgroundColor = [UIColor clearColor];
  2959. footerLabel.textAlignment = NSTextAlignmentCenter;
  2960. NSString *folders;
  2961. NSString *files;
  2962. NSString *footerText;
  2963. if (sectionDataSource.directories > 1) {
  2964. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2965. } else if (sectionDataSource.directories == 1){
  2966. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2967. } else {
  2968. folders = @"";
  2969. }
  2970. if (sectionDataSource.files > 1) {
  2971. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2972. } else if (sectionDataSource.files == 1){
  2973. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2974. } else {
  2975. files = @"";
  2976. }
  2977. if ([folders isEqualToString:@""]) {
  2978. footerText = files;
  2979. } else if ([files isEqualToString:@""]) {
  2980. footerText = folders;
  2981. } else {
  2982. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2983. }
  2984. footerLabel.text = footerText;
  2985. [footerView addSubview:footerLabel];
  2986. [self.tableView setTableFooterView:footerView];
  2987. }
  2988. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2989. {
  2990. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2991. // settiamo il record file.
  2992. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2993. if (!self.metadata)
  2994. return;
  2995. // se non può essere selezionata deseleziona
  2996. if ([cell isEditing] == NO)
  2997. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2998. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2999. if (self.tableView.editing) {
  3000. [_selectedFileIDsMetadatas setObject:self.metadata forKey:self.metadata.fileID];
  3001. [self setTitle];
  3002. return;
  3003. }
  3004. // se è in corso una sessione
  3005. if (self.metadata.status != k_metadataStatusNormal)
  3006. return;
  3007. // file
  3008. if (self.metadata.directory == NO) {
  3009. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3010. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  3011. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName fileID:self.metadata.fileID serverUrl:self.metadata.serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3012. } else {
  3013. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3014. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3015. } else {
  3016. 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) {
  3017. [self shouldPerformSegue:self.metadata];
  3018. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCViewerRichdocument sharedInstance] isRichDocument:self.metadata]) {
  3019. [self shouldPerformSegue:self.metadata];
  3020. } else {
  3021. self.metadata.session = k_download_session;
  3022. self.metadata.sessionError = @"";
  3023. self.metadata.sessionSelector = selectorLoadFileView;
  3024. self.metadata.status = k_metadataStatusWaitDownload;
  3025. // Add Metadata for Download
  3026. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  3027. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  3028. [appDelegate startLoadAutoDownloadUpload];
  3029. }
  3030. }
  3031. }
  3032. }
  3033. if (self.metadata.directory) {
  3034. [self performSegueDirectoryWithControlPasscode:true metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  3035. }
  3036. }
  3037. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3038. {
  3039. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3040. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3041. [self setTitle];
  3042. }
  3043. - (void)didSelectAll
  3044. {
  3045. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3046. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3047. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3048. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3049. [_selectedFileIDsMetadatas setObject:metadata forKey:metadata.fileID];
  3050. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3051. }
  3052. }
  3053. [self setTitle];
  3054. }
  3055. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3056. {
  3057. if (!indexPath)
  3058. return NO;
  3059. NSInteger section = indexPath.section;
  3060. NSInteger row = indexPath.row;
  3061. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3062. if (section > lastSectionIndex || lastSectionIndex < 0)
  3063. return NO;
  3064. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3065. if (rowCount < 0)
  3066. return NO;
  3067. return row <= rowCount;
  3068. }
  3069. #pragma --------------------------------------------------------------------------------------------
  3070. #pragma mark ===== Navigation ====
  3071. #pragma --------------------------------------------------------------------------------------------
  3072. - (void)shouldPerformSegue:(tableMetadata *)metadata
  3073. {
  3074. // if background return
  3075. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3076. if (self.view.window == NO)
  3077. return;
  3078. // Collapsed ma siamo già in detail esci
  3079. if (self.splitViewController.isCollapsed)
  3080. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3081. // Metadata for push detail
  3082. self.metadataForPushDetail = metadata;
  3083. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3084. }
  3085. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3086. {
  3087. id viewController = segue.destinationViewController;
  3088. tableMetadata *metadata;
  3089. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3090. UINavigationController *nav = viewController;
  3091. _detailViewController = (CCDetail *)nav.topViewController;
  3092. } else {
  3093. _detailViewController = segue.destinationViewController;
  3094. }
  3095. NSMutableArray *photoDataSource = [NSMutableArray new];
  3096. if ([sender isKindOfClass:[tableMetadata class]]) {
  3097. metadata = sender;
  3098. [photoDataSource addObject:sender];
  3099. } else {
  3100. metadata = self.metadataForPushDetail;
  3101. for (NSString *fileID in sectionDataSource.allFileID) {
  3102. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3103. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3104. [photoDataSource addObject:metadata];
  3105. }
  3106. }
  3107. _detailViewController.metadataDetail = metadata;
  3108. _detailViewController.photoDataSource = photoDataSource;
  3109. _detailViewController.dateFilterQuery = nil;
  3110. [_detailViewController setTitle:metadata.fileNameView];
  3111. }
  3112. // can i go to next viewcontroller
  3113. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode metadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  3114. {
  3115. NSString *nomeDir;
  3116. if (self.tableView.editing == NO) {
  3117. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  3118. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadata.account, lockServerUrl]];
  3119. // 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
  3120. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3121. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3122. viewController.delegate = self;
  3123. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3124. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3125. viewController.inputViewTitlePassword = YES;
  3126. if ([CCUtility getSimplyBlockCode]) {
  3127. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3128. viewController.passcodeInputView.maximumLength = 6;
  3129. } else {
  3130. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3131. viewController.passcodeInputView.maximumLength = 64;
  3132. }
  3133. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3134. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3135. viewController.touchIDManager = touchIDManager;
  3136. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3137. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3138. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3139. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3140. [self presentViewController:navController animated:YES completion:nil];
  3141. return;
  3142. }
  3143. // E2EE Check enable
  3144. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3145. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3146. return;
  3147. }
  3148. nomeDir = metadata.fileName;
  3149. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  3150. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3151. if (!viewController) {
  3152. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3153. viewController.serverUrl = serverUrlPush;
  3154. viewController.titleMain = metadata.fileName;
  3155. viewController.blinkFileNamePath = blinkFileNamePath;
  3156. // save self
  3157. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3158. [self.navigationController pushViewController:viewController animated:YES];
  3159. } else {
  3160. if (viewController.isViewLoaded) {
  3161. viewController.titleMain = metadata.fileName;
  3162. viewController.blinkFileNamePath = blinkFileNamePath;
  3163. // Fix : Application tried to present modally an active controller
  3164. if ([self.navigationController isBeingPresented]) {
  3165. // being presented
  3166. } else if ([self.navigationController isMovingToParentViewController]) {
  3167. // being pushed
  3168. } else {
  3169. [self.navigationController pushViewController:viewController animated:YES];
  3170. }
  3171. }
  3172. }
  3173. }
  3174. }
  3175. @end