From cc85c944e7206608105a46c6fd8bcfaa6d00228f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 21:20:44 -0500 Subject: expose Shares --- src/slskd/Shares/SharedFileCache.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index ac996fa6..1b35aacf 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -37,6 +37,11 @@ namespace slskd.Shares /// public interface ISharedFileCache { + /// + /// Gets the list of shares. + /// + public List Shares { get; } + /// /// Gets the cache state monitor. /// @@ -100,12 +105,16 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor => State; + /// + /// Gets the list of shares. + /// + public List Shares { get; private set; } + private IManagedState State { get; } = new ManagedState(); private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } private Dictionary MaskedFiles { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } - private List Shares { get; set; } private SqliteConnection SQLite { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private ISoulseekFileFactory SoulseekFileFactory { get; } -- cgit v1.2.3 From c04b3aa5243213161ed20a9d65b434de37fdab4e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:28:55 -0500 Subject: add Id to Share --- src/slskd/Shares/Domain/Share.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/Domain/Share.cs b/src/slskd/Shares/Domain/Share.cs index 890c8565..464ab074 100644 --- a/src/slskd/Shares/Domain/Share.cs +++ b/src/slskd/Shares/Domain/Share.cs @@ -63,8 +63,11 @@ namespace slskd.Shares var aliasedSegment = LocalPath[(parent.Length + 1)..]; RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias); + + Id = Compute.Sha1Hash(RemotePath); } + public string Id { get; init; } public string Alias { get; init; } public bool IsExcluded { get; init; } public string LocalPath { get; init; } -- cgit v1.2.3 From 7473491617e71a9e33cde36c5b9d49c77fabc973 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:29:11 -0500 Subject: stub ShareService --- src/slskd/Shares/ShareService.cs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/slskd/Shares/ShareService.cs (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs new file mode 100644 index 00000000..2e4e7c95 --- /dev/null +++ b/src/slskd/Shares/ShareService.cs @@ -0,0 +1,27 @@ +namespace slskd.Shares +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public interface IShareService + { + ISharedFileCache Cache { get; } + IReadOnlyList List(Func expression = null); + } + + public class ShareService : IShareService + { + public ShareService(ISharedFileCache sharedFileCache) + { + Cache = sharedFileCache; + } + + public ISharedFileCache Cache { get; } + + public IReadOnlyList List(Func expression = null) + { + return Cache.Shares.Where(expression).ToList().AsReadOnly(); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 28ab70b9aeb3a0060e3ca76b4faae586e724fd74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:29:22 -0500 Subject: rough in SharesController --- .../Shares/API/Controllers/SharesController.cs | 90 ++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/slskd/Shares/API/Controllers/SharesController.cs (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs new file mode 100644 index 00000000..06a02de3 --- /dev/null +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -0,0 +1,90 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares.API +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Shares. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SharesController : ControllerBase + { + public SharesController(IShareService shareService) + { + Shares = shareService; + } + + private IShareService Shares { get; } + + [HttpGet("")] + public IActionResult List() + { + return Ok(Shares.Cache.Shares); + } + + [HttpGet("{id}")] + public IActionResult Get(string id) + { + var share = Ok(Shares.Cache.Shares.FirstOrDefault(share => share.Id == id)); + + if (share == default) + { + return NotFound(); + } + + return share; + } + + [HttpGet("contents")] + public IActionResult BrowseAll() + { + return Ok(Shares.Cache.Browse()); + } + + [HttpGet("{id}/contents")] + public IActionResult BrowseShare(string id) + { + var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + + if (share == default) + { + return NotFound(); + } + + var browse = Shares.Cache.Browse(); + + foreach (var dir in browse) + { + Console.WriteLine($"{dir.Name} ?? ${share.RemotePath}"); + } + + var contents = Shares.Cache.Browse().Where(directory => directory.Name.StartsWith(share.RemotePath)); + + return Ok(contents); + } + } +} -- cgit v1.2.3 From 6bf6f6c1aa199f0a9878c7819606bed3cbccf312 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:29:38 -0500 Subject: add ShareService to DI --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 40e6e72d..4643daa0 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -454,6 +454,7 @@ namespace slskd services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 378df649f87732a3adaae3b0402ff71360c8a969 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:30:00 -0500 Subject: rename 'page' css class to 'view' to avoid conflict --- src/web/src/components/App.css | 4 ++-- src/web/src/components/App.js | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index e0935163..82e74b71 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -120,7 +120,7 @@ body { background-color: transparent !important; } -.page { +.view { padding-left: 15px; padding-right: 15px; max-width: 1200px !important; @@ -128,6 +128,6 @@ body { margin-right: auto !important; } -.page:last-child { +.view:last-child { margin-bottom: 17px; } \ No newline at end of file diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 09039442..76881c93 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -260,7 +260,7 @@ class App extends Component { - this.withTokenCheck(
+ this.withTokenCheck(
this.withTokenCheck()}/> - this.withTokenCheck(
) + this.withTokenCheck(
) }/> - this.withTokenCheck(
+ this.withTokenCheck(
) }/> -- cgit v1.2.3 From b34d1d9dfbe379d2f1397b0d2503ec73c4fd9a0d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:30:16 -0500 Subject: rough in Share components --- src/web/src/components/System/Shares/Share.js | 25 ++++++++ src/web/src/components/System/Shares/index.js | 82 +++++++++++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 src/web/src/components/System/Shares/Share.js create mode 100644 src/web/src/components/System/Shares/index.js (limited to 'src') diff --git a/src/web/src/components/System/Shares/Share.js b/src/web/src/components/System/Shares/Share.js new file mode 100644 index 00000000..eadcd07b --- /dev/null +++ b/src/web/src/components/System/Shares/Share.js @@ -0,0 +1,25 @@ +import React from 'react'; + +import { + Item, +} from 'semantic-ui-react'; + +const Share = ({ share = {}, onBrowse } = {}) => { + const { id, remotePath, localPath, mask, alias, isExcluded } = share; + + return ( + + + {remotePath} + Description + +
+            {JSON.stringify({ id, localPath, mask, alias, isExcluded }, null, 2)}
+          
+
+
+
+ ); +}; + +export default Share; \ No newline at end of file diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js new file mode 100644 index 00000000..5f3ae971 --- /dev/null +++ b/src/web/src/components/System/Shares/index.js @@ -0,0 +1,82 @@ +import React, { useState, useEffect } from 'react'; +import { toast } from 'react-toastify'; + +import * as sharesLib from '../../../lib/shares'; +import { LoaderSegment } from '../../Shared'; +import Share from './Share'; + +import { + Modal, + Button, +} from 'semantic-ui-react'; + +const Index = () => { + const [loading, setLoading] = useState(true); + const [shares, setShares] = useState([]); + const [everything, setEverything] = useState(); + const [modal, setModal] = useState(false); + + useEffect(() => { + getAll(); + }, []); + + const getAll = async () => { + try { + setLoading(true); + setShares(await sharesLib.getAll()); + setLoading(false); + } catch (error) { + console.error(error); + toast.error(error?.response?.data ?? error?.message ?? error); + } finally { + setLoading(false); + } + }; + + const browse = async ({ id }) => { + setEverything(await sharesLib.browse({ id })); + setModal(true); + }; + + if (loading) { + return LoaderSegment; + } + + return ( + <> +
+
    + {shares.map(share => ( + browse({ id: share.id })}/> + ))} +
+
+          {JSON.stringify(everything, null, 2)}
+        
+
+ setModal(false)} + style={{ color: 'red' }} + > + Delete Your Account + +
+            {JSON.stringify(everything, null, 2)}
+          
+
+ + + + +
+ + ); +}; + +export default Index; \ No newline at end of file -- cgit v1.2.3 From 4c4461bc54cbad68c3ed20ba7faee9625b77c98c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:30:27 -0500 Subject: add shares lib --- src/web/src/lib/shares.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/web/src/lib/shares.js (limited to 'src') diff --git a/src/web/src/lib/shares.js b/src/web/src/lib/shares.js new file mode 100644 index 00000000..34fab679 --- /dev/null +++ b/src/web/src/lib/shares.js @@ -0,0 +1,19 @@ +import api from './api'; + +export const getAll = async () => { + return (await api.get('/shares')).data; +}; + +export const get = async ({ id } = {}) => { + if (!id) throw new Error('unable to get share: id is missing'); + return (await api.get(`/shares/${id}`)).data; +}; + +export const browseAll = async () => { + return (await api.get('/shares/contents')).data; +}; + +export const browse = async ({ id } = {}) => { + if (!id) throw new Error('unable to get share contents: id is missing'); + return (await api.get(`/shares/${id}/contents`)).data; +}; \ No newline at end of file -- cgit v1.2.3 From c16e7614b6a37d542f838459850e599e6eb6dcf3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:30:38 -0500 Subject: add Shares system tab --- src/web/src/components/System/System.js | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js index 9310777f..8955b212 100644 --- a/src/web/src/components/System/System.js +++ b/src/web/src/components/System/System.js @@ -8,6 +8,7 @@ import './System.css'; import Info from './Info'; import Logs from './Logs'; import Options from './Options'; +import Shares from './Shares'; const System = ({ state = {}, options = {} }) => { const { params: { tab }, ...route } = useRouteMatch(); @@ -19,6 +20,9 @@ const System = ({ state = {}, options = {} }) => { route: 'options', menuItem: 'Options', render: () => , }, + { + route: 'shares', menuItem: 'Shares', render: () => , + }, { route: 'logs', menuItem: 'Logs', render: () => }, ]; -- cgit v1.2.3 From 592660a5ca6f88375f5ec7b7543b110bbf8479ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 16:51:38 -0500 Subject: add an endpoint to get configuration debug view --- src/slskd/Core/API/Controllers/OptionsController.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs index 062de8f7..b0856ed3 100644 --- a/src/slskd/Core/API/Controllers/OptionsController.cs +++ b/src/slskd/Core/API/Controllers/OptionsController.cs @@ -21,8 +21,10 @@ namespace slskd.Core.API { using System; using System.IO; + using System.Reflection; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.Configuration; using Serilog; using slskd.Validation; using IOFile = System.IO.File; @@ -74,6 +76,24 @@ namespace slskd.Core.API return Ok(OptionsAtStartup.Redact()); } + /// + /// Gets the debug view of the current application options. + /// + /// + [HttpGet] + [Route("debug")] + [Authorize] + [ProducesResponseType(typeof(string), 200)] + public IActionResult Debug() + { + // retrieve the IConfigurationRoot instance with reflection to avoid + // exposing it as a public member of Program. + var property = typeof(Program).GetProperty("Configuration", BindingFlags.NonPublic | BindingFlags.Static); + var configurationRoot = (IConfigurationRoot)property.GetValue(null, null); + + return Ok(configurationRoot.GetDebugView()); + } + [HttpGet] [Authorize] [Route("yaml/location")] -- cgit v1.2.3 From 0974475adc31aa5b4179c427ba7670fc96874481 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 16:51:49 -0500 Subject: add a function to fetch options debug --- src/web/src/lib/options.js | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/web/src/lib/options.js b/src/web/src/lib/options.js index 20f8dd0a..32e48534 100644 --- a/src/web/src/lib/options.js +++ b/src/web/src/lib/options.js @@ -4,6 +4,10 @@ export const getCurrent = async () => { return (await api.get('/options')).data; }; +export const getCurrentDebugView = async () => { + return (await api.get('/options/debug')).data; +}; + export const getYaml = async () => { return (await api.get('/options/yaml')).data; }; -- cgit v1.2.3 From 59623e20ac93565bf377457f70cff87fc4b6e459 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 16:52:36 -0500 Subject: refactor System components --- src/web/src/components/System/Info.js | 70 -------------- src/web/src/components/System/Info/index.js | 74 +++++++++++++++ src/web/src/components/System/Logs.js | 83 ----------------- .../src/components/System/Options/DebugModal.js | 67 ++++++++++++++ src/web/src/components/System/Options/Edit.js | 87 ------------------ src/web/src/components/System/Options/EditModal.js | 101 +++++++++++++++++++++ src/web/src/components/System/Options/View.js | 30 ------ src/web/src/components/System/Options/index.js | 74 +++++++++++++-- src/web/src/components/System/System.css | 36 +++----- src/web/src/components/System/System.js | 37 +++++++- 10 files changed, 355 insertions(+), 304 deletions(-) delete mode 100644 src/web/src/components/System/Info.js create mode 100644 src/web/src/components/System/Info/index.js delete mode 100644 src/web/src/components/System/Logs.js create mode 100644 src/web/src/components/System/Options/DebugModal.js delete mode 100644 src/web/src/components/System/Options/Edit.js create mode 100644 src/web/src/components/System/Options/EditModal.js delete mode 100644 src/web/src/components/System/Options/View.js (limited to 'src') diff --git a/src/web/src/components/System/Info.js b/src/web/src/components/System/Info.js deleted file mode 100644 index d9ce8813..00000000 --- a/src/web/src/components/System/Info.js +++ /dev/null @@ -1,70 +0,0 @@ -import React from 'react'; -import YAML from 'yaml'; - -import { restart, shutdown, getVersion } from '../../lib/application'; - -import { Modal, Header } from 'semantic-ui-react'; -import CodeEditor from '../Shared/CodeEditor'; -import ShrinkableButton from '../Shared/ShrinkableButton'; - -const Info = ({ state }) => { - const stateAsYaml = YAML.stringify(state, { simpleKeys: true, sortMapEntries: true }); - - return ( - <> -
- -
-
-
- getVersion({ forceCheck: true })} - > - Check for Updates - -
- - Shut Down - - } - centered - size='mini' - header={
} - content="Are you sure you want to shut the application down? You'll need to manually start it again." - actions={['Cancel', { key: 'done', content: 'Shut Down', negative: true, onClick: shutdown }]} - /> - - Restart - - } - centered - size='mini' - header={
} - content='Are you sure you want restart the application?' - actions={['Cancel', { key: 'done', content: 'Restart', negative: true, onClick: restart }]} - /> -
- - ); -}; - -export default Info; \ No newline at end of file diff --git a/src/web/src/components/System/Info/index.js b/src/web/src/components/System/Info/index.js new file mode 100644 index 00000000..f640716e --- /dev/null +++ b/src/web/src/components/System/Info/index.js @@ -0,0 +1,74 @@ +import React from 'react'; +import YAML from 'yaml'; + +import { restart, shutdown, getVersion } from '../../../lib/application'; + +import { Modal, Header, Divider } from 'semantic-ui-react'; + +import { + CodeEditor, + ShrinkableButton, +} from '../../Shared'; + +const Info = ({ state }) => { + const stateAsYaml = YAML.stringify(state, { simpleKeys: true, sortMapEntries: true }); + + return ( + <> +
+
+ getVersion({ forceCheck: true })} + > + Check for Updates + +
+ + Shut Down + + } + centered + size='mini' + header={
} + content="Are you sure you want to shut the application down? You'll need to manually start it again." + actions={['Cancel', { key: 'done', content: 'Shut Down', negative: true, onClick: shutdown }]} + /> + + Restart + + } + centered + size='mini' + header={
} + content='Are you sure you want restart the application?' + actions={['Cancel', { key: 'done', content: 'Restart', negative: true, onClick: restart }]} + /> +
+ +
+ +
+ + ); +}; + +export default Info; \ No newline at end of file diff --git a/src/web/src/components/System/Logs.js b/src/web/src/components/System/Logs.js deleted file mode 100644 index 4a118414..00000000 --- a/src/web/src/components/System/Logs.js +++ /dev/null @@ -1,83 +0,0 @@ -import React, { Component } from 'react'; -import { Table, Loader, Dimmer } from 'semantic-ui-react'; - -import { createLogsHubConnection } from '../../lib/hubFactory'; - -import './System.css'; - -const initialState = { - logs: [], - connected: false, -}; - -const levels = { - 'Debug': 'DBG', - 'Warning': 'WRN', - 'Error': 'ERR', - 'Information': 'INF', -}; - -const maxLogs = 500; - -class Logs extends Component { - state = initialState; - - componentDidMount = () => { - const logsHub = createLogsHubConnection(); - - logsHub.on('buffer', (buffer) => { - this.setState({ connected: true, logs: buffer.reverse().slice(0, maxLogs) }); - }); - - logsHub.on('log', (log) => { - this.setState({ connected: true, logs: [log].concat(this.state.logs).slice(0, maxLogs) }); - }); - - logsHub.onreconnecting(() => this.setState({ connected: false })); - logsHub.onclose(() => this.setState({ connected: false })); - logsHub.onreconnected(() => this.setState({ connected: true })); - - logsHub.start(); - }; - - formatTimestamp = (timestamp) => { - const date = new Date(timestamp); - return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len - }; - - render = () => { - const { connected, logs } = this.state; - - return ( -
- {!connected && } - {connected && - - - - Timestamp - Level - Message - - - - {logs.map((log, index) => - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - {log.message} - )} - -
- } -
- ); - }; -} - -export default Logs; \ No newline at end of file diff --git a/src/web/src/components/System/Options/DebugModal.js b/src/web/src/components/System/Options/DebugModal.js new file mode 100644 index 00000000..2f01eb16 --- /dev/null +++ b/src/web/src/components/System/Options/DebugModal.js @@ -0,0 +1,67 @@ +import React, { useState, useEffect } from 'react'; +import { toast } from 'react-toastify'; + +import { + Modal, + Button, + Icon, +} from 'semantic-ui-react'; + +import { getCurrentDebugView } from '../../../lib/options'; +import { CodeEditor, PlaceholderSegment, Switch } from '../../Shared'; + +const DebugModal = ({ open, onClose }) => { + const [loading, setLoading] = useState(true); + const [debugView, setDebugView] = useState(); + + useEffect(() => { + if (open) { + get(); + } + }, [open]); + + const get = async () => { + setLoading(true); + + try { + setDebugView(await getCurrentDebugView()); + } catch (error) { + console.error(error); + toast.error(error?.response?.data ?? error?.message ?? error); + } finally { + setLoading(false); + } + }; + + return ( + + + + Options (Debug View) + + + } + > +
+ +
+
+
+ + + +
); +}; + +export default DebugModal; \ No newline at end of file diff --git a/src/web/src/components/System/Options/Edit.js b/src/web/src/components/System/Options/Edit.js deleted file mode 100644 index f9657022..00000000 --- a/src/web/src/components/System/Options/Edit.js +++ /dev/null @@ -1,87 +0,0 @@ -import React, { useState, useEffect } from 'react'; - -import { Button, Icon, Message } from 'semantic-ui-react'; -import CodeEditor from '../../Shared/CodeEditor'; - -import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib/options'; -import PlaceholderSegment from '../../Shared/PlaceholderSegment'; - -const Edit = ({ cancelAction }) => { - const [{ loading, error }, setLoading] = useState({ loading: true, error: false }); - const [{ location, yaml, isDirty }, setYaml] = useState({ location: undefined, yaml: undefined, isDirty: false }); - const [yamlError, setYamlError] = useState(); - const [updateError, setUpdateError] = useState(); - - useEffect(() => { - get(); - }, []); - - const get = async () => { - setLoading({ loading: true, error: false }); - - try { - const [location, yaml] = await Promise.all([getYamlLocation(), getYaml()]); - - setYaml({ location, yaml, isDirty: false }); - setLoading({ loading: false, error: false }); - } catch (error) { - setLoading({ loading: false, error: error.message }); - } - }; - - const update = async (yaml) => { - setYaml({ location, yaml, isDirty: true }); - validate(yaml); - }; - - const validate = async (yaml) => { - const response = await validateYaml({ yaml }); - setYamlError(response); - }; - - const save = async (yaml) => { - await validate(yaml); - - if (!yamlError) { - try { - await updateYaml({ yaml }); - cancelAction(); - } - catch (error) { - setUpdateError(error.response.data); - } - } - }; - - if (loading) { - return ; - } - - if (error) { - return ; - } - - return ( - <> - - Editing {location} - -
- update(value)} - /> -
- {(yamlError || updateError) && - {(yamlError ?? '') + (updateError ?? '')}} -
- - -
- - ); -}; - -export default Edit; \ No newline at end of file diff --git a/src/web/src/components/System/Options/EditModal.js b/src/web/src/components/System/Options/EditModal.js new file mode 100644 index 00000000..b02cbf99 --- /dev/null +++ b/src/web/src/components/System/Options/EditModal.js @@ -0,0 +1,101 @@ +import React, { useState, useEffect } from 'react'; + +import { Button, Icon, Message, Modal } from 'semantic-ui-react'; +import CodeEditor from '../../Shared/CodeEditor'; + +import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib/options'; +import { + PlaceholderSegment, + Switch, +} from '../../Shared'; + +const EditModal = ({ open, onClose }) => { + const [{ loading, error }, setLoading] = useState({ loading: true, error: false }); + const [{ location, yaml, isDirty }, setYaml] = useState({ location: undefined, yaml: undefined, isDirty: false }); + const [yamlError, setYamlError] = useState(); + const [updateError, setUpdateError] = useState(); + + useEffect(() => { + if (open) { + get(); + } + }, [open]); + + const get = async () => { + setLoading({ loading: true, error: false }); + + try { + const [location, yaml] = await Promise.all([getYamlLocation(), getYaml()]); + + setYaml({ location, yaml, isDirty: false }); + setLoading({ loading: false, error: false }); + } catch (error) { + setLoading({ loading: false, error: error.message }); + } + }; + + const update = async (yaml) => { + setYaml({ location, yaml, isDirty: true }); + validate(yaml); + }; + + const validate = async (yaml) => { + const response = await validateYaml({ yaml }); + setYamlError(response); + }; + + const save = async (yaml) => { + await validate(yaml); + + if (!yamlError) { + try { + await updateYaml({ yaml }); + onClose(); + } + catch (error) { + setUpdateError(error.response.data); + } + } + }; + + return ( + + + + Edit Options + + Editing {location} + + + + } + error={error && } + > +
+ update(value)} + /> +
+
+
+ + {(yamlError || updateError) && + + {(yamlError ?? '') + (updateError ?? '')} + } + + + +
+ ); +}; + +export default EditModal; \ No newline at end of file diff --git a/src/web/src/components/System/Options/View.js b/src/web/src/components/System/Options/View.js deleted file mode 100644 index 9d4d7635..00000000 --- a/src/web/src/components/System/Options/View.js +++ /dev/null @@ -1,30 +0,0 @@ -import React from 'react'; -import YAML from 'yaml'; - -import { Icon, Button } from 'semantic-ui-react'; -import CodeEditor from '../../Shared/CodeEditor'; - -const View = ({ options, editAction }) => { - const { remoteConfiguration } = options; - - const optionsAsYaml = YAML.stringify(options, { simpleKeys: true, sortMapEntries: true }); - - return ( - <> -
- -
-
- {remoteConfiguration ? - : - } -
- - ); -}; - -export default View; \ No newline at end of file diff --git a/src/web/src/components/System/Options/index.js b/src/web/src/components/System/Options/index.js index 92535b95..894199e9 100644 --- a/src/web/src/components/System/Options/index.js +++ b/src/web/src/components/System/Options/index.js @@ -1,16 +1,76 @@ import React, { useState } from 'react'; +import YAML from 'yaml'; -import Edit from './Edit'; -import View from './View'; +import DebugModal from './DebugModal'; +import EditModal from './EditModal'; + +import { Divider } from 'semantic-ui-react'; +import { + CodeEditor, + ShrinkableButton, +} from '../../Shared'; const Index = ({ options }) => { - const [mode, setMode] = useState('view'); + const [debugModal, setDebugModal] = useState(false); + const [editModal, setEditModal] = useState(false); + + const { remoteConfiguration, debug } = options; + + const optionsAsYaml = YAML.stringify(options, { simpleKeys: true, sortMapEntries: true }); + + const DebugButton = () => { + if (!debug) return <>; + + return setDebugModal(true)} + > + Debug View + ; + }; + + const EditButton = () => { + if (!remoteConfiguration) { + return Remote Configuration Disabled; + } - if (mode === 'edit') { - return setMode('view')}/>; - } + return setEditModal(true)} + >Edit; + }; - return setMode('edit')}/>; + return ( + <> +
+ + +
+ +
+ +
+ setDebugModal(false)} + /> + setEditModal(false)} + /> + + ); }; export default Index; \ No newline at end of file diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index 560cc21a..cbcddf81 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -24,15 +24,24 @@ min-height: 100px; } -.full-height { - height: calc(100vh - 175px); -} - .no-grow { white-space: nowrap; overflow: overlay; } +.edit-code-header { + margin-top: 1em !important; + font-size: initial !important; +} + +.edit-code-content, .debug-view-content { + padding: 0px !important; +} + +.left-align { + text-align: left; +} + .footer-buttons { margin-top: 14px; text-align: right; @@ -43,23 +52,6 @@ text-align: right; } -.state-code-editor, .view-code-container, .edit-code-container, .edit-code-container-error { - border: 1px solid #d4d4d5; +.edit-code-container, .edit-code-container-error { overflow: auto; -} - -.state-code-container { - height: calc(100vh - 204px); -} - -.view-code-container { - height: calc(100vh - 254px); -} - -.edit-code-container { - height: calc(100vh - 316px); -} - -.edit-code-container-error { - height: calc(100vh - 378px); } \ No newline at end of file diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js index 8955b212..73904006 100644 --- a/src/web/src/components/System/System.js +++ b/src/web/src/components/System/System.js @@ -15,15 +15,42 @@ const System = ({ state = {}, options = {} }) => { const history = useHistory(); const panes = [ - { route: 'info', menuItem: 'Info', render: () => }, + { + route: 'info', + menuItem: { + key: 'info', + icon: 'info', + content: 'Info', + }, + render: () => , + }, { - route: 'options', menuItem: 'Options', render: () => - , + route: 'options', + menuItem: { + key: 'options', + icon: 'options', + content: 'Options', + }, + render: () => , }, { - route: 'shares', menuItem: 'Shares', render: () => , + route: 'shares', + menuItem: { + key: 'shares', + icon: 'share external', + content: 'Shares', + }, + render: () => , + }, + { + route: 'logs', + menuItem: { + key: 'logs', + icon: 'file outline', + content: 'Logs', + }, + render: () => , }, - { route: 'logs', menuItem: 'Logs', render: () => }, ]; const activeIndex = panes.findIndex(pane => pane.route === tab); -- cgit v1.2.3 From 388792b916fdba7b0200d04e7d12ca8f22e33fcc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:07:29 -0500 Subject: move rescan share function, implement share summary --- src/slskd/Application.cs | 7 ---- .../Core/API/Controllers/ApplicationController.cs | 15 ------- .../Shares/API/Controllers/SharesController.cs | 48 +++++++++++++++++++++- src/slskd/Shares/API/DTO/SummarizedShare.cs | 32 +++++++++++++++ 4 files changed, 78 insertions(+), 24 deletions(-) create mode 100644 src/slskd/Shares/API/DTO/SummarizedShare.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1064e56a..c2a8632b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -48,7 +48,6 @@ namespace slskd public interface IApplication : IHostedService { public Task CheckVersionAsync(); - public Task RescanSharesAsync(); public void CollectGarbage(); } @@ -226,12 +225,6 @@ namespace slskd } } - /// - /// Re-scans shared directories. - /// - /// The operation context. - public Task RescanSharesAsync() => SharedFileCache.FillAsync(); - async Task IHostedService.StartAsync(CancellationToken cancellationToken) { Log.Information("Configuring client"); diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index cd03d96f..3cf3c0a3 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -136,20 +136,5 @@ namespace slskd.Core.API return Ok(); } - - [HttpPut] - [Route("shares")] - [Authorize] - public IActionResult RescanSharesAsync() - { - if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) - { - return Conflict("A share scan is already in progress."); - } - - _ = Application.RescanSharesAsync(); - - return Ok(); - } } } diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 06a02de3..c569a150 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -33,17 +33,46 @@ namespace slskd.Shares.API [Consumes("application/json")] public class SharesController : ControllerBase { - public SharesController(IShareService shareService) + public SharesController( + IShareService shareService, + IStateMonitor applicationStateMonitor) { Shares = shareService; + ApplicationStateMonitor = applicationStateMonitor; } private IShareService Shares { get; } + private IStateMonitor ApplicationStateMonitor { get; } [HttpGet("")] public IActionResult List() { - return Ok(Shares.Cache.Shares); + var browse = Shares.Cache.Browse(); + + var summary = Shares.Cache.Shares.Select(share => + { + var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); + var fileCount = directories.Aggregate(seed: 0, (sum, directory) => + { + sum += directory.FileCount; + return sum; + }); + + return new SummarizedShare() + { + Id = share.Id, + Alias = share.Alias, + IsExcluded = share.IsExcluded, + LocalPath = share.LocalPath, + Mask = share.Mask, + Raw = share.Raw, + RemotePath = share.RemotePath, + Directories = directories.Count(), + Files = fileCount, + }; + }); + + return Ok(summary); } [HttpGet("{id}")] @@ -86,5 +115,20 @@ namespace slskd.Shares.API return Ok(contents); } + + [HttpPut] + [Route("")] + [Authorize] + public IActionResult RescanSharesAsync() + { + if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) + { + return Conflict("A share scan is already in progress."); + } + + _ = Shares.Cache.FillAsync(); + + return Ok(); + } } } diff --git a/src/slskd/Shares/API/DTO/SummarizedShare.cs b/src/slskd/Shares/API/DTO/SummarizedShare.cs new file mode 100644 index 00000000..a1d6ed7b --- /dev/null +++ b/src/slskd/Shares/API/DTO/SummarizedShare.cs @@ -0,0 +1,32 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + public record SummarizedShare + { + public string Id { get; init; } + public string Alias { get; init; } + public bool IsExcluded { get; init; } + public string LocalPath { get; init; } + public string Mask { get; init; } + public string Raw { get; init; } + public string RemotePath { get; init; } + public int Directories { get; init; } + public int Files { get; init; } + } +} \ No newline at end of file -- cgit v1.2.3 From 89b75c295de97096a6c5dbef8d9b93f28d2a1767 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:07:56 -0500 Subject: drop cache table when starting scan --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 1b35aacf..5a218835 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -460,7 +460,7 @@ namespace slskd.Shares SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); SQLite.Open(); - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); cmd.ExecuteNonQuery(); } -- cgit v1.2.3 From a5b3cd97d037a1a4d7bf62e68d6b94d3fd149175 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:08:07 -0500 Subject: add loading prop --- src/web/src/components/Shared/ShrinkableButton.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Shared/ShrinkableButton.js b/src/web/src/components/Shared/ShrinkableButton.js index 2f736ade..67c9f660 100644 --- a/src/web/src/components/Shared/ShrinkableButton.js +++ b/src/web/src/components/Shared/ShrinkableButton.js @@ -3,13 +3,13 @@ import React from 'react'; import { useMediaQuery } from 'react-responsive'; import { Button, Icon, Popup } from 'semantic-ui-react'; -const ShrinkableButton = ({ icon, mediaQuery, children, ...rest }) => { +const ShrinkableButton = ({ icon, loading, mediaQuery, children, ...rest }) => { const shouldShrink = useMediaQuery({ query: mediaQuery }); if (!shouldShrink) { return ( ); @@ -20,7 +20,7 @@ const ShrinkableButton = ({ icon, mediaQuery, children, ...rest }) => { content={children} trigger={ } /> -- cgit v1.2.3 From c16695fc69577b95592079c59cce4afec4ea80aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:08:35 -0500 Subject: add rescan --- src/web/src/lib/shares.js | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/web/src/lib/shares.js b/src/web/src/lib/shares.js index 34fab679..f1d0373c 100644 --- a/src/web/src/lib/shares.js +++ b/src/web/src/lib/shares.js @@ -16,4 +16,8 @@ export const browseAll = async () => { export const browse = async ({ id } = {}) => { if (!id) throw new Error('unable to get share contents: id is missing'); return (await api.get(`/shares/${id}/contents`)).data; +}; + +export const rescan = async () => { + return (await api.put('/shares')).data; }; \ No newline at end of file -- cgit v1.2.3 From 492cfe9ad1fcaf2c7d11ca92089ca4e87b28bdc2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:08:38 -0500 Subject: wip --- src/web/src/components/System/Shares/Share.js | 4 +-- src/web/src/components/System/Shares/index.js | 44 ++++++++++++++++++++------- src/web/src/components/System/System.js | 2 +- 3 files changed, 36 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Shares/Share.js b/src/web/src/components/System/Shares/Share.js index eadcd07b..61080453 100644 --- a/src/web/src/components/System/Shares/Share.js +++ b/src/web/src/components/System/Shares/Share.js @@ -5,7 +5,7 @@ import { } from 'semantic-ui-react'; const Share = ({ share = {}, onBrowse } = {}) => { - const { id, remotePath, localPath, mask, alias, isExcluded } = share; + const { id, remotePath, localPath, mask, alias, isExcluded, directories, files } = share; return ( @@ -14,7 +14,7 @@ const Share = ({ share = {}, onBrowse } = {}) => { Description
-            {JSON.stringify({ id, localPath, mask, alias, isExcluded }, null, 2)}
+            {JSON.stringify({ id, localPath, mask, alias, isExcluded, directories, files }, null, 2)}
           
diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 5f3ae971..aa8db54a 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -2,15 +2,16 @@ import React, { useState, useEffect } from 'react'; import { toast } from 'react-toastify'; import * as sharesLib from '../../../lib/shares'; -import { LoaderSegment } from '../../Shared'; +import { LoaderSegment, PlaceholderSegment, ShrinkableButton, Switch } from '../../Shared'; import Share from './Share'; import { Modal, Button, + Divider, } from 'semantic-ui-react'; -const Index = () => { +const Index = ({ state }) => { const [loading, setLoading] = useState(true); const [shares, setShares] = useState([]); const [everything, setEverything] = useState(); @@ -38,22 +39,43 @@ const Index = () => { setModal(true); }; + const rescan = async () => { + await sharesLib.rescan(); + }; + if (loading) { return LoaderSegment; } + const { filling, filled, faulted, fillProgress, directories, files, excludedDirectories } = state; + return ( <> -
-
    - {shares.map(share => ( - browse({ id: share.id })}/> - ))} -
-
-          {JSON.stringify(everything, null, 2)}
-        
+
+ {filling ? 'Scanning shares' : 'Rescan Shares'}
+ + } + > +
+
    + {shares.map(share => ( + browse({ id: share.id })}/> + ))} +
+
+            {JSON.stringify(state, null, 2)}
+          
+
+
{ icon: 'share external', content: 'Shares', }, - render: () => , + render: () => , }, { route: 'logs', -- cgit v1.2.3 From dc61b2d0f43ee455c0c73bb0118918a77a124082 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 22:52:47 -0500 Subject: add missing Logs component --- src/web/src/components/System/Logs/index.js | 83 +++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/web/src/components/System/Logs/index.js (limited to 'src') diff --git a/src/web/src/components/System/Logs/index.js b/src/web/src/components/System/Logs/index.js new file mode 100644 index 00000000..51b48f44 --- /dev/null +++ b/src/web/src/components/System/Logs/index.js @@ -0,0 +1,83 @@ +import React, { Component } from 'react'; +import { Table, Loader, Dimmer } from 'semantic-ui-react'; + +import { createLogsHubConnection } from '../../../lib/hubFactory'; + +import '../System.css'; + +const initialState = { + logs: [], + connected: false, +}; + +const levels = { + 'Debug': 'DBG', + 'Warning': 'WRN', + 'Error': 'ERR', + 'Information': 'INF', +}; + +const maxLogs = 500; + +class Logs extends Component { + state = initialState; + + componentDidMount = () => { + const logsHub = createLogsHubConnection(); + + logsHub.on('buffer', (buffer) => { + this.setState({ connected: true, logs: buffer.reverse().slice(0, maxLogs) }); + }); + + logsHub.on('log', (log) => { + this.setState({ connected: true, logs: [log].concat(this.state.logs).slice(0, maxLogs) }); + }); + + logsHub.onreconnecting(() => this.setState({ connected: false })); + logsHub.onclose(() => this.setState({ connected: false })); + logsHub.onreconnected(() => this.setState({ connected: true })); + + logsHub.start(); + }; + + formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len + }; + + render = () => { + const { connected, logs } = this.state; + + return ( +
+ {!connected && } + {connected && + + + + Timestamp + Level + Message + + + + {logs.map((log, index) => + + {this.formatTimestamp(log.timestamp)} + {levels[log.level] || log.level} + {log.message} + )} + +
+ } +
+ ); + }; +} + +export default Logs; \ No newline at end of file -- cgit v1.2.3 From c049c50f778c6129ead1d91e2bc3d2c88ba815e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 00:58:57 -0500 Subject: tidy up --- src/slskd/Shares/API/Controllers/SharesController.cs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index c569a150..d6a31c4e 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -104,14 +104,8 @@ namespace slskd.Shares.API return NotFound(); } - var browse = Shares.Cache.Browse(); - - foreach (var dir in browse) - { - Console.WriteLine($"{dir.Name} ?? ${share.RemotePath}"); - } - - var contents = Shares.Cache.Browse().Where(directory => directory.Name.StartsWith(share.RemotePath)); + var contents = Shares.Cache.Browse() + .Where(directory => directory.Name.StartsWith(share.RemotePath)); return Ok(contents); } -- cgit v1.2.3 From e32e6f011422190a332f162a9a1dcd301579f591 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 00:59:27 -0500 Subject: display an icon when an action is pending --- src/web/src/components/App.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 76881c93..7f488643 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -116,7 +116,7 @@ class App extends Component { render = () => { const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state; - const { version = {}, server } = applicationState; + const { version = {}, server, pendingReconnect, pendingRestart, pendingShareRescan } = applicationState; const { isUpdateAvailable, current, latest } = version; if (!initialized) { @@ -212,6 +212,13 @@ class App extends Component { Disconnected } + {(pendingReconnect || pendingRestart || pendingShareRescan) && + + + + + Pending Action + } {isUpdateAvailable && -- cgit v1.2.3 From 86c510a31fa5e279da49b834808c2a81c6782c74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 00:59:48 -0500 Subject: tidy up --- src/web/src/components/Search/List/SearchList.js | 50 +++++++++++------------- src/web/src/components/Search/Searches.js | 3 +- 2 files changed, 24 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js index db16fa71..5a77149b 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -27,33 +27,29 @@ const SearchList = ({ connecting={connecting && } error={error && } > - - - - - - - Search - Files - Locked - Responses - Ended - - - - - {Object.values(searches) - .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) - .map((search, index) => )} - -
-
-
+ + + + + Search + Files + Locked + Responses + Ended + + + + + {Object.values(searches) + .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) + .map((search, index) => )} + +
diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index fdcda3ac..fb0ce027 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -91,8 +91,7 @@ const Searches = ({ server }) => { return () => { searchHub.stop(); }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, []); // eslint-disable-line react-hooks/exhaustive-deps // create a new search, and optionally navigate to it to display the details // we do this if the user clicks the search icon, or repeats an existing search -- cgit v1.2.3 From 410dc9db717ad5f01f4b6b40a5a0da41d53b1a74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 01:00:06 -0500 Subject: add 5px padding back to debug and share view --- src/web/src/components/System/System.css | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index cbcddf81..e29487f1 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -34,10 +34,14 @@ font-size: initial !important; } -.edit-code-content, .debug-view-content { +.edit-code-content { padding: 0px !important; } +.debug-view-content, .share-ls-content { + padding: 5px !important; +} + .left-align { text-align: left; } -- cgit v1.2.3 From c9faf80c4988ef52fb2047763f455e7c30f4bbaf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 01:00:22 -0500 Subject: wip --- src/web/src/components/System/Shares/index.js | 122 ++++++++++++++++++-------- 1 file changed, 85 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index aa8db54a..ff054a97 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -1,31 +1,48 @@ import React, { useState, useEffect } from 'react'; import { toast } from 'react-toastify'; +import { orderBy } from 'lodash'; import * as sharesLib from '../../../lib/shares'; -import { LoaderSegment, PlaceholderSegment, ShrinkableButton, Switch } from '../../Shared'; +import { + CodeEditor, + LoaderSegment, + PlaceholderSegment, + ShrinkableButton, + Switch, +} from '../../Shared'; + import Share from './Share'; import { Modal, Button, Divider, + Table, + Icon, } from 'semantic-ui-react'; +import { Link } from 'react-router-dom'; const Index = ({ state }) => { const [loading, setLoading] = useState(true); const [shares, setShares] = useState([]); - const [everything, setEverything] = useState(); const [modal, setModal] = useState(false); + const { filling, filled, faulted, fillProgress, directories, files, excludedDirectories } = state; + useEffect(() => { getAll(); }, []); + useEffect(() => { + if (filled) { + getAll(); + } + }, [filled]); + const getAll = async () => { try { setLoading(true); setShares(await sharesLib.getAll()); - setLoading(false); } catch (error) { console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); @@ -34,20 +51,28 @@ const Index = ({ state }) => { } }; - const browse = async ({ id }) => { - setEverything(await sharesLib.browse({ id })); - setModal(true); - }; + const browse = async (share) => { + const { id, localPath, remotePath } = share; + const contents = await sharesLib.browse({ id }); - const rescan = async () => { - await sharesLib.rescan(); - }; + var directories = contents.map(directory => { + const lines = [directory.name.replace(remotePath, localPath)]; - if (loading) { - return LoaderSegment; - } + orderBy(directory.files, 'filename').forEach(file => { + console.log(file); + lines.push('\t' + file.filename.replace(remotePath, '')); + }); - const { filling, filled, faulted, fillProgress, directories, files, excludedDirectories } = state; + lines.push(''); + + return lines.join('\n'); + }); + + setModal({ id, localPath, remotePath, contents: directories.join('\n') }); + }; + + const shared = shares.filter(share => !share.isExcluded); + const excluded = shares.filter(share => share.isExcluded); return ( <> @@ -58,42 +83,65 @@ const Index = ({ state }) => { loading={filling} disabled={filling} mediaQuery={'(max-width: 516px)'} - onClick={rescan} + onClick={() => sharesLib.rescan()} >{filling ? 'Scanning shares' : 'Rescan Shares'}
} + filling={loading && } > -
-
    - {shares.map(share => ( - browse({ id: share.id })}/> - ))} -
-
-            {JSON.stringify(state, null, 2)}
-          
-
+ + + + Local Path + Directories + Files + Alias + Remote Path + + + + {shared.map((share, index) => ( + browse(share)}> + + {share.localPath} + + {share.directories} + {share.files} + {share.alias} + {share.remotePath} + ))} + +
+ + + + Excluded Paths + + + + {excluded.map((share, index) => ( + {share.localPath} + ))} + +
setModal(false)} - style={{ color: 'red' }} > - Delete Your Account - -
-            {JSON.stringify(everything, null, 2)}
-          
+ {modal.localPath} + + - -
-- cgit v1.2.3 From 21c08b38f13d5ae8a039e1aab5bc5c52508f06b8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 01:12:46 -0500 Subject: set minimum height of editor, show loader while rescanning --- src/web/src/components/System/Info/index.js | 13 ++++++------- src/web/src/components/System/Options/DebugModal.js | 13 ++++++------- src/web/src/components/System/Options/EditModal.js | 1 + src/web/src/components/System/Options/index.js | 13 ++++++------- src/web/src/components/System/Shares/index.js | 3 ++- 5 files changed, 21 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Info/index.js b/src/web/src/components/System/Info/index.js index f640716e..d1b504e2 100644 --- a/src/web/src/components/System/Info/index.js +++ b/src/web/src/components/System/Info/index.js @@ -60,13 +60,12 @@ const Info = ({ state }) => { />
-
- -
+ ); }; diff --git a/src/web/src/components/System/Options/DebugModal.js b/src/web/src/components/System/Options/DebugModal.js index 2f01eb16..21514c57 100644 --- a/src/web/src/components/System/Options/DebugModal.js +++ b/src/web/src/components/System/Options/DebugModal.js @@ -47,13 +47,12 @@ const DebugModal = ({ open, onClose }) => { } > -
- -
+
diff --git a/src/web/src/components/System/Options/EditModal.js b/src/web/src/components/System/Options/EditModal.js index b02cbf99..cfcbd3b6 100644 --- a/src/web/src/components/System/Options/EditModal.js +++ b/src/web/src/components/System/Options/EditModal.js @@ -80,6 +80,7 @@ const EditModal = ({ open, onClose }) => { {...{ className: (yamlError || updateError) ? 'edit-code-container-error' : 'edit-code-container' }} > update(value)} /> diff --git a/src/web/src/components/System/Options/index.js b/src/web/src/components/System/Options/index.js index 894199e9..afc1f545 100644 --- a/src/web/src/components/System/Options/index.js +++ b/src/web/src/components/System/Options/index.js @@ -54,13 +54,12 @@ const Index = ({ options }) => {
-
- -
+ setDebugModal(false)} diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index ff054a97..6ede4cbc 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -88,7 +88,7 @@ const Index = ({ state }) => { } + filling={(loading || filling) && } > @@ -134,6 +134,7 @@ const Index = ({ state }) => { {modal.localPath} Date: Fri, 27 May 2022 08:05:15 -0500 Subject: add fake delay to prevent flashing when navigating --- src/web/src/components/System/Info/index.js | 30 ++++++++++++++------ src/web/src/components/System/Options/index.js | 38 +++++++++++++++++--------- 2 files changed, 47 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Info/index.js b/src/web/src/components/System/Info/index.js index d1b504e2..063303ac 100644 --- a/src/web/src/components/System/Info/index.js +++ b/src/web/src/components/System/Info/index.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState, useEffect } from 'react'; import YAML from 'yaml'; import { restart, shutdown, getVersion } from '../../../lib/application'; @@ -7,11 +7,19 @@ import { Modal, Header, Divider } from 'semantic-ui-react'; import { CodeEditor, + LoaderSegment, ShrinkableButton, + Switch, } from '../../Shared'; const Info = ({ state }) => { - const stateAsYaml = YAML.stringify(state, { simpleKeys: true, sortMapEntries: true }); + const [contents, setContents] = useState(); + + useEffect(() => { + setTimeout(() => { + setContents(YAML.stringify(state, { simpleKeys: true, sortMapEntries: true })); + }, 250); + }, [state]); return ( <> @@ -21,6 +29,7 @@ const Info = ({ state }) => { icon='refresh' mediaQuery='(max-width: 516px)' primary + disabled={!contents} onClick={() => getVersion({ forceCheck: true })} > Check for Updates @@ -32,6 +41,7 @@ const Info = ({ state }) => { icon='shutdown' mediaQuery='(max-width: 516px)' negative + disabled={!contents} > Shut Down @@ -48,6 +58,7 @@ const Info = ({ state }) => { icon='redo' mediaQuery='(max-width: 516px)' negative + disabled={!contents} > Restart @@ -60,12 +71,15 @@ const Info = ({ state }) => { /> - + } + > + + ); }; diff --git a/src/web/src/components/System/Options/index.js b/src/web/src/components/System/Options/index.js index afc1f545..16928a29 100644 --- a/src/web/src/components/System/Options/index.js +++ b/src/web/src/components/System/Options/index.js @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import YAML from 'yaml'; import DebugModal from './DebugModal'; @@ -7,30 +7,38 @@ import EditModal from './EditModal'; import { Divider } from 'semantic-ui-react'; import { CodeEditor, + LoaderSegment, ShrinkableButton, + Switch, } from '../../Shared'; const Index = ({ options }) => { const [debugModal, setDebugModal] = useState(false); const [editModal, setEditModal] = useState(false); + const [contents, setContents] = useState(); + + useEffect(() => { + setTimeout(() => { + setContents(YAML.stringify(options, { simpleKeys: true, sortMapEntries: true })); + }, 250); + }, [options]); const { remoteConfiguration, debug } = options; - const optionsAsYaml = YAML.stringify(options, { simpleKeys: true, sortMapEntries: true }); - - const DebugButton = () => { + const DebugButton = ({ ...props }) => { if (!debug) return <>; return setDebugModal(true)} + {...props} > Debug View ; }; - const EditButton = () => { + const EditButton = ({ ...props }) => { if (!remoteConfiguration) { return { icon='edit' mediaQuery='(max-width: 516px)' onClick={() => setEditModal(true)} + {...props} >Edit; }; return ( <>
- - + +
- + } + > + + setDebugModal(false)} -- cgit v1.2.3 From 46a33d3974bfeb3cfa0a5bb68e7278ff9fe2db8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 08:05:33 -0500 Subject: use standard LoaderSegment --- src/web/src/components/System/Logs/index.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Logs/index.js b/src/web/src/components/System/Logs/index.js index 51b48f44..b30b0a43 100644 --- a/src/web/src/components/System/Logs/index.js +++ b/src/web/src/components/System/Logs/index.js @@ -1,7 +1,8 @@ import React, { Component } from 'react'; -import { Table, Loader, Dimmer } from 'semantic-ui-react'; +import { Table } from 'semantic-ui-react'; import { createLogsHubConnection } from '../../../lib/hubFactory'; +import { LoaderSegment } from '../../Shared'; import '../System.css'; @@ -50,7 +51,7 @@ class Logs extends Component { return (
- {!connected && } + {!connected && } {connected &&
-- cgit v1.2.3 From adcc26ed221085f0cabd827fbd6b06a85fdef12d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 08:05:51 -0500 Subject: hide banner before loaded --- src/web/src/components/System/Options/EditModal.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Options/EditModal.js b/src/web/src/components/System/Options/EditModal.js index cfcbd3b6..d435bfd8 100644 --- a/src/web/src/components/System/Options/EditModal.js +++ b/src/web/src/components/System/Options/EditModal.js @@ -7,6 +7,7 @@ import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib import { PlaceholderSegment, Switch, + Div, } from '../../Shared'; const EditModal = ({ open, onClose }) => { @@ -67,9 +68,11 @@ const EditModal = ({ open, onClose }) => { Edit Options - - Editing {location} - + Date: Fri, 27 May 2022 08:06:09 -0500 Subject: move contents modal to a separate file --- .../src/components/System/Shares/ContentsModal.js | 80 ++++++++++++++++++++ src/web/src/components/System/Shares/index.js | 85 ++++++---------------- 2 files changed, 102 insertions(+), 63 deletions(-) create mode 100644 src/web/src/components/System/Shares/ContentsModal.js (limited to 'src') diff --git a/src/web/src/components/System/Shares/ContentsModal.js b/src/web/src/components/System/Shares/ContentsModal.js new file mode 100644 index 00000000..b9f0d86d --- /dev/null +++ b/src/web/src/components/System/Shares/ContentsModal.js @@ -0,0 +1,80 @@ +import React, { useEffect, useState } from 'react'; +import { orderBy } from 'lodash'; + +import { browse } from '../../../lib/shares'; + +import { + Modal, + Button, + Icon, +} from 'semantic-ui-react'; + +import { + CodeEditor, LoaderSegment, Switch, +} from '../../Shared'; + +const ContentsModal = ({ share, onClose }) => { + const [loading, setLoading] = useState(true); + const [contents, setContents] = useState(); + + const { id, localPath, remotePath } = share || {}; + + useEffect(() => { + const fetch = async () => { + setLoading(true); + + const contents = await browse({ id }); + + var directories = contents.map(directory => { + const lines = [directory.name.replace(remotePath, localPath)]; + + orderBy(directory.files, 'filename').forEach(file => { + lines.push('\t' + file.filename.replace(remotePath, '')); + }); + + lines.push(''); + + return lines.join('\n'); + }); + + setContents(directories.join('\n')); + setLoading(false); + }; + + if (id) { + fetch(); + } else { + setLoading(true); + setContents(); + } + }, [id]); // eslint-disable-line react-hooks/exhaustive-deps + + return ( + + {localPath} + + } + > + + + + + + + + ); +}; + +export default ContentsModal; \ No newline at end of file diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 6ede4cbc..8da95034 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -1,33 +1,29 @@ import React, { useState, useEffect } from 'react'; import { toast } from 'react-toastify'; -import { orderBy } from 'lodash'; import * as sharesLib from '../../../lib/shares'; import { - CodeEditor, - LoaderSegment, - PlaceholderSegment, + LoaderSegment, ShrinkableButton, Switch, + Div, } from '../../Shared'; -import Share from './Share'; +import ContentsModal from './ContentsModal'; import { - Modal, - Button, Divider, Table, Icon, } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; -const Index = ({ state }) => { +const Index = ({ state = {} } = {}) => { const [loading, setLoading] = useState(true); const [shares, setShares] = useState([]); const [modal, setModal] = useState(false); - const { filling, filled, faulted, fillProgress, directories, files, excludedDirectories } = state; + const { filling, filled, fillProgress } = state; useEffect(() => { getAll(); @@ -51,26 +47,6 @@ const Index = ({ state }) => { } }; - const browse = async (share) => { - const { id, localPath, remotePath } = share; - const contents = await sharesLib.browse({ id }); - - var directories = contents.map(directory => { - const lines = [directory.name.replace(remotePath, localPath)]; - - orderBy(directory.files, 'filename').forEach(file => { - console.log(file); - lines.push('\t' + file.filename.replace(remotePath, '')); - }); - - lines.push(''); - - return lines.join('\n'); - }); - - setModal({ id, localPath, remotePath, contents: directories.join('\n') }); - }; - const shared = shares.filter(share => !share.isExcluded); const excluded = shares.filter(share => share.isExcluded); @@ -81,7 +57,7 @@ const Index = ({ state }) => { primary icon='refresh' loading={filling} - disabled={filling} + disabled={filling || loading} mediaQuery={'(max-width: 516px)'} onClick={() => sharesLib.rescan()} >{filling ? 'Scanning shares' : 'Rescan Shares'} @@ -102,7 +78,7 @@ const Index = ({ state }) => { {shared.map((share, index) => ( - browse(share)}> + setModal(share)}> {share.localPath} @@ -113,39 +89,22 @@ const Index = ({ state }) => { ))}
- - - - Excluded Paths - - - - {excluded.map((share, index) => ( - {share.localPath} - ))} - -
+
- setModal(false)} - > - {modal.localPath} - - - - - - - + setModal(false)}/> ); }; -- cgit v1.2.3 From 7fdcc7c2cafd81db446c2ea96b3d620a7a0adf0f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 08:07:31 -0500 Subject: fix loaders not being shown in modals --- src/web/src/components/App.css | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src') diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 82e74b71..9c06bf34 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -130,4 +130,13 @@ body { .view:last-child { margin-bottom: 17px; +} + +/* https://github.com/Semantic-Org/Semantic-UI-React/issues/3133#issuecomment-418766748 */ +.ui.dimmer .ui.modal-loader.loader:before { + border-color: rgba(0,0,0,.1); +} + +.ui.dimmer .ui.modal-loader.loader:after { + border-color: #767676 transparent transparent; } \ No newline at end of file -- cgit v1.2.3 From 1152df08d7c7d7f3a6787f26a6946d3f6f07ea43 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 13:12:06 -0500 Subject: tidy up --- .gitignore | 1 - .../src/components/System/Shares/ExclusionTable.js | 29 ++++++++++++++ src/web/src/components/System/Shares/Share.js | 25 ------------ src/web/src/components/System/Shares/ShareTable.js | 38 ++++++++++++++++++ src/web/src/components/System/Shares/index.js | 46 +++------------------- src/web/src/components/System/System.css | 4 ++ 6 files changed, 76 insertions(+), 67 deletions(-) create mode 100644 src/web/src/components/System/Shares/ExclusionTable.js delete mode 100644 src/web/src/components/System/Shares/Share.js create mode 100644 src/web/src/components/System/Shares/ShareTable.js (limited to 'src') diff --git a/.gitignore b/.gitignore index bcf6c53e..57adbc64 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ .vs dist/ -logs/ src/slskd/bin/ src/slskd/obj/ src/slskd/wwwroot/ diff --git a/src/web/src/components/System/Shares/ExclusionTable.js b/src/web/src/components/System/Shares/ExclusionTable.js new file mode 100644 index 00000000..90ee2eff --- /dev/null +++ b/src/web/src/components/System/Shares/ExclusionTable.js @@ -0,0 +1,29 @@ +import React from 'react'; + +import { + Table, + Icon, +} from 'semantic-ui-react'; + +const ExclusionTable = ({ exclusions = [] } = {}) => { + if (exclusions.length === 0) { + return <>; + } + + return ( + + + + Excluded Paths + + + + {exclusions.map((share, index) => ( + {share.localPath} + ))} + +
+ ); +}; + +export default ExclusionTable; \ No newline at end of file diff --git a/src/web/src/components/System/Shares/Share.js b/src/web/src/components/System/Shares/Share.js deleted file mode 100644 index 61080453..00000000 --- a/src/web/src/components/System/Shares/Share.js +++ /dev/null @@ -1,25 +0,0 @@ -import React from 'react'; - -import { - Item, -} from 'semantic-ui-react'; - -const Share = ({ share = {}, onBrowse } = {}) => { - const { id, remotePath, localPath, mask, alias, isExcluded, directories, files } = share; - - return ( - - - {remotePath} - Description - -
-            {JSON.stringify({ id, localPath, mask, alias, isExcluded, directories, files }, null, 2)}
-          
-
-
-
- ); -}; - -export default Share; \ No newline at end of file diff --git a/src/web/src/components/System/Shares/ShareTable.js b/src/web/src/components/System/Shares/ShareTable.js new file mode 100644 index 00000000..ecd83e3f --- /dev/null +++ b/src/web/src/components/System/Shares/ShareTable.js @@ -0,0 +1,38 @@ +import React from 'react'; + +import { + Table, + Icon, +} from 'semantic-ui-react'; + +import { Link } from 'react-router-dom'; + +const ShareTable = ({ shares, onClick }) => { + return ( + + + + Local Path + Directories + Files + Alias + Remote Path + + + + {shares.map((share, index) => ( + onClick(share)}> + + {share.localPath} + + {share.directories} + {share.files} + {share.alias} + {share.remotePath} + ))} + +
+ ); +}; + +export default ShareTable; \ No newline at end of file diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 8da95034..5fe59cb2 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -6,17 +6,16 @@ import { LoaderSegment, ShrinkableButton, Switch, - Div, } from '../../Shared'; import ContentsModal from './ContentsModal'; import { Divider, - Table, - Icon, } from 'semantic-ui-react'; -import { Link } from 'react-router-dom'; + +import ExclusionTable from './ExclusionTable'; +import ShareTable from './ShareTable'; const Index = ({ state = {} } = {}) => { const [loading, setLoading] = useState(true); @@ -66,43 +65,8 @@ const Index = ({ state = {} } = {}) => { } > - - - - Local Path - Directories - Files - Alias - Remote Path - - - - {shared.map((share, index) => ( - setModal(share)}> - - {share.localPath} - - {share.directories} - {share.files} - {share.alias} - {share.remotePath} - ))} - -
- + +
setModal(false)}/> diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index e29487f1..a8e9cb8e 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -58,4 +58,8 @@ .edit-code-container, .edit-code-container-error { overflow: auto; +} + +.share-count-column { + width: 110px; } \ No newline at end of file -- cgit v1.2.3 From e9c1a68650fa3567b04c8543f8cf77926b099a4f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 28 May 2022 23:00:54 -0500 Subject: docs --- .../Shares/API/Controllers/SharesController.cs | 79 ++++++++++++++++++++-- 1 file changed, 73 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index d6a31c4e..0b397bfd 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -17,22 +17,27 @@ namespace slskd.Shares.API { - using System; + using System.Collections.Generic; using System.Linq; - using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; /// /// Shares. /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] [ApiController] + [ApiVersion("0")] [Produces("application/json")] [Consumes("application/json")] + [Route("api/v{version:apiVersion}/[controller]")] + [Authorize] public class SharesController : ControllerBase { + /// + /// Initializes a new instance of the class. + /// + /// + /// public SharesController( IShareService shareService, IStateMonitor applicationStateMonitor) @@ -44,7 +49,14 @@ namespace slskd.Shares.API private IShareService Shares { get; } private IStateMonitor ApplicationStateMonitor { get; } + /// + /// Gets the current list of shares. + /// + /// The request completed successfully. + /// [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] public IActionResult List() { var browse = Shares.Cache.Browse(); @@ -75,26 +87,73 @@ namespace slskd.Shares.API return Ok(summary); } + /// + /// Gets the share associated with the specified . + /// + /// The id of the share. + /// The request completed successfully. + /// The requested share could not be found. + /// [HttpGet("{id}")] + [Authorize] + [ProducesResponseType(typeof(SummarizedShare), 200)] + [ProducesResponseType(404)] public IActionResult Get(string id) { - var share = Ok(Shares.Cache.Shares.FirstOrDefault(share => share.Id == id)); + var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - return share; + var browse = Shares.Cache.Browse(); + var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); + var fileCount = directories.Aggregate(seed: 0, (sum, directory) => + { + sum += directory.FileCount; + return sum; + }); + + var summary = new SummarizedShare() + { + Id = share.Id, + Alias = share.Alias, + IsExcluded = share.IsExcluded, + LocalPath = share.LocalPath, + Mask = share.Mask, + Raw = share.Raw, + RemotePath = share.RemotePath, + Directories = directories.Count(), + Files = fileCount, + }; + + return Ok(summary); } + /// + /// Returns a list of all shared directories and files. + /// + /// + /// The request completed successfully. [HttpGet("contents")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] public IActionResult BrowseAll() { return Ok(Shares.Cache.Browse()); } + /// + /// Gets the contents of the share associated with the specified . + /// + /// The id of the share. + /// + /// The request completed successfully. + /// The requested share could not be found. [HttpGet("{id}/contents")] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(404)] public IActionResult BrowseShare(string id) { var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); @@ -110,9 +169,17 @@ namespace slskd.Shares.API return Ok(contents); } + /// + /// Initiates a scan of the configured shares. + /// + /// + /// The request completed successfully. + /// A share scan is already in progress. [HttpPut] [Route("")] [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) -- cgit v1.2.3 From 79bfb864cd3acaa398cfc32849c455fb5313c3ce Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 28 May 2022 23:02:41 -0500 Subject: start ShareService refactor --- src/slskd/Shares/ShareService.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 2e4e7c95..763bb819 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.Options; + namespace slskd.Shares { using System; @@ -12,16 +14,22 @@ namespace slskd.Shares public class ShareService : IShareService { - public ShareService(ISharedFileCache sharedFileCache) + public ShareService( + ISharedFileCache sharedFileCache, + IOptionsMonitor optionsMonitor) { Cache = sharedFileCache; + OptionsMonitor = optionsMonitor; } public ISharedFileCache Cache { get; } + private IOptionsMonitor OptionsMonitor { get; } + private List Shares { get; set; } = new List(); + public IReadOnlyList List(Func expression = null) { - return Cache.Shares.Where(expression).ToList().AsReadOnly(); + return Shares.Where(expression).ToList().AsReadOnly(); } } } \ No newline at end of file -- cgit v1.2.3 From 38255041d2e68a6fee1f481b3922869d9b577510 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 29 May 2022 22:44:53 -0500 Subject: refactor shares service/cache --- src/slskd/Application.cs | 59 ++- src/slskd/Program.cs | 1 - .../Shares/API/Controllers/SharesController.cs | 27 +- src/slskd/Shares/ShareService.cs | 72 ++- src/slskd/Shares/SharedFileCache.cs | 482 --------------------- src/slskd/Shares/SharesCache.cs | 482 +++++++++++++++++++++ src/slskd/Shares/SoulseekFileFactory.cs | 2 +- src/slskd/State.cs | 68 +-- 8 files changed, 623 insertions(+), 570 deletions(-) delete mode 100644 src/slskd/Shares/SharedFileCache.cs create mode 100644 src/slskd/Shares/SharesCache.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c2a8632b..c0390c5a 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -82,7 +82,7 @@ namespace slskd IRoomTracker roomTracker, IRoomService roomService, IUserService userService, - ISharedFileCache sharedFileCache, + IShareService shareService, IPushbulletService pushbulletService, IHubContext applicationHub, IHubContext logHub) @@ -97,8 +97,8 @@ namespace slskd State = state; State.OnChange(state => State_OnChange(state)); - SharedFileCache = sharedFileCache; - SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); + Shares = shareService; + Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); TransferTracker = transferTracker; Transfers = transferService; @@ -152,7 +152,6 @@ namespace slskd private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } - private ISharedFileCache SharedFileCache { get; set; } private DateTime SharesRefreshStarted { get; set; } private IManagedState State { get; } private ITransferTracker TransferTracker { get; set; } @@ -160,6 +159,7 @@ namespace slskd private IHubContext ApplicationHub { get; set; } private IHubContext LogHub { get; set; } private IUserService Users { get; set; } + private IShareService Shares { get; set; } public void CollectGarbage() { @@ -306,7 +306,7 @@ namespace slskd } else { - _ = SharedFileCache.FillAsync(); + _ = Shares.StartScanAsync(); } if (OptionsAtStartup.NoConnect) @@ -337,12 +337,12 @@ namespace slskd /// The username of the requesting user. /// The IP endpoint of the requesting user. /// A Task resolving an IEnumerable of Soulseek.Directory. - private Task BrowseResponseResolver(string username, IPEndPoint endpoint) + private async Task BrowseResponseResolver(string username, IPEndPoint endpoint) { - var directories = SharedFileCache.Browse() + var directories = (await Shares.BrowseAsync()) .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes - return Task.FromResult(new BrowseResponse(directories)); + return new BrowseResponse(directories); } private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) @@ -441,7 +441,7 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero // initially, but we'll update them when the cache is filled. - _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -553,10 +553,10 @@ namespace slskd /// The unique token for the request, supplied by the requesting user. /// The requested directory. /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. - private Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + private async Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = SharedFileCache.List(directory); - return Task.FromResult(dir); + var dir = await Shares.ListAsync(directory); + return dir; } /// @@ -574,10 +574,10 @@ namespace slskd /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for /// security reasons. /// - private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; - var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); + var localFilename = (await Shares.ResolveAsync(filename)).ToLocalOSPath(); var fileInfo = new FileInfo(localFilename); @@ -593,7 +593,7 @@ namespace slskd { // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); - return Task.CompletedTask; + return; } // create a new cancellation token source so that we can cancel the upload from the UI. @@ -632,9 +632,6 @@ namespace slskd { Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget - - // return a completed task so that the invoking code can respond to the remote client. - return Task.CompletedTask; } private async Task OptionsMonitor_OnChange(Options newOptions) @@ -819,7 +816,7 @@ namespace slskd return null; } - var results = await SharedFileCache.SearchAsync(query); + var results = await Shares.SearchAsync(query); if (results.Any()) { @@ -839,45 +836,45 @@ namespace slskd return null; } - private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) + private void ShareState_OnChange((ShareState Previous, ShareState Current) state) { var (previous, current) = state; - if (!previous.Filling && current.Filling) + if (!previous.Cache.Filling && current.Cache.Filling) { SharesRefreshStarted = DateTime.UtcNow; - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); Log.Information("Scanning shares"); } - var lastProgress = Math.Round(previous.FillProgress * 100); - var currentProgress = Math.Round(current.FillProgress * 100); + var lastProgress = Math.Round(previous.Cache.FillProgress * 100); + var currentProgress = Math.Round(current.Cache.FillProgress * 100); if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { - State.SetValue(s => s with { SharedFileCache = current }); - Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); + State.SetValue(s => s with { Shares = current }); + Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Cache.Files); } - if (previous.Filling && !current.Filling) + if (previous.Cache.Filling && !current.Cache.Filling) { - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); - if (current.Faulted) + if (current.Cache.Faulted) { Log.Error("Failed to scan shares."); } else { State.SetValue(s => s with { PendingShareRescan = false }); - Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Cache.Directories, current.Cache.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) { - _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4643daa0..1a5d2a28 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -453,7 +453,6 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 0b397bfd..251f50b9 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -19,6 +19,7 @@ namespace slskd.Shares.API { using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -57,11 +58,11 @@ namespace slskd.Shares.API [HttpGet("")] [Authorize] [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult List() + public async Task List() { - var browse = Shares.Cache.Browse(); + var browse = await Shares.BrowseAsync(); - var summary = Shares.Cache.Shares.Select(share => + var summary = Shares.Shares.Select(share => { var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => @@ -98,16 +99,16 @@ namespace slskd.Shares.API [Authorize] [ProducesResponseType(typeof(SummarizedShare), 200)] [ProducesResponseType(404)] - public IActionResult Get(string id) + public async Task Get(string id) { - var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - var browse = Shares.Cache.Browse(); + var browse = await Shares.BrowseAsync(); var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => { @@ -139,9 +140,9 @@ namespace slskd.Shares.API [HttpGet("contents")] [Authorize] [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult BrowseAll() + public async Task BrowseAll() { - return Ok(Shares.Cache.Browse()); + return Ok(await Shares.BrowseAsync()); } /// @@ -154,16 +155,16 @@ namespace slskd.Shares.API [HttpGet("{id}/contents")] [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] - public IActionResult BrowseShare(string id) + public async Task BrowseShare(string id) { - var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - var contents = Shares.Cache.Browse() + var contents = (await Shares.BrowseAsync()) .Where(directory => directory.Name.StartsWith(share.RemotePath)); return Ok(contents); @@ -182,12 +183,12 @@ namespace slskd.Shares.API [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { - if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) + if (ApplicationStateMonitor.CurrentValue.Shares.Cache.Filling) { return Conflict("A share scan is already in progress."); } - _ = Shares.Cache.FillAsync(); + _ = Shares.StartScanAsync(); return Ok(); } diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 763bb819..68b3c629 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -1,3 +1,20 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + using Microsoft.Extensions.Options; namespace slskd.Shares @@ -5,31 +22,64 @@ namespace slskd.Shares using System; using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; + using Soulseek; public interface IShareService { - ISharedFileCache Cache { get; } - IReadOnlyList List(Func expression = null); + IReadOnlyList Shares { get; } + + Task> BrowseAsync(); + + Task ListAsync(string directory); + + Task> SearchAsync(SearchQuery query); + + Task StartScanAsync(); + + Task ResolveAsync(string remoteFilename); + + public IStateMonitor StateMonitor { get; } } public class ShareService : IShareService { public ShareService( - ISharedFileCache sharedFileCache, - IOptionsMonitor optionsMonitor) + IOptionsMonitor optionsMonitor, + IShareCache sharesCache = null) { - Cache = sharedFileCache; OptionsMonitor = optionsMonitor; + + // todo: when options change, fill SharesList with configured shares + // and set ScanPending = true + + Cache = sharesCache ?? new ShareCache(OptionsMonitor); + Cache.StateMonitor.OnChange(cacheState + => State.SetValue(state + => state with { Cache = cacheState.Current })); } - public ISharedFileCache Cache { get; } + public IReadOnlyList Shares => SharesList.AsReadOnly(); + public IStateMonitor StateMonitor => State; + private IShareCache Cache { get; } private IOptionsMonitor OptionsMonitor { get; } - private List Shares { get; set; } = new List(); + private List SharesList { get; set; } = new List(); + private IManagedState State { get; } = new ManagedState(); - public IReadOnlyList List(Func expression = null) - { - return Shares.Where(expression).ToList().AsReadOnly(); - } + public Task> BrowseAsync() + => Task.FromResult(Cache.Browse()); + + public Task ListAsync(string directory) + => Task.FromResult(Cache.List(directory)); + + public Task> SearchAsync(SearchQuery query) + => Cache.SearchAsync(query); + + public Task StartScanAsync() + => Cache.FillAsync(); + + public Task ResolveAsync(string remoteFilename) + => Task.FromResult(Cache.Resolve(remoteFilename)); } } \ No newline at end of file diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs deleted file mode 100644 index 5a218835..00000000 --- a/src/slskd/Shares/SharedFileCache.cs +++ /dev/null @@ -1,482 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -using System.IO; -using Microsoft.Extensions.Options; - -namespace slskd.Shares -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Shared file cache. - /// - public interface ISharedFileCache - { - /// - /// Gets the list of shares. - /// - public List Shares { get; } - - /// - /// Gets the cache state monitor. - /// - IStateMonitor StateMonitor { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - IEnumerable Browse(); - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - Task FillAsync(); - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - Directory List(string directory); - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - Task> SearchAsync(SearchQuery query); - } - - /// - /// Shared file cache. - /// - public class SharedFileCache : ISharedFileCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SharedFileCache( - IOptionsMonitor optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) - { - OptionsMonitor = optionsMonitor; - SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); - } - - /// - /// Gets the cache state monitor. - /// - public IStateMonitor StateMonitor => State; - - /// - /// Gets the list of shares. - /// - public List Shares { get; private set; } - - private IManagedState State { get; } = new ManagedState(); - private ILogger Log { get; } = Serilog.Log.ForContext(); - private HashSet MaskedDirectories { get; set; } - private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private SqliteConnection SQLite { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private ISoulseekFileFactory SoulseekFileFactory { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - public IEnumerable Browse() - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; - } - - return Enumerable.Empty(); - } - - var directories = new ConcurrentDictionary(); - - // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if - // missing, files that are nested within directories which contain only directories (no files) are displayed as being - // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if - // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the - // files. if not they'll be left as is. - foreach (var directory in MaskedDirectories) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = MaskedFiles - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. - // entries with no files will remain untouched. - foreach (var group in groups) - { - directories.AddOrUpdate(group.Name, group, (_, _) => group); - } - - return directories.Values.OrderBy(f => f.Name); - } - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - public async Task FillAsync() - { - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. - if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) - { - Log.Warning("Shared file scan rejected; scan is already in progress."); - throw new ShareScanInProgressException("Shared files are already being scanned."); - } - - try - { - State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); - Log.Debug("Starting shared file scan"); - - await Task.Yield(); - - ResetCache(); - - var sw = new Stopwatch(); - var swSnapshot = 0L; - sw.Start(); - - Shares = OptionsMonitor.CurrentValue.Directories.Shared - .Select(share => share.TrimEnd('/', '\\')) - .ToHashSet() // remove duplicates - .Select(share => new Share(share)) // convert to Shares - .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent - .ToList(); - - if (!Shares.Any()) - { - Log.Warning("Aborting shared file scan; no shares configured."); - } - - Shares.ForEach(s => Log.Debug(s.ToJson())); - - Shares.Where(s => !s.IsExcluded).ToList() - .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); - - Shares.Where(s => s.IsExcluded).ToList() - .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); - - Log.Debug("Enumerating shared directories"); - swSnapshot = sw.ElapsedMilliseconds; - - var unmaskedDirectories = Shares - .SelectMany(share => - { - try - { - return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); - } - catch (Exception ex) - { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) - - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); - - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); - - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - - var files = new Dictionary(); - var maskedDirectories = new HashSet(); - var current = 0; - var filtered = 0; - - foreach (var directory in unmaskedDirectories) - { - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - - // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized - // filename and with a value of a Soulseek.File object - try - { - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) - .ToDictionary(file => file.Filename, file => file); - - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully - // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var file in newFiles) - { - if (filters.Any(filter => filter.IsMatch(file.Key))) - { - filtered++; - continue; - } - - if (files.ContainsKey(file.Key)) - { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - files[file.Key] = file.Value; - } - } - catch (Exception ex) - { - Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } - - current++; - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); - } - - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - MaskedDirectories = maskedDirectories; - MaskedFiles = files; - - State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); - } - catch (Exception ex) - { - State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); - Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); - throw; - } - finally - { - SyncRoot.Release(); - } - } - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - public Directory List(string directory) - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); - } - - return null; - } - - var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => - { - var f = kvp.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), - f.Size, - f.Extension, - f.Attributes); - }); - - return new Directory(directory, files); - } - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename) - { - filename = filename.ToLocalOSPath(); - var resolved = filename; - - // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a - // file. split the requested filename so we can examine the first two segments - var parts = filename.Split(new[] { '/', '\\' }); - - if (parts.Length < 2) - { - Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); - return resolved; - } - - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); - - if (share == default) - { - Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); - return resolved; - } - - resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); - - if (resolved == filename) - { - Log.Warning($"Failed to resolve shared file {filename}"); - } - - Log.Debug($"Resolved requested shared file {filename} to {resolved}"); - return resolved; - } - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - public async Task> SearchAsync(SearchQuery query) - { - if (!State.CurrentValue.Filled) - { - return Enumerable.Empty(); - } - - string Clean(string str) => str.Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " ") - .Replace("'", "''"); - - var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); - var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; - var results = new List(); - - try - { - using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - using var cmd = new SqliteCommand(sql, conn); - await conn.OpenAsync(); - - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - - try - { - return results.Select(r => MaskedFiles[r]).ToList(); - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); - return Enumerable.Empty(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - SQLite.Open(); - - using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite); - cmd.Parameters.AddWithValue("filename", filename); - cmd.ExecuteNonQuery(); - } - - private void ResetCache() - { - CreateTable(); - MaskedDirectories = new HashSet(); - MaskedFiles = new Dictionary(); - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - } -} \ No newline at end of file diff --git a/src/slskd/Shares/SharesCache.cs b/src/slskd/Shares/SharesCache.cs new file mode 100644 index 00000000..22e72c77 --- /dev/null +++ b/src/slskd/Shares/SharesCache.cs @@ -0,0 +1,482 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System.IO; +using Microsoft.Extensions.Options; + +namespace slskd.Shares +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface IShareCache + { + /// + /// Gets the list of shares. + /// + public List Shares { get; } // todo: remove this + + /// + /// Gets the cache state monitor. + /// + IStateMonitor StateMonitor { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + Task FillAsync(); // TODO: accept a list of shares here + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Directory List(string directory); + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } + + /// + /// Shared file cache. + /// + public class ShareCache : IShareCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public ShareCache( + IOptionsMonitor optionsMonitor, + ISoulseekFileFactory soulseekFileFactory = null) + { + OptionsMonitor = optionsMonitor; + SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); + } + + /// + /// Gets the cache state monitor. + /// + public IStateMonitor StateMonitor => State; + + /// + /// Gets the list of shares. + /// + public List Shares { get; private set; } + + private IManagedState State { get; } = new ManagedState(); + private ILogger Log { get; } = Serilog.Log.ForContext(); + private HashSet MaskedDirectories { get; set; } + private Dictionary MaskedFiles { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private SqliteConnection SQLite { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private ISoulseekFileFactory SoulseekFileFactory { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; + } + + return Enumerable.Empty(); + } + + var directories = new ConcurrentDictionary(); + + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if + // missing, files that are nested within directories which contain only directories (no files) are displayed as being + // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if + // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the + // files. if not they'll be left as is. + foreach (var directory in MaskedDirectories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = MaskedFiles + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values.OrderBy(f => f.Name); + } + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + public async Task FillAsync() + { + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. + if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + try + { + State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + await Task.Yield(); + + ResetCache(); + + var sw = new Stopwatch(); + var swSnapshot = 0L; + sw.Start(); + + Shares = OptionsMonitor.CurrentValue.Directories.Shared + .Select(share => share.TrimEnd('/', '\\')) + .ToHashSet() // remove duplicates + .Select(share => new Share(share)) // convert to Shares + .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent + .ToList(); + + if (!Shares.Any()) + { + Log.Warning("Aborting shared file scan; no shares configured."); + } + + Shares.ForEach(s => Log.Debug(s.ToJson())); + + Shares.Where(s => !s.IsExcluded).ToList() + .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); + + Shares.Where(s => s.IsExcluded).ToList() + .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; + + var unmaskedDirectories = Shares + .SelectMany(share => + { + try + { + return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + return Array.Empty(); + } + }) + .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. + .ToHashSet(); // remove duplicates (in case shares overlap) + + var excludedDirectories = unmaskedDirectories + .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + + unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); + Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + var filters = OptionsMonitor.CurrentValue.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)); + + var files = new Dictionary(); + var maskedDirectories = new HashSet(); + var current = 0; + var filtered = 0; + + foreach (var directory in unmaskedDirectories) + { + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized + // filename and with a value of a Soulseek.File object + try + { + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) + .ToDictionary(file => file.Filename, file => file); + + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. + foreach (var file in newFiles) + { + if (filters.Any(filter => filter.IsMatch(file.Key))) + { + filtered++; + continue; + } + + if (files.ContainsKey(file.Key)) + { + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + } + + files[file.Key] = file.Value; + } + } + catch (Exception ex) + { + Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); + } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); + } + + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + MaskedDirectories = maskedDirectories; + MaskedFiles = files; + + State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; + } + finally + { + SyncRoot.Release(); + } + } + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + public Directory List(string directory) + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); + } + + return null; + } + + var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => + { + var f = kvp.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), + f.Size, + f.Extension, + f.Attributes); + }); + + return new Directory(directory, files); + } + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename) + { + filename = filename.ToLocalOSPath(); + var resolved = filename; + + // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a + // file. split the requested filename so we can examine the first two segments + var parts = filename.Split(new[] { '/', '\\' }); + + if (parts.Length < 2) + { + Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); + return resolved; + } + + // find the share with a matching mask and alias/local directory + var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); + + if (share == default) + { + Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); + return resolved; + } + + resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); + + if (resolved == filename) + { + Log.Warning($"Failed to resolve shared file {filename}"); + } + + Log.Debug($"Resolved requested shared file {filename} to {resolved}"); + return resolved; + } + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + public async Task> SearchAsync(SearchQuery query) + { + if (!State.CurrentValue.Filled) + { + return Enumerable.Empty(); + } + + string Clean(string str) => str.Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " ") + .Replace("'", "''"); + + var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); + var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; + var results = new List(); + + try + { + using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + using var cmd = new SqliteCommand(sql, conn); + await conn.OpenAsync(); + + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); + return Enumerable.Empty(); + } + + try + { + return results.Select(r => MaskedFiles[r]).ToList(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); + return Enumerable.Empty(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + SQLite.Open(); + + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite); + cmd.Parameters.AddWithValue("filename", filename); + cmd.ExecuteNonQuery(); + } + + private void ResetCache() + { + CreateTable(); + MaskedDirectories = new HashSet(); + MaskedFiles = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/SoulseekFileFactory.cs b/src/slskd/Shares/SoulseekFileFactory.cs index 5221265b..7cdd6174 100644 --- a/src/slskd/Shares/SoulseekFileFactory.cs +++ b/src/slskd/Shares/SoulseekFileFactory.cs @@ -48,7 +48,7 @@ namespace slskd.Shares private static readonly string[] VideoExtensions = { "mkv", "ogv", "avi", "wmv", "asf", "mp4", "m4p", "m4v", "mpg", "mpe", "mpv", "mpg", "m2v" }; private static readonly HashSet SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet(); - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Creates an instance of from the given path. diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 0daa5d76..b84efb6c 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -35,7 +35,7 @@ namespace slskd public bool PendingShareRescan { get; init; } public ServerState Server { get; init; } = new ServerState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); - public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); + public ShareState Shares { get; init; } = new ShareState(); public string[] Rooms { get; init; } = Array.Empty(); public User[] Users { get; init; } = Array.Empty(); } @@ -76,43 +76,49 @@ namespace slskd } /// - /// Share cache state. + /// Share state. /// - public record SharedFileCacheState + public record ShareState { - /// - /// Gets a value indicating whether the cache is being filled. - /// - public bool Filling { get; init; } = false; + public ShareCacheState Cache { get; init; } = new ShareCacheState(); + public bool ScanPending { get; init; } - /// - /// Gets a value indicating whether the cache is filled. - /// - public bool Filled { get; init; } = false; + public record ShareCacheState + { + /// + /// Gets a value indicating whether the cache is being filled. + /// + public bool Filling { get; init; } = false; - /// - /// Gets a value indicating whether the cache is faulted. - /// - public bool Faulted { get; init; } = false; + /// + /// Gets a value indicating whether the cache is filled. + /// + public bool Filled { get; init; } = false; - /// - /// Gets the current fill progress. - /// - public double FillProgress { get; init; } + /// + /// Gets a value indicating whether the cache is faulted. + /// + public bool Faulted { get; init; } = false; - /// - /// Gets the number of cached directories. - /// - public int Directories { get; init; } + /// + /// Gets the current fill progress. + /// + public double FillProgress { get; init; } - /// - /// Gets the number of cached files. - /// - public int Files { get; init; } + /// + /// Gets the number of cached directories. + /// + public int Directories { get; init; } - /// - /// Gets the number of directories excluded by filters. - /// - public int ExcludedDirectories { get; init; } + /// + /// Gets the number of cached files. + /// + public int Files { get; init; } + + /// + /// Gets the number of directories excluded by filters. + /// + public int ExcludedDirectories { get; init; } + } } } \ No newline at end of file -- cgit v1.2.3 From d9bd83fbec533d86e43e0a55ba3543948eba96ff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 13:54:26 -0500 Subject: ShareCacheState -> CacheState --- src/slskd/State.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/State.cs b/src/slskd/State.cs index b84efb6c..05a96a76 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -80,10 +80,10 @@ namespace slskd /// public record ShareState { - public ShareCacheState Cache { get; init; } = new ShareCacheState(); + public CacheState Cache { get; init; } = new CacheState(); public bool ScanPending { get; init; } - public record ShareCacheState + public record CacheState { /// /// Gets a value indicating whether the cache is being filled. -- cgit v1.2.3 From 1856c9c569aad24e59ab87a73e3f5fd10ec1cbcf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 14:39:51 -0500 Subject: fix warning --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c0390c5a..110b1d4f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -616,7 +616,7 @@ namespace slskd // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. - Task.Run(async () => + _ = Task.Run(async () => { // users with uploads must be watched so that we can keep informed of their // online status, privileges, and statistics. this is so that we can accurately -- cgit v1.2.3 From b5557cc484f7a24b3a6f35d4e3398ffeddb4e371 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 14:41:36 -0500 Subject: rename once again --- src/slskd/Shares/SharedFileCache.cs | 473 +++++++++++++++++++++++++++++++++++ src/slskd/Shares/SharesCache.cs | 482 ------------------------------------ 2 files changed, 473 insertions(+), 482 deletions(-) create mode 100644 src/slskd/Shares/SharedFileCache.cs delete mode 100644 src/slskd/Shares/SharesCache.cs (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs new file mode 100644 index 00000000..1a465903 --- /dev/null +++ b/src/slskd/Shares/SharedFileCache.cs @@ -0,0 +1,473 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System.IO; +using Microsoft.Extensions.Options; + +namespace slskd.Shares +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface ISharedFileCache + { + /// + /// Gets the cache state monitor. + /// + IStateMonitor StateMonitor { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Scans the configured shares and fills the cache. + /// + /// + /// Initiates the scan, then yields + /// + /// The list of shares from which to fill the cache. + /// The operation context. + Task FillAsync(IEnumerable shares); + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Directory List(string directory); + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } + + /// + /// Shared file cache. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SharedFileCache( + IOptionsMonitor optionsMonitor, + ISoulseekFileFactory soulseekFileFactory = null) + { + OptionsMonitor = optionsMonitor; + SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); + } + + /// + /// Gets the cache state monitor. + /// + public IStateMonitor StateMonitor => State; + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private HashSet MaskedDirectories { get; set; } + private Dictionary MaskedFiles { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private List Shares { get; set; } + private ISoulseekFileFactory SoulseekFileFactory { get; } + private SqliteConnection SQLite { get; set; } + private IManagedState State { get; } = new ManagedState(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; + } + + return Enumerable.Empty(); + } + + var directories = new ConcurrentDictionary(); + + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if + // missing, files that are nested within directories which contain only directories (no files) are displayed as being + // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if + // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the + // files. if not they'll be left as is. + foreach (var directory in MaskedDirectories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = MaskedFiles + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values.OrderBy(f => f.Name); + } + + /// + /// Scans the configured shares and fills the cache. + /// + /// The list of shares from which to fill the cache. + /// The operation context. + public async Task FillAsync(IEnumerable shares) + { + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. + if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + try + { + State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + await Task.Yield(); + + ResetCache(); + + var sw = new Stopwatch(); + var swSnapshot = 0L; + sw.Start(); + + Shares = shares.ToList(); + + if (!Shares.Any()) + { + Log.Warning("Aborting shared file scan; no shares configured."); + } + + Shares.ForEach(s => Log.Debug(s.ToJson())); + + Shares.Where(s => !s.IsExcluded).ToList() + .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); + + Shares.Where(s => s.IsExcluded).ToList() + .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; + + var unmaskedDirectories = Shares + .SelectMany(share => + { + try + { + return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + return Array.Empty(); + } + }) + .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. + .ToHashSet(); // remove duplicates (in case shares overlap) + + var excludedDirectories = unmaskedDirectories + .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + + unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); + Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + var filters = OptionsMonitor.CurrentValue.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)); + + var files = new Dictionary(); + var maskedDirectories = new HashSet(); + var current = 0; + var filtered = 0; + + foreach (var directory in unmaskedDirectories) + { + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized + // filename and with a value of a Soulseek.File object + try + { + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) + .ToDictionary(file => file.Filename, file => file); + + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. + foreach (var file in newFiles) + { + if (filters.Any(filter => filter.IsMatch(file.Key))) + { + filtered++; + continue; + } + + if (files.ContainsKey(file.Key)) + { + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + } + + files[file.Key] = file.Value; + } + } + catch (Exception ex) + { + Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); + } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); + } + + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + MaskedDirectories = maskedDirectories; + MaskedFiles = files; + + State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; + } + finally + { + SyncRoot.Release(); + } + } + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + public Directory List(string directory) + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); + } + + return null; + } + + var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => + { + var f = kvp.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), + f.Size, + f.Extension, + f.Attributes); + }); + + return new Directory(directory, files); + } + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename) + { + filename = filename.ToLocalOSPath(); + var resolved = filename; + + // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a + // file. split the requested filename so we can examine the first two segments + var parts = filename.Split(new[] { '/', '\\' }); + + if (parts.Length < 2) + { + Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); + return resolved; + } + + // find the share with a matching mask and alias/local directory + var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); + + if (share == default) + { + Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); + return resolved; + } + + resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); + + if (resolved == filename) + { + Log.Warning($"Failed to resolve shared file {filename}"); + } + + Log.Debug($"Resolved requested shared file {filename} to {resolved}"); + return resolved; + } + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + public async Task> SearchAsync(SearchQuery query) + { + if (!State.CurrentValue.Filled) + { + return Enumerable.Empty(); + } + + string Clean(string str) => str.Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " ") + .Replace("'", "''"); + + var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); + var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; + var results = new List(); + + try + { + using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + using var cmd = new SqliteCommand(sql, conn); + await conn.OpenAsync(); + + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); + return Enumerable.Empty(); + } + + try + { + return results.Select(r => MaskedFiles[r]).ToList(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); + return Enumerable.Empty(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + SQLite.Open(); + + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite); + cmd.Parameters.AddWithValue("filename", filename); + cmd.ExecuteNonQuery(); + } + + private void ResetCache() + { + CreateTable(); + MaskedDirectories = new HashSet(); + MaskedFiles = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/SharesCache.cs b/src/slskd/Shares/SharesCache.cs deleted file mode 100644 index 22e72c77..00000000 --- a/src/slskd/Shares/SharesCache.cs +++ /dev/null @@ -1,482 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -using System.IO; -using Microsoft.Extensions.Options; - -namespace slskd.Shares -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Shared file cache. - /// - public interface IShareCache - { - /// - /// Gets the list of shares. - /// - public List Shares { get; } // todo: remove this - - /// - /// Gets the cache state monitor. - /// - IStateMonitor StateMonitor { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - IEnumerable Browse(); - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - Task FillAsync(); // TODO: accept a list of shares here - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - Directory List(string directory); - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - Task> SearchAsync(SearchQuery query); - } - - /// - /// Shared file cache. - /// - public class ShareCache : IShareCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public ShareCache( - IOptionsMonitor optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) - { - OptionsMonitor = optionsMonitor; - SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); - } - - /// - /// Gets the cache state monitor. - /// - public IStateMonitor StateMonitor => State; - - /// - /// Gets the list of shares. - /// - public List Shares { get; private set; } - - private IManagedState State { get; } = new ManagedState(); - private ILogger Log { get; } = Serilog.Log.ForContext(); - private HashSet MaskedDirectories { get; set; } - private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private SqliteConnection SQLite { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private ISoulseekFileFactory SoulseekFileFactory { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - public IEnumerable Browse() - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; - } - - return Enumerable.Empty(); - } - - var directories = new ConcurrentDictionary(); - - // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if - // missing, files that are nested within directories which contain only directories (no files) are displayed as being - // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if - // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the - // files. if not they'll be left as is. - foreach (var directory in MaskedDirectories) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = MaskedFiles - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. - // entries with no files will remain untouched. - foreach (var group in groups) - { - directories.AddOrUpdate(group.Name, group, (_, _) => group); - } - - return directories.Values.OrderBy(f => f.Name); - } - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - public async Task FillAsync() - { - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. - if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) - { - Log.Warning("Shared file scan rejected; scan is already in progress."); - throw new ShareScanInProgressException("Shared files are already being scanned."); - } - - try - { - State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); - Log.Debug("Starting shared file scan"); - - await Task.Yield(); - - ResetCache(); - - var sw = new Stopwatch(); - var swSnapshot = 0L; - sw.Start(); - - Shares = OptionsMonitor.CurrentValue.Directories.Shared - .Select(share => share.TrimEnd('/', '\\')) - .ToHashSet() // remove duplicates - .Select(share => new Share(share)) // convert to Shares - .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent - .ToList(); - - if (!Shares.Any()) - { - Log.Warning("Aborting shared file scan; no shares configured."); - } - - Shares.ForEach(s => Log.Debug(s.ToJson())); - - Shares.Where(s => !s.IsExcluded).ToList() - .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); - - Shares.Where(s => s.IsExcluded).ToList() - .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); - - Log.Debug("Enumerating shared directories"); - swSnapshot = sw.ElapsedMilliseconds; - - var unmaskedDirectories = Shares - .SelectMany(share => - { - try - { - return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); - } - catch (Exception ex) - { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) - - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); - - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); - - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - - var files = new Dictionary(); - var maskedDirectories = new HashSet(); - var current = 0; - var filtered = 0; - - foreach (var directory in unmaskedDirectories) - { - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - - // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized - // filename and with a value of a Soulseek.File object - try - { - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) - .ToDictionary(file => file.Filename, file => file); - - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully - // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var file in newFiles) - { - if (filters.Any(filter => filter.IsMatch(file.Key))) - { - filtered++; - continue; - } - - if (files.ContainsKey(file.Key)) - { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - files[file.Key] = file.Value; - } - } - catch (Exception ex) - { - Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } - - current++; - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); - } - - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - MaskedDirectories = maskedDirectories; - MaskedFiles = files; - - State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); - } - catch (Exception ex) - { - State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); - Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); - throw; - } - finally - { - SyncRoot.Release(); - } - } - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - public Directory List(string directory) - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); - } - - return null; - } - - var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => - { - var f = kvp.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), - f.Size, - f.Extension, - f.Attributes); - }); - - return new Directory(directory, files); - } - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename) - { - filename = filename.ToLocalOSPath(); - var resolved = filename; - - // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a - // file. split the requested filename so we can examine the first two segments - var parts = filename.Split(new[] { '/', '\\' }); - - if (parts.Length < 2) - { - Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); - return resolved; - } - - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); - - if (share == default) - { - Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); - return resolved; - } - - resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); - - if (resolved == filename) - { - Log.Warning($"Failed to resolve shared file {filename}"); - } - - Log.Debug($"Resolved requested shared file {filename} to {resolved}"); - return resolved; - } - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - public async Task> SearchAsync(SearchQuery query) - { - if (!State.CurrentValue.Filled) - { - return Enumerable.Empty(); - } - - string Clean(string str) => str.Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " ") - .Replace("'", "''"); - - var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); - var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; - var results = new List(); - - try - { - using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - using var cmd = new SqliteCommand(sql, conn); - await conn.OpenAsync(); - - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - - try - { - return results.Select(r => MaskedFiles[r]).ToList(); - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); - return Enumerable.Empty(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - SQLite.Open(); - - using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite); - cmd.Parameters.AddWithValue("filename", filename); - cmd.ExecuteNonQuery(); - } - - private void ResetCache() - { - CreateTable(); - MaskedDirectories = new HashSet(); - MaskedFiles = new Dictionary(); - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - } -} \ No newline at end of file -- cgit v1.2.3 From 48548c7eb96fb723f67aea71dc9760581b41ac68 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:10:45 -0500 Subject: simplify share state --- src/slskd/State.cs | 67 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 35 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 05a96a76..863c59da 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -80,45 +80,48 @@ namespace slskd /// public record ShareState { - public CacheState Cache { get; init; } = new CacheState(); public bool ScanPending { get; init; } + public bool Scanning { get; init; } + public double ScanProgress { get; init; } + public int Directories { get; init; } + public int Files { get; init; } + } - public record CacheState - { - /// - /// Gets a value indicating whether the cache is being filled. - /// - public bool Filling { get; init; } = false; + public record SharedFileCacheState + { + /// + /// Gets a value indicating whether the cache is being filled. + /// + public bool Filling { get; init; } = false; - /// - /// Gets a value indicating whether the cache is filled. - /// - public bool Filled { get; init; } = false; + /// + /// Gets a value indicating whether the cache is filled. + /// + public bool Filled { get; init; } = false; - /// - /// Gets a value indicating whether the cache is faulted. - /// - public bool Faulted { get; init; } = false; + /// + /// Gets a value indicating whether the cache is faulted. + /// + public bool Faulted { get; init; } = false; - /// - /// Gets the current fill progress. - /// - public double FillProgress { get; init; } + /// + /// Gets the current fill progress. + /// + public double FillProgress { get; init; } - /// - /// Gets the number of cached directories. - /// - public int Directories { get; init; } + /// + /// Gets the number of cached directories. + /// + public int Directories { get; init; } - /// - /// Gets the number of cached files. - /// - public int Files { get; init; } + /// + /// Gets the number of cached files. + /// + public int Files { get; init; } - /// - /// Gets the number of directories excluded by filters. - /// - public int ExcludedDirectories { get; init; } - } + /// + /// Gets the number of directories excluded by filters. + /// + public int ExcludedDirectories { get; init; } } } \ No newline at end of file -- cgit v1.2.3 From a95df84e99b5b447da44955901dd6d0ad1816de6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:10:54 -0500 Subject: add generic NotFoundException --- src/slskd/Common/Exceptions/NotFoundException.cs | 72 ++++++++++++++++++++++ src/slskd/Common/Exceptions/ShareAliasException.cs | 72 ---------------------- 2 files changed, 72 insertions(+), 72 deletions(-) create mode 100644 src/slskd/Common/Exceptions/NotFoundException.cs delete mode 100644 src/slskd/Common/Exceptions/ShareAliasException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/NotFoundException.cs b/src/slskd/Common/Exceptions/NotFoundException.cs new file mode 100644 index 00000000..cc0f6969 --- /dev/null +++ b/src/slskd/Common/Exceptions/NotFoundException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents errors that originate when a searched resource can't be located. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class NotFoundException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public NotFoundException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public NotFoundException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public NotFoundException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected NotFoundException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Exceptions/ShareAliasException.cs b/src/slskd/Common/Exceptions/ShareAliasException.cs deleted file mode 100644 index 3047d0a9..00000000 --- a/src/slskd/Common/Exceptions/ShareAliasException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents an error that occurs when multiple share scans are attempted concurrently. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class ShareAliasException : SlskdException - { - /// - /// Initializes a new instance of the class. - /// - public ShareAliasException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public ShareAliasException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public ShareAliasException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected ShareAliasException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file -- cgit v1.2.3 From 41897719b57ac3b64a1a9f2f78982e6c9b6dc868 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:11:06 -0500 Subject: split/finalize IShareService --- src/slskd/Shares/IShareService.cs | 77 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/slskd/Shares/IShareService.cs (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs new file mode 100644 index 00000000..cc91ba07 --- /dev/null +++ b/src/slskd/Shares/IShareService.cs @@ -0,0 +1,77 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Soulseek; + + /// + /// Provides control and interactions with configured shares and shared files. + /// + public interface IShareService + { + /// + /// Gets the list of configured shares. + /// + IReadOnlyList Shares { get; } + + /// + /// Gets the state monitor for the service. + /// + public IStateMonitor StateMonitor { get; } + + /// + /// Returns the entire contents of the share. + /// + /// The entire contents of the share. + Task> BrowseAsync(); + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Task ListAsync(string directory); + + /// + /// Resolves the local filename of the specified , if the mask is associated with a + /// configured share. + /// + /// The fully qualified filename to resolve. + /// The resolved local filename. + /// + /// Thrown when the specified remote filename can not be associated with a configured share. + /// + Task ResolveAsync(string remoteFilename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + + /// + /// Starts a scan of the configured shares. + /// + /// The operation context. + /// Thrown when a scan is already in progress. + Task StartScanAsync(); + } +} -- cgit v1.2.3 From 5b7744f92c8b3913844942d2d44f90cdbc65cb4e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:11:24 -0500 Subject: rename one final time --- src/slskd/Shares/SharedFileCache.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 1a465903..b06f7be6 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -40,7 +40,7 @@ namespace slskd.Shares /// /// Gets the cache state monitor. /// - IStateMonitor StateMonitor { get; } + IStateMonitor StateMonitor { get; } /// /// Returns the contents of the cache. @@ -51,9 +51,7 @@ namespace slskd.Shares /// /// Scans the configured shares and fills the cache. /// - /// - /// Initiates the scan, then yields - /// + /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. /// The list of shares from which to fill the cache. /// The operation context. Task FillAsync(IEnumerable shares); @@ -102,7 +100,7 @@ namespace slskd.Shares /// /// Gets the cache state monitor. /// - public IStateMonitor StateMonitor => State; + public IStateMonitor StateMonitor => State; private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } @@ -111,7 +109,7 @@ namespace slskd.Shares private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private SqliteConnection SQLite { get; set; } - private IManagedState State { get; } = new ManagedState(); + private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); /// -- cgit v1.2.3 From a1b481cfbb0483e54266f2dfeed80ceb070d0f63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:11:35 -0500 Subject: docs --- src/slskd/Shares/ShareService.cs | 144 ++++++++++++++++++++++++++++++--------- 1 file changed, 110 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 68b3c629..103a96fc 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -19,67 +19,143 @@ using Microsoft.Extensions.Options; namespace slskd.Shares { - using System; using System.Collections.Generic; using System.Linq; + using System.Threading; using System.Threading.Tasks; using Soulseek; - public interface IShareService - { - IReadOnlyList Shares { get; } - - Task> BrowseAsync(); - - Task ListAsync(string directory); - - Task> SearchAsync(SearchQuery query); - - Task StartScanAsync(); - - Task ResolveAsync(string remoteFilename); - - public IStateMonitor StateMonitor { get; } - } - + /// + /// Provides control and interactions with configured shares and shared files. + /// public class ShareService : IShareService { + /// + /// Initializes a new instance of the class. + /// + /// + /// public ShareService( IOptionsMonitor optionsMonitor, - IShareCache sharesCache = null) + ISharedFileCache sharedFileCache = null) { OptionsMonitor = optionsMonitor; - - // todo: when options change, fill SharesList with configured shares - // and set ScanPending = true - - Cache = sharesCache ?? new ShareCache(OptionsMonitor); - Cache.StateMonitor.OnChange(cacheState - => State.SetValue(state - => state with { Cache = cacheState.Current })); + OptionsMonitor.OnChange(Configure); + + Cache = sharedFileCache ?? new SharedFileCache(OptionsMonitor); + Cache.StateMonitor.OnChange(cacheState => + { + var (previous, current) = cacheState; + + State.SetValue(state => state with + { + ScanPending = current.Faulted || ((previous.Filling && !current.Filling) ? false : state.ScanPending), + Scanning = current.Filling, + ScanProgress = current.FillProgress, + Directories = current.Directories, + Files = current.Files, + }); + }); } + /// + /// Gets the list of configured shares. + /// public IReadOnlyList Shares => SharesList.AsReadOnly(); + + /// + /// Gets the state monitor for the service. + /// public IStateMonitor StateMonitor => State; - private IShareCache Cache { get; } + private ISharedFileCache Cache { get; } + private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } private List SharesList { get; set; } = new List(); private IManagedState State { get; } = new ManagedState(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - public Task> BrowseAsync() + /// + /// Returns the entire contents of the share. + /// + /// The entire contents of the share. + public Task> BrowseAsync() => Task.FromResult(Cache.Browse()); - public Task ListAsync(string directory) + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + public Task ListAsync(string directory) => Task.FromResult(Cache.List(directory)); - public Task> SearchAsync(SearchQuery query) + /// + /// Resolves the local filename of the specified , if the mask is associated with a + /// configured share. + /// + /// The fully qualified filename to resolve. + /// The resolved local filename. + /// + /// Thrown when the specified remote filename can not be associated with a configured share. + /// + public Task ResolveAsync(string remoteFilename) + { + var resolvedFilename = Cache.Resolve(remoteFilename); + + if (resolvedFilename == remoteFilename) + { + throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a configured share."); + } + + return Task.FromResult(resolvedFilename); + } + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + public Task> SearchAsync(SearchQuery query) => Cache.SearchAsync(query); + /// + /// Starts a scan of the configured shares. + /// + /// The operation context. + /// Thrown when a scan is already in progress. public Task StartScanAsync() - => Cache.FillAsync(); + => Cache.FillAsync(Shares); - public Task ResolveAsync(string remoteFilename) - => Task.FromResult(Cache.Resolve(remoteFilename)); + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Directories.Shared)); + + if (optionsHash == LastOptionsHash) + { + return; + } + + var shares = options.Directories.Shared + .Select(share => share.TrimEnd('/', '\\')) + .ToHashSet() // remove duplicates + .Select(share => new Share(share)) // convert to Shares + .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent + .ToList(); + + SharesList = shares; + State.SetValue(state => state with { ScanPending = true }); + + LastOptionsHash = optionsHash; + } + finally + { + SyncRoot.Release(); + } + } } } \ No newline at end of file -- cgit v1.2.3 From c8c97202df9b7e25a1ee84d264f324960e1c548e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:15:29 -0500 Subject: remove app state monitor dependency --- src/slskd/Shares/API/Controllers/SharesController.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 251f50b9..990d6143 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -38,13 +38,10 @@ namespace slskd.Shares.API /// Initializes a new instance of the class. /// /// - /// public SharesController( - IShareService shareService, - IStateMonitor applicationStateMonitor) + IShareService shareService) { Shares = shareService; - ApplicationStateMonitor = applicationStateMonitor; } private IShareService Shares { get; } @@ -181,15 +178,17 @@ namespace slskd.Shares.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(409)] - public IActionResult RescanSharesAsync() + public async Task RescanSharesAsync() { - if (ApplicationStateMonitor.CurrentValue.Shares.Cache.Filling) + try + { + await Shares.StartScanAsync(); + } + catch (ShareScanInProgressException) { return Conflict("A share scan is already in progress."); } - _ = Shares.StartScanAsync(); - return Ok(); } } -- cgit v1.2.3 From d72da4b8a2134686a68c914b7b5537dc91ba5da5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:16:44 -0500 Subject: using Soulseek --- src/slskd/Shares/API/Controllers/SharesController.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 990d6143..300bbf5a 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -22,6 +22,7 @@ namespace slskd.Shares.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Soulseek; /// /// Shares. @@ -136,7 +137,7 @@ namespace slskd.Shares.API /// The request completed successfully. [HttpGet("contents")] [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(typeof(IEnumerable), 200)] public async Task BrowseAll() { return Ok(await Shares.BrowseAsync()); @@ -150,7 +151,7 @@ namespace slskd.Shares.API /// The request completed successfully. /// The requested share could not be found. [HttpGet("{id}/contents")] - [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] public async Task BrowseShare(string id) { -- cgit v1.2.3 From 3019ed0a76fac1fdedaccc82aca7546f729d42ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 31 May 2022 10:11:52 -0500 Subject: tweak expression --- src/slskd/Shares/ShareService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 103a96fc..d99c5f6a 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -49,7 +49,8 @@ namespace slskd.Shares State.SetValue(state => state with { - ScanPending = current.Faulted || ((previous.Filling && !current.Filling) ? false : state.ScanPending), + // scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending + ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending), Scanning = current.Filling, ScanProgress = current.FillProgress, Directories = current.Directories, -- cgit v1.2.3 From f6aad956a83155e8e89add7e24804d6b99ec4119 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 09:38:17 -0500 Subject: light refactoring --- src/slskd/Application.cs | 44 +++++++++++++++++++++++---------------- src/slskd/Program.cs | 2 +- src/slskd/Search/SearchService.cs | 15 ++++++++----- src/slskd/Shares/IShareService.cs | 4 ++-- src/slskd/Shares/ShareService.cs | 5 +++-- src/slskd/State.cs | 1 + 6 files changed, 43 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 110b1d4f..880e8f74 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -441,7 +441,7 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero // initially, but we'll update them when the cache is filled. - _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -509,9 +509,7 @@ namespace slskd private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) { - // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] - // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] - // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); + // no-op. this is really verbose, use for troubleshooting. } private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) @@ -555,7 +553,7 @@ namespace slskd /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. private async Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = await Shares.ListAsync(directory); + var dir = await Shares.ListDirectoryAsync(directory); return dir; } @@ -577,15 +575,25 @@ namespace slskd private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; - var localFilename = (await Shares.ResolveAsync(filename)).ToLocalOSPath(); - - var fileInfo = new FileInfo(localFilename); + string localFilename; + FileInfo fileInfo = default; Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); - if (!fileInfo.Exists) + try + { + localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); + + fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + throw new NotFoundException(); + } + } + catch (NotFoundException) { - Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); throw new DownloadEnqueueException($"File not shared."); } @@ -840,7 +848,7 @@ namespace slskd { var (previous, current) = state; - if (!previous.Cache.Filling && current.Cache.Filling) + if (!previous.Scanning && current.Scanning) { SharesRefreshStarted = DateTime.UtcNow; @@ -848,33 +856,33 @@ namespace slskd Log.Information("Scanning shares"); } - var lastProgress = Math.Round(previous.Cache.FillProgress * 100); - var currentProgress = Math.Round(current.Cache.FillProgress * 100); + var lastProgress = Math.Round(previous.ScanProgress * 100); + var currentProgress = Math.Round(current.ScanProgress * 100); if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { State.SetValue(s => s with { Shares = current }); - Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Cache.Files); + Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); } - if (previous.Cache.Filling && !current.Cache.Filling) + if (previous.Scanning && !current.Scanning) { State.SetValue(s => s with { Shares = current }); - if (current.Cache.Faulted) + if (current.Faulted) { Log.Error("Failed to scan shares."); } else { State.SetValue(s => s with { PendingShareRescan = false }); - Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Cache.Directories, current.Cache.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) { - _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 1a5d2a28..df1fb55c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -682,7 +682,7 @@ namespace slskd } // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused. - // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next + // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next // middleware app.Use(async (context, next) => { diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 949a7088..f077e76b 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -162,18 +162,23 @@ namespace slskd.Search /// /// The search to delete. /// The operation context. - public async Task DeleteAsync(Search search) + public Task DeleteAsync(Search search) { if (search == default) { throw new ArgumentNullException(nameof(search)); } - using var context = ContextFactory.CreateDbContext(); - context.Searches.Remove(search); - await context.SaveChangesAsync(); + return DoDeleteAsync(search); - await SearchHub.BroadcastDeleteAsync(search); + async Task DoDeleteAsync(Search search) + { + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + + await SearchHub.BroadcastDeleteAsync(search); + } } /// diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index cc91ba07..16f1a890 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -47,7 +47,7 @@ namespace slskd.Shares /// /// The directory for which the contents are to be listed. /// The contents of the directory. - Task ListAsync(string directory); + Task ListDirectoryAsync(string directory); /// /// Resolves the local filename of the specified , if the mask is associated with a @@ -58,7 +58,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - Task ResolveAsync(string remoteFilename); + Task ResolveFilenameAsync(string remoteFilename); /// /// Searches the cache for the specified and returns the matching files. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d99c5f6a..7c08ad13 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -52,6 +52,7 @@ namespace slskd.Shares // scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending), Scanning = current.Filling, + Faulted = current.Faulted, ScanProgress = current.FillProgress, Directories = current.Directories, Files = current.Files, @@ -88,7 +89,7 @@ namespace slskd.Shares /// /// The directory for which the contents are to be listed. /// The contents of the directory. - public Task ListAsync(string directory) + public Task ListDirectoryAsync(string directory) => Task.FromResult(Cache.List(directory)); /// @@ -100,7 +101,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - public Task ResolveAsync(string remoteFilename) + public Task ResolveFilenameAsync(string remoteFilename) { var resolvedFilename = Cache.Resolve(remoteFilename); diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 863c59da..407aeb9e 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -82,6 +82,7 @@ namespace slskd { public bool ScanPending { get; init; } public bool Scanning { get; init; } + public bool Faulted { get; init; } public double ScanProgress { get; init; } public int Directories { get; init; } public int Files { get; init; } -- cgit v1.2.3 From a1a2ab7961c2107e063e77020877d82e36c7c296 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:13:45 -0500 Subject: add small placeholder css --- src/web/src/components/App.css | 15 ++++++++++++++- src/web/src/components/Shared/PlaceholderSegment.js | 19 +++++++++++-------- 2 files changed, 25 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 9c06bf34..78b029b8 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -101,10 +101,23 @@ body { line-height: 1.15 !important; } -.placeholder-segment { +.placeholder-segment, .placeholder-segment-small { opacity: .25; } +.placeholder-segment-small { + min-height: 6rem !important; +} + +.placeholder-segment-small > .ui.icon.header { + font-size: 1em !important; +} + +.placeholder-segment-small > .ui.icon.header > i { + font-size: 2em !important; +} + + .menu-icon-group { font-size: 1.71428571em !important; margin: 0 auto .5rem !important; diff --git a/src/web/src/components/Shared/PlaceholderSegment.js b/src/web/src/components/Shared/PlaceholderSegment.js index 0307b9e0..31ac8e9e 100644 --- a/src/web/src/components/Shared/PlaceholderSegment.js +++ b/src/web/src/components/Shared/PlaceholderSegment.js @@ -2,13 +2,16 @@ import React from 'react'; import { Segment, Header, Icon } from 'semantic-ui-react'; -const PlaceholderSegment = ({ icon, caption, ...rest }) => ( - -
- - {caption} -
-
-); +const PlaceholderSegment = ({ icon, caption, size, ...rest }) => { + const className = size === 'small' ? 'placeholder-segment-small' : 'placeholder-segment'; + + return ( + +
+ + {caption} +
+
); +}; export default PlaceholderSegment; \ No newline at end of file -- cgit v1.2.3 From c85441d966446bda8e4ca771bb74ed02c7970209 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:29:23 -0500 Subject: remove unused ApplicationStateMonitor --- src/slskd/Shares/API/Controllers/SharesController.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 300bbf5a..8ae8551f 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -46,7 +46,6 @@ namespace slskd.Shares.API } private IShareService Shares { get; } - private IStateMonitor ApplicationStateMonitor { get; } /// /// Gets the current list of shares. -- cgit v1.2.3 From ccd0e524b7c2d60362ea272140080e5cc52ab08a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:29:45 -0500 Subject: show placeholder if no shares are configured --- src/web/src/components/System/Shares/index.js | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 5fe59cb2..53018b45 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -4,6 +4,7 @@ import { toast } from 'react-toastify'; import * as sharesLib from '../../../lib/shares'; import { LoaderSegment, + PlaceholderSegment, ShrinkableButton, Switch, } from '../../Shared'; @@ -64,6 +65,12 @@ const Index = ({ state = {} } = {}) => { } + empty={shared.length === 0 && + } > -- cgit v1.2.3 From 1da4e1f198aff7f5ad7f61381d481acc8dc7119c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:56:34 -0500 Subject: pass filters to cache --- src/slskd/Shares/ShareService.cs | 22 +++++++++++++++++----- src/slskd/Shares/SharedFileCache.cs | 19 ++++++++----------- 2 files changed, 25 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 7c08ad13..9cae0d42 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -21,6 +21,7 @@ namespace slskd.Shares { using System.Collections.Generic; using System.Linq; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Soulseek; @@ -39,10 +40,7 @@ namespace slskd.Shares IOptionsMonitor optionsMonitor, ISharedFileCache sharedFileCache = null) { - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); - - Cache = sharedFileCache ?? new SharedFileCache(OptionsMonitor); + Cache = sharedFileCache ?? new SharedFileCache(); Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; @@ -58,6 +56,11 @@ namespace slskd.Shares Files = current.Files, }); }); + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); } /// @@ -65,6 +68,8 @@ namespace slskd.Shares /// public IReadOnlyList Shares => SharesList.AsReadOnly(); + public IReadOnlyList FilterRegexes => FilterRegexList.AsReadOnly(); + /// /// Gets the state monitor for the service. /// @@ -76,6 +81,7 @@ namespace slskd.Shares private List SharesList { get; set; } = new List(); private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private List FilterRegexList { get; set; } = new List(); /// /// Returns the entire contents of the share. @@ -127,7 +133,7 @@ namespace slskd.Shares /// The operation context. /// Thrown when a scan is already in progress. public Task StartScanAsync() - => Cache.FillAsync(Shares); + => Cache.FillAsync(Shares, FilterRegexes); private void Configure(Options options) { @@ -149,7 +155,13 @@ namespace slskd.Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); + var regexes = options.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)) + .ToList(); + SharesList = shares; + FilterRegexList = regexes; + State.SetValue(state => state with { ScanPending = true }); LastOptionsHash = optionsHash; diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index b06f7be6..cb1ccdee 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -53,8 +53,9 @@ namespace slskd.Shares /// /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. /// The list of shares from which to fill the cache. + /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - Task FillAsync(IEnumerable shares); + Task FillAsync(IEnumerable shares, IEnumerable filters); /// /// Returns the contents of the specified . @@ -87,13 +88,9 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// - /// /// - public SharedFileCache( - IOptionsMonitor optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null) { - OptionsMonitor = optionsMonitor; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -105,7 +102,6 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private SqliteConnection SQLite { get; set; } @@ -118,6 +114,7 @@ namespace slskd.Shares /// The contents of the cache. public IEnumerable Browse() { + Console.WriteLine(State.ToJson()); if (!State.CurrentValue.Filled) { if (State.CurrentValue.Filling) @@ -167,9 +164,12 @@ namespace slskd.Shares /// Scans the configured shares and fills the cache. /// /// The list of shares from which to fill the cache. + /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - public async Task FillAsync(IEnumerable shares) + public async Task FillAsync(IEnumerable shares, IEnumerable filters) { + Console.WriteLine($"Filling: {shares.ToJson()}"); + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) { @@ -234,9 +234,6 @@ namespace slskd.Shares Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - var files = new Dictionary(); var maskedDirectories = new HashSet(); var current = 0; -- cgit v1.2.3 From f3b2e02168e77ea8cc9bc68d151aba56e279f9c4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:56:46 -0500 Subject: show empty row in tables --- src/slskd/Shares/SharedFileCache.cs | 4 --- .../src/components/System/Shares/ExclusionTable.js | 20 +++++++++------ src/web/src/components/System/Shares/ShareTable.js | 29 ++++++++++++++-------- src/web/src/components/System/Shares/index.js | 7 ------ 4 files changed, 32 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index cb1ccdee..8ac52462 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -16,7 +16,6 @@ // using System.IO; -using Microsoft.Extensions.Options; namespace slskd.Shares { @@ -114,7 +113,6 @@ namespace slskd.Shares /// The contents of the cache. public IEnumerable Browse() { - Console.WriteLine(State.ToJson()); if (!State.CurrentValue.Filled) { if (State.CurrentValue.Filling) @@ -168,8 +166,6 @@ namespace slskd.Shares /// The operation context. public async Task FillAsync(IEnumerable shares, IEnumerable filters) { - Console.WriteLine($"Filling: {shares.ToJson()}"); - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) { diff --git a/src/web/src/components/System/Shares/ExclusionTable.js b/src/web/src/components/System/Shares/ExclusionTable.js index 90ee2eff..5e010e30 100644 --- a/src/web/src/components/System/Shares/ExclusionTable.js +++ b/src/web/src/components/System/Shares/ExclusionTable.js @@ -5,11 +5,9 @@ import { Icon, } from 'semantic-ui-react'; -const ExclusionTable = ({ exclusions = [] } = {}) => { - if (exclusions.length === 0) { - return <>; - } +import { Switch } from '../../Shared'; +const ExclusionTable = ({ exclusions = [] } = {}) => { return ( @@ -18,9 +16,17 @@ const ExclusionTable = ({ exclusions = [] } = {}) => { - {exclusions.map((share, index) => ( - {share.localPath} - ))} + + + No exclusions configured + + } + > + {exclusions.map((share, index) => ( + {share.localPath} + ))} +
); diff --git a/src/web/src/components/System/Shares/ShareTable.js b/src/web/src/components/System/Shares/ShareTable.js index ecd83e3f..d264fc8f 100644 --- a/src/web/src/components/System/Shares/ShareTable.js +++ b/src/web/src/components/System/Shares/ShareTable.js @@ -6,6 +6,7 @@ import { } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; +import { Switch } from '../../Shared'; const ShareTable = ({ shares, onClick }) => { return ( @@ -20,16 +21,24 @@ const ShareTable = ({ shares, onClick }) => { - {shares.map((share, index) => ( - onClick(share)}> - - {share.localPath} - - {share.directories} - {share.files} - {share.alias} - {share.remotePath} - ))} + + + No shares configured + + } + > + {shares.map((share, index) => ( + onClick(share)}> + + {share.localPath} + + {share.directories} + {share.files} + {share.alias} + {share.remotePath} + ))} + ); diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 53018b45..5fe59cb2 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -4,7 +4,6 @@ import { toast } from 'react-toastify'; import * as sharesLib from '../../../lib/shares'; import { LoaderSegment, - PlaceholderSegment, ShrinkableButton, Switch, } from '../../Shared'; @@ -65,12 +64,6 @@ const Index = ({ state = {} } = {}) => { } - empty={shared.length === 0 && - } > -- cgit v1.2.3 From cbffe2d38e5b7b0831eeacff7ba1ef7973f4f85c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:26:58 -0500 Subject: add serialization constructor --- src/slskd/Shares/Domain/Share.cs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/Domain/Share.cs b/src/slskd/Shares/Domain/Share.cs index 464ab074..9bdbc002 100644 --- a/src/slskd/Shares/Domain/Share.cs +++ b/src/slskd/Shares/Domain/Share.cs @@ -18,6 +18,7 @@ namespace slskd.Shares { using System.Linq; + using System.Text.Json.Serialization; using System.Text.RegularExpressions; /// @@ -25,6 +26,28 @@ namespace slskd.Shares /// public sealed class Share { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + /// + /// + /// + [JsonConstructor] + public Share (string id, string alias, bool isExcluded, string localPath, string mask, string raw, string remotePath) + { + Id = id; + Alias = alias; + IsExcluded = isExcluded; + LocalPath = localPath; + Mask = mask; + Raw = raw; + RemotePath = remotePath; + } + /// /// Initializes a new instance of the class. /// -- cgit v1.2.3 From 2efd8278ce9a5a895fe0c75bd95080ecc386163b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:28:10 -0500 Subject: differentiate configured shares vs cached shares --- src/slskd/Shares/API/Controllers/SharesController.cs | 2 +- src/slskd/Shares/IShareService.cs | 5 +++++ src/slskd/Shares/ShareService.cs | 14 +++++++++++--- src/slskd/Shares/SharedFileCache.cs | 20 ++++++++++++++++++-- src/slskd/State.cs | 9 +++++++-- 5 files changed, 42 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 8ae8551f..41178bac 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -59,7 +59,7 @@ namespace slskd.Shares.API { var browse = await Shares.BrowseAsync(); - var summary = Shares.Shares.Select(share => + var summary = Shares.CachedShares.Select(share => { var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 16f1a890..fd88f2b0 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -26,6 +26,11 @@ namespace slskd.Shares ///
public interface IShareService { + /// + /// Gets the list of shares stored in the cache. + /// + IReadOnlyList CachedShares { get; } + /// /// Gets the list of configured shares. /// diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 9cae0d42..ead96d10 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -55,6 +55,11 @@ namespace slskd.Shares Directories = current.Directories, Files = current.Files, }); + + if (previous.Filling && !current.Filling) + { + CachedShares = current.Shares.ToList().AsReadOnly(); + } }); OptionsMonitor = optionsMonitor; @@ -68,7 +73,10 @@ namespace slskd.Shares ///
public IReadOnlyList Shares => SharesList.AsReadOnly(); - public IReadOnlyList FilterRegexes => FilterRegexList.AsReadOnly(); + /// + /// Gets the list of shares stored in the cache. + /// + public IReadOnlyList CachedShares { get; private set; } = new List().AsReadOnly(); /// /// Gets the state monitor for the service. @@ -81,7 +89,7 @@ namespace slskd.Shares private List SharesList { get; set; } = new List(); private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private List FilterRegexList { get; set; } = new List(); + private List FilterRegexes { get; set; } = new List(); /// /// Returns the entire contents of the share. @@ -160,7 +168,7 @@ namespace slskd.Shares .ToList(); SharesList = shares; - FilterRegexList = regexes; + FilterRegexes = regexes; State.SetValue(state => state with { ScanPending = true }); diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 8ac52462..6b7a3ca3 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -175,7 +175,14 @@ namespace slskd.Shares try { - State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); + State.SetValue(state => state with + { + Filling = true, + Filled = false, + FillProgress = 0, + Shares = Enumerable.Empty().ToList().AsReadOnly(), + }); + Log.Debug("Starting shared file scan"); await Task.Yield(); @@ -291,7 +298,16 @@ namespace slskd.Shares MaskedDirectories = maskedDirectories; MaskedFiles = files; - State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + State.SetValue(state => state with { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = MaskedDirectories.Count, + Files = MaskedFiles.Count, + Shares = shares.ToList().AsReadOnly(), + }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); } catch (Exception ex) diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 407aeb9e..10ed80f6 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -21,6 +21,7 @@ namespace slskd using System.Collections.Generic; using System.Net; using System.Text.Json.Serialization; + using slskd.Shares; using slskd.Users; using Soulseek; @@ -32,7 +33,6 @@ namespace slskd public VersionState Version { get; init; } = new VersionState(); public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } - public bool PendingShareRescan { get; init; } public ServerState Server { get; init; } = new ServerState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); public ShareState Shares { get; init; } = new ShareState(); @@ -69,7 +69,7 @@ namespace slskd public string BranchRoot { get; init; } public bool CanAcceptChildren { get; init; } public int ChildLimit { get; init; } - public IReadOnlyCollection Children { get; init; } + public IReadOnlyCollection Children { get; init; } = new List().AsReadOnly(); public bool HasParent { get; init; } public bool IsBranchRoot { get; init; } public string Parent { get; init; } @@ -124,5 +124,10 @@ namespace slskd /// Gets the number of directories excluded by filters. /// public int ExcludedDirectories { get; init; } + + /// + /// Gets the list of shares stored in the cache. + /// + public IReadOnlyCollection Shares { get; init; } = new List().AsReadOnly(); } } \ No newline at end of file -- cgit v1.2.3 From ce6f897644ab0603e1ccb1ece3b6c9036d4bf5c4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:28:26 -0500 Subject: change how share state is stored --- src/slskd/Application.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 880e8f74..0144daa2 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -679,14 +679,14 @@ namespace slskd if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) { - State.SetValue(state => state with { PendingShareRescan = true }); + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect."); } if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any() || newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any()) { - State.SetValue(state => state with { PendingShareRescan = true }); + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect."); } @@ -875,7 +875,7 @@ namespace slskd } else { - State.SetValue(s => s with { PendingShareRescan = false }); + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; -- cgit v1.2.3 From f67ce78da5d9f6dfb7f4967217ecfbff2cd05dd8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:29:06 -0500 Subject: use console.error when logging errors --- src/web/src/components/Browse/Browse.js | 2 +- src/web/src/components/Transfers/TransferGroup.js | 4 ++-- src/web/src/components/Transfers/Transfers.js | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Browse/Browse.js b/src/web/src/components/Browse/Browse.js index e1a3c7f0..93cf31f0 100644 --- a/src/web/src/components/Browse/Browse.js +++ b/src/web/src/components/Browse/Browse.js @@ -90,7 +90,7 @@ class Browse extends Component { try { localStorage.setItem('soulseek-example-browse-state', lzString.compress(JSON.stringify(this.state))); } catch (error) { - console.log(error); + console.error(error); } }; diff --git a/src/web/src/components/Transfers/TransferGroup.js b/src/web/src/components/Transfers/TransferGroup.js index 023c18a0..ad4ab969 100644 --- a/src/web/src/components/Transfers/TransferGroup.js +++ b/src/web/src/components/Transfers/TransferGroup.js @@ -70,7 +70,7 @@ class TransferGroup extends Component { try { await transfers.download({username, files: [{filename, size }] }); } catch (error) { - console.log(error); + console.error(error); } }; @@ -80,7 +80,7 @@ class TransferGroup extends Component { try { await transfers.getPlaceInQueue({ username, id }); } catch (error) { - console.log(error); + console.error(error); } }; diff --git a/src/web/src/components/Transfers/Transfers.js b/src/web/src/components/Transfers/Transfers.js index 638c0d67..7820400e 100644 --- a/src/web/src/components/Transfers/Transfers.js +++ b/src/web/src/components/Transfers/Transfers.js @@ -64,7 +64,7 @@ const Transfers = ({ direction, server }) => { await transfersLib.download({username, files: [{filename, size }] }); if (!suppressStateChange) setRetrying(false); } catch (error) { - console.log(error); + console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); if (!suppressStateChange) setRetrying(false); } @@ -84,7 +84,7 @@ const Transfers = ({ direction, server }) => { await transfersLib.cancel({ direction, username, id }); if (!suppressStateChange) setCancelling(false); } catch (error) { - console.log(error); + console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); if (!suppressStateChange) setCancelling(false); } @@ -104,7 +104,7 @@ const Transfers = ({ direction, server }) => { await transfersLib.cancel({ direction, username, id, remove: true }); if (!suppressStateChange) setRemoving(false); } catch (error) { - console.log(error); + console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); if (!suppressStateChange) setRemoving(false); } -- cgit v1.2.3 From c3b6ad913e14e58d04d5efc16d4f2cc92a3a1b4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:29:40 -0500 Subject: fix state, use exclamation icon for pending action --- src/web/src/components/App.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 7f488643..fc3f856e 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -116,8 +116,9 @@ class App extends Component { render = () => { const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state; - const { version = {}, server, pendingReconnect, pendingRestart, pendingShareRescan } = applicationState; + const { version = {}, server, pendingReconnect, pendingRestart, shares = {} } = applicationState; const { isUpdateAvailable, current, latest } = version; + const { scanPending: pendingShareRescan } = shares; if (!initialized) { return ; @@ -215,7 +216,7 @@ class App extends Component { {(pendingReconnect || pendingRestart || pendingShareRescan) && - + Pending Action } -- cgit v1.2.3 From 14f2a4d076b96999f74979ae693ba36fb720f60c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:58:48 -0500 Subject: add visual cues when user adction is required --- src/web/src/components/App.js | 2 +- src/web/src/components/System/Info/index.js | 5 ++++- src/web/src/components/System/Shares/index.js | 18 ++++++++------- src/web/src/components/System/System.js | 32 +++++++++++++++++---------- 4 files changed, 35 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index fc3f856e..206cea34 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -203,7 +203,7 @@ class App extends Component { {server?.isConnected && disconnect()} > - Connected + Connected } {(!server?.isConnected) && connect()} diff --git a/src/web/src/components/System/Info/index.js b/src/web/src/components/System/Info/index.js index 063303ac..7068e047 100644 --- a/src/web/src/components/System/Info/index.js +++ b/src/web/src/components/System/Info/index.js @@ -21,6 +21,8 @@ const Info = ({ state }) => { }, 250); }, [state]); + const { pendingRestart } = state; + return ( <>
@@ -57,7 +59,8 @@ const Info = ({ state }) => { Restart diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 5fe59cb2..ceb5746c 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -22,17 +22,18 @@ const Index = ({ state = {} } = {}) => { const [shares, setShares] = useState([]); const [modal, setModal] = useState(false); - const { filling, filled, fillProgress } = state; + const { scanning, scanProgress, scanPending } = state; + const scanned = !scanning; useEffect(() => { getAll(); }, []); useEffect(() => { - if (filled) { + if (scanned) { getAll(); } - }, [filled]); + }, [scanned]); const getAll = async () => { try { @@ -53,17 +54,18 @@ const Index = ({ state = {} } = {}) => { <>
sharesLib.rescan()} - >{filling ? 'Scanning shares' : 'Rescan Shares'} + >{scanning ? 'Scanning shares' : 'Rescan Shares'}
} + filling={(loading || scanning) && {Math.round(scanProgress * 100)}%} > diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js index 6c0229cf..2be10f81 100644 --- a/src/web/src/components/System/System.js +++ b/src/web/src/components/System/System.js @@ -1,7 +1,7 @@ import React from 'react'; import { useRouteMatch, useHistory, Redirect } from 'react-router-dom'; -import { Segment, Tab } from 'semantic-ui-react'; +import { Segment, Tab, Menu, Icon } from 'semantic-ui-react'; import './System.css'; @@ -9,6 +9,7 @@ import Info from './Info'; import Logs from './Logs'; import Options from './Options'; import Shares from './Shares'; +import { Switch } from '../Shared'; const System = ({ state = {}, options = {} }) => { const { params: { tab }, ...route } = useRouteMatch(); @@ -17,11 +18,15 @@ const System = ({ state = {}, options = {} }) => { const panes = [ { route: 'info', - menuItem: { - key: 'info', - icon: 'info', - content: 'Info', - }, + menuItem: ( + } + > + + + Info + ), render: () => , }, { @@ -35,12 +40,15 @@ const System = ({ state = {}, options = {} }) => { }, { route: 'shares', - menuItem: { - key: 'shares', - icon: 'share external', - content: 'Shares', - }, - render: () => , + menuItem: ( + } + > + + + Shares + ), + render: () => , }, { route: 'logs', -- cgit v1.2.3 From 9e0013c0317adbaa007fce8dbea06928b1d159ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 08:30:28 -0500 Subject: remove unused import --- src/web/src/components/Search/List/SearchList.js | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js index 5a77149b..11cfcb22 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -9,7 +9,6 @@ import { Table, Icon, Loader, - List, } from 'semantic-ui-react'; const SearchList = ({ -- cgit v1.2.3 From a8f5f652eec420922f01d3009d354d43d72fd994 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 10:27:12 -0500 Subject: fix header button alignment on search detail --- .../src/components/Search/Detail/SearchDetailHeader.js | 6 +++--- src/web/src/components/Search/Search.css | 17 ++++++++++++----- 2 files changed, 15 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js index ac613249..2071540f 100644 --- a/src/web/src/components/Search/Detail/SearchDetailHeader.js +++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js @@ -63,11 +63,11 @@ const SearchDetailHeader = ({ // if the screen is less than 684 pixels, display the action buttons in a new segment, with full text. return ( <> - -
+ +
{searchText}
- {!isTinyScreen &&
+ {!isTinyScreen &&
} diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index f66a3bc7..ca31d308 100644 --- a/src/web/src/components/Search/Search.css +++ b/src/web/src/components/Search/Search.css @@ -105,12 +105,19 @@ width: 5px !important; } -.search-detail-header { +.search-detail-header-segment { + margin-top: 15px !important; + height: 78px !important; + padding-top: 20px !important; + display: flex; +} + +.search-detail-header-segment > .header { font-weight: normal !important; - margin-top: 12px !important; + margin-top: 8px !important; } -.search-detail-action-button { - float: right; - margin-top: -48px !important; +.search-detail-header-buttons { + display: inline; + margin-left: auto; } \ No newline at end of file -- cgit v1.2.3