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