aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Shares/SharedFileCache.cs
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-09-20 20:13:05 -0500
committerGitHub <noreply@github.com>2022-09-20 20:13:05 -0500
commitc4544a6a14577a79d02d009f38557cbcf9ec80ad (patch)
tree69ae056823d2d5d050e2c80ff45b1ffa2126c1b4 /src/slskd/Shares/SharedFileCache.cs
parent2a1a7aca5f7a6fa70652135f7a7034bef55dfed4 (diff)
parent6a307269ab99956fb2c5ea2149ae76c3ef24c8b2 (diff)
downloadslskd-c4544a6a14577a79d02d009f38557cbcf9ec80ad.tar.gz
Merge branch 'master' into aux/docs-proofreading
Diffstat (limited to 'src/slskd/Shares/SharedFileCache.cs')
-rw-r--r--src/slskd/Shares/SharedFileCache.cs595
1 files changed, 399 insertions, 196 deletions
diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs
index 6e38ee31..4afbfed8 100644
--- a/src/slskd/Shares/SharedFileCache.cs
+++ b/src/slskd/Shares/SharedFileCache.cs
@@ -22,10 +22,12 @@ namespace slskd.Shares
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+ using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
+ using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using Serilog;
@@ -34,62 +36,18 @@ namespace slskd.Shares
/// <summary>
/// Shared file cache.
/// </summary>
- public interface ISharedFileCache
- {
- /// <summary>
- /// Gets the cache state monitor.
- /// </summary>
- IStateMonitor<SharedFileCacheState> StateMonitor { get; }
-
- /// <summary>
- /// Returns the contents of the cache.
- /// </summary>
- /// <returns>The contents of the cache.</returns>
- IEnumerable<Directory> Browse();
-
- /// <summary>
- /// Scans the configured shares and fills the cache.
- /// </summary>
- /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks>
- /// <param name="shares">The list of shares from which to fill the cache.</param>
- /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param>
- /// <returns>The operation context.</returns>
- Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters);
-
- /// <summary>
- /// Returns the contents of the specified <paramref name="directory"/>.
- /// </summary>
- /// <param name="directory">The directory for which the contents are to be listed.</param>
- /// <returns>The contents of the directory.</returns>
- Directory List(string directory);
-
- /// <summary>
- /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked
- /// by the cache.
- /// </summary>
- /// <param name="filename">The fully qualified filename to unmask.</param>
- /// <returns>The unmasked filename.</returns>
- public string Resolve(string filename);
-
- /// <summary>
- /// Searches the cache for the specified <paramref name="query"/> and returns the matching files.
- /// </summary>
- /// <param name="query">The query for which to search.</param>
- /// <returns>The matching files.</returns>
- Task<IEnumerable<File>> SearchAsync(SearchQuery query);
- }
-
- /// <summary>
- /// Shared file cache.
- /// </summary>
public class SharedFileCache : ISharedFileCache
{
/// <summary>
/// Initializes a new instance of the <see cref="SharedFileCache"/> class.
/// </summary>
+ /// <param name="storageMode"></param>
+ /// <param name="workerCount"></param>
/// <param name="soulseekFileFactory"></param>
- public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null)
+ public SharedFileCache(StorageMode storageMode, int workerCount, ISoulseekFileFactory soulseekFileFactory = null)
{
+ StorageMode = storageMode;
+ WorkerCount = workerCount;
SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory();
}
@@ -98,14 +56,14 @@ namespace slskd.Shares
/// </summary>
public IStateMonitor<SharedFileCacheState> StateMonitor => State;
+ private StorageMode StorageMode { get; }
+ private int WorkerCount { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>();
- private HashSet<string> MaskedDirectories { get; set; }
- private Dictionary<string, File> MaskedFiles { get; set; }
private List<Share> Shares { get; set; }
private ISoulseekFileFactory SoulseekFileFactory { get; }
- private SqliteConnection SQLite { get; set; }
private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
+ private Channel<string> DirectoryChannel { get; set; }
/// <summary>
/// Returns the contents of the cache.
@@ -130,23 +88,43 @@ namespace slskd.Shares
// 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)
+ foreach (var directory in ListDirectories())
{
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 files = new List<File>();
+
+ using var conn = GetConnection();
+ using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn);
+ var reader = cmd.ExecuteReader();
+
+ while (reader.Read())
+ {
+ var filename = reader.GetString(0);
+ var code = reader.GetInt32(1);
+ var size = reader.GetInt64(2);
+ var extension = reader.GetString(3);
+ var attributeJson = reader.GetString(4);
+
+ var attributeList = attributeJson.FromJson<List<FileAttribute>>();
+
+ var file = new File(code, filename, size, extension, attributeList);
+
+ files.Add(file);
+ }
+
+ var groups = files
+ .GroupBy(file => Path.GetDirectoryName(file.Filename))
+ .Select(group => new Directory(group.Key, group.Select(f =>
{
- 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);
- })));
+ }).OrderBy(f => f.Filename)));
// merge the dictionary containing all directories with the Soulseek.Directory instances containing their files.
// entries with no files will remain untouched.
@@ -155,7 +133,7 @@ namespace slskd.Shares
directories.AddOrUpdate(group.Name, group, (_, _) => group);
}
- return directories.Values.OrderBy(f => f.Name);
+ return directories.Values.OrderBy(d => d.Name);
}
/// <summary>
@@ -164,7 +142,7 @@ namespace slskd.Shares
/// <param name="shares">The list of shares from which to fill the cache.</param>
/// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param>
/// <returns>The operation context.</returns>
- public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters)
+ public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters, CancellationToken cancellationToken = default)
{
// obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running.
if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0))
@@ -175,19 +153,24 @@ namespace slskd.Shares
try
{
+ // drop and recreate the tables to clear them
+ // note: leave the backup in place. this will leave the app in a better position if the app stops during the scan.
+ CreateTables();
+
State.SetValue(state => state with
{
Filling = true,
Filled = false,
FillProgress = 0,
+ Directories = 0,
+ Files = 0,
+ ExcludedDirectories = 0,
});
Log.Debug("Starting shared file scan");
await Task.Yield();
- ResetCache();
-
var sw = new Stopwatch();
var swSnapshot = 0L;
sw.Start();
@@ -210,9 +193,9 @@ namespace slskd.Shares
Log.Debug("Enumerating shared directories");
swSnapshot = sw.ElapsedMilliseconds;
- // derive a list of all directories from all shares
- // skip hidden and system directories, as well as anything that can't be accessed due to security restrictions.
- // it's necessary to enumerate these directories up front so we can deduplicate directories and apply exclusions
+ // derive a list of all directories from all shares skip hidden and system directories, as well as anything that
+ // can't be accessed due to security restrictions. it's necessary to enumerate these directories up front so we
+ // can deduplicate directories and apply exclusions
var unmaskedDirectories = Shares
.SelectMany(share =>
{
@@ -244,92 +227,120 @@ 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 files = new Dictionary<string, File>();
var maskedDirectories = new HashSet<string>();
- var current = 0L;
- var filtered = 0L;
+ var current = 0;
+ var cached = 0;
+ var filtered = 0;
- foreach (var directory in unmaskedDirectories)
+ // set up a channel to fan out for directory scanning
+ DirectoryChannel = Channel.CreateBounded<string>(new BoundedChannelOptions(1000)
{
- Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count);
+ AllowSynchronousContinuations = false,
+ FullMode = BoundedChannelFullMode.Wait,
+ SingleReader = false,
+ SingleWriter = true,
+ });
- var addedFiles = 0L;
- var filteredFiles = 0L;
+ // create workers to perform the fan out
+ var workers = new List<ChannelReader<string>>();
- var share = Shares.First(share => directory.StartsWith(share.LocalPath));
+ foreach (var id in Enumerable.Range(0, WorkerCount))
+ {
+ workers.Add(new ChannelReader<string>(
+ channel: DirectoryChannel,
+ cancellationToken: cancellationToken,
+ handler: (directory) =>
+ {
+ Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count);
- maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath));
+ var addedFiles = 0;
+ var filteredFiles = 0;
- // 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
- {
- // enumerate files in this directory only (no subdirectories)
- // exclude hidden and system files and anything that can't be accessed due to security restrictions
- var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions()
- {
- AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
- IgnoreInaccessible = true,
- RecurseSubdirectories = false,
- })
- .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath)))
- .ToDictionary(file => file.Filename, file => file);
-
- addedFiles = newFiles.Count;
-
- // 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)))
+ var share = Shares.First(share => directory.StartsWith(share.LocalPath));
+
+ maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath));
+ InsertDirectory(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
{
- filteredFiles++;
- continue;
+ // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything
+ // that can't be accessed due to security restrictions
+ var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions()
+ {
+ AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
+ IgnoreInaccessible = true,
+ RecurseSubdirectories = false,
+ });
+
+ addedFiles = newFiles.Length;
+
+ // 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 originalFilename in newFiles)
+ {
+ var info = new FileInfo(originalFilename);
+ var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath));
+
+ if (filters.Any(filter => filter.IsMatch(originalFilename)))
+ {
+ filteredFiles++;
+ continue;
+ }
+
+ InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file);
+ }
}
-
- if (files.ContainsKey(file.Key))
+ catch (Exception ex)
{
- 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?).");
+ 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);
}
- 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++;
- filtered += filteredFiles;
+ current++;
+ filtered += filteredFiles;
+ cached += addedFiles;
- Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles);
+ Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles);
- try
- {
- State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count });
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message);
- throw;
- }
+ try
+ {
+ State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached });
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message);
+ throw;
+ }
+ }));
}
- 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;
+ Log.Debug("Starting workers...");
+ workers.ForEach(w => w.Start());
+ Log.Debug("All workers started");
- // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite
- foreach (var file in files)
+ Log.Debug("Filling DirectoryChannel...");
+ foreach (var directory in unmaskedDirectories)
{
- InsertFilename(file.Key);
+ await DirectoryChannel.Writer.WriteAsync(directory);
}
- Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot);
+ DirectoryChannel.Writer.Complete();
+ Log.Debug("DirectoryChannel filled");
+
+ Log.Debug("Waiting for workers to finish working...");
+ await Task.WhenAll(workers.Select(w => w.Completed));
+ Log.Debug("All workers finished");
- MaskedDirectories = maskedDirectories;
- MaskedFiles = files;
+ Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot);
+ swSnapshot = sw.ElapsedMilliseconds;
+
+ Log.Debug("Inserted {Files} records in {Elapsed}ms", cached, sw.ElapsedMilliseconds - swSnapshot);
+
+ Log.Debug("Backing up shared file cache database...");
+ Backup();
+ Log.Debug("Shared file cache database backup complete");
State.SetValue(state => state with
{
@@ -337,11 +348,11 @@ namespace slskd.Shares
Faulted = false,
Filled = true,
FillProgress = 1,
- Directories = MaskedDirectories.Count,
- Files = MaskedFiles.Count,
+ Directories = CountDirectories(),
+ Files = CountFiles(),
});
- Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}");
+ Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {cached}");
}
catch (Exception ex)
{
@@ -372,17 +383,7 @@ namespace slskd.Shares
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);
- });
-
+ var files = ListFiles(directory);
return new Directory(directory, files);
}
@@ -394,37 +395,19 @@ namespace slskd.Shares
/// <returns>The unmasked filename.</returns>
public string Resolve(string filename)
{
- filename = filename.ToLocalOSPath();
+ using var conn = GetConnection();
+ using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn);
+ cmd.Parameters.AddWithValue("maskedFilename", filename);
- // ensure this is a tracked file
- if (!MaskedFiles.TryGetValue(filename, out _))
- {
- return null;
- }
-
- 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[] { '/', '\\' });
+ var reader = cmd.ExecuteReader();
- if (parts.Length < 2)
+ if (!reader.Read())
{
- Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed");
+ Log.Warning("Failed to resolve shared file {Filename}", filename);
return null;
}
- // find the share with a matching mask and alias/local directory
- var share = Shares.FirstOrDefault(share => share.Alias == parts[0]);
-
- if (share == default)
- {
- Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from alias '{Alias}'", filename, parts[0]);
- return null;
- }
-
- resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath);
-
+ var resolved = reader.GetString(0);
Log.Debug($"Resolved requested shared file {filename} to {resolved}");
return resolved;
}
@@ -434,7 +417,7 @@ namespace slskd.Shares
/// </summary>
/// <param name="query">The query for which to search.</param>
/// <returns>The matching files.</returns>
- public async Task<IEnumerable<File>> SearchAsync(SearchQuery query)
+ public IEnumerable<File> Search(SearchQuery query)
{
if (!State.CurrentValue.Filled)
{
@@ -450,66 +433,286 @@ namespace slskd.Shares
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<string>();
+ var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " +
+ "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " +
+ $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " +
+ "ORDER BY filenames.maskedFilename ASC;";
+
+ var results = new List<File>();
+ SqliteDataReader reader = default;
try
{
- using var conn = new SqliteConnection($"Data Source={Path.Combine(Program.AppDirectory, "data", "shares.db")};cache=shared");
+ using var conn = GetConnection();
using var cmd = new SqliteCommand(sql, conn);
- await conn.OpenAsync();
-
- var reader = await cmd.ExecuteReaderAsync();
+ reader = cmd.ExecuteReader();
while (reader.Read())
{
- results.Add(reader.GetString(0));
+ var filename = reader.GetString(0);
+ var code = reader.GetInt32(1);
+ var size = reader.GetInt64(2);
+ var extension = reader.GetString(3);
+ var attributeJson = reader.GetString(4);
+
+ var attributeList = attributeJson.FromJson<List<FileAttribute>>();
+
+ var file = new File(code, filename, size, extension, attributeList);
+ results.Add(file);
}
+
+ return results;
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message);
return Enumerable.Empty<File>();
}
+ }
+ /// <summary>
+ /// Attempts to load the cache from disk.
+ /// </summary>
+ /// <returns>A value indicating whether the load was successful.</returns>
+ public bool TryLoad()
+ {
try
{
- return results.Select(r => MaskedFiles[r]).ToList();
+ // see if we need to 'restore' the database from disk, and do so
+ if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !ValidateTables(Program.ConnectionStrings.Shares)))
+ {
+ Log.Debug($"Share cache {(StorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup...");
+
+ // the backup is missing; we can't do anything but recreate it from scratch
+ if (!ValidateTables(Program.ConnectionStrings.SharesBackup))
+ {
+ Log.Debug("Share cache backup is missing; unable to restore");
+ return false;
+ }
+
+ Log.Debug("Share cache backup located. Attempting to restore...");
+
+ using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup);
+ using var conn = GetConnection();
+ backupConn.BackupDatabase(conn);
+
+ Log.Debug("Share cache successfully restored from backup");
+ }
+
+ // one of several thigns happened above before we got here:
+ // the storage mode is memory, and we loaded the in-memory db from a valid backup
+ // the storage mode is disk, and the file is there and valid
+ // the storage mode is disk but either missing or invalid, and we restored from a valid backup
+ // at this point there is a valid (existing, schema matching expected schema) database at the primary connection string
+ State.SetValue(state => state with
+ {
+ Filling = false,
+ Faulted = false,
+ Filled = true,
+ FillProgress = 1,
+ Directories = CountDirectories(),
+ Files = CountFiles(),
+ });
+
+ return true;
}
catch (Exception ex)
{
- Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message);
- return Enumerable.Empty<File>();
+ Log.Debug(ex, "Error loading shared file cache: {Message}", ex.Message);
+ return false;
}
}
- private void CreateTable()
+ private bool ValidateTables(string connectionString)
{
- if (SQLite != null)
+ var schema = new Dictionary<string, string>()
{
- SQLite.Dispose();
+ { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY)" },
+ { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" },
+ { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL)" },
+ };
+
+ try
+ {
+ Log.Debug("Validating shares database with connection string {String}", connectionString);
+
+ using var conn = GetConnection(connectionString);
+ using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table' AND name IN ('directories', 'filenames', 'files');", conn);
+
+ var reader = cmd.ExecuteReader();
+ var rows = 0;
+
+ while (reader.Read())
+ {
+ var table = reader.GetString(0);
+ var expectedSql = reader.GetString(1);
+
+ if (schema.TryGetValue(table, out var actualSql))
+ {
+ if (actualSql != expectedSql)
+ {
+ throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}");
+ }
+ else
+ {
+ Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql);
+ }
+ }
+
+ rows++;
+ }
+
+ if (rows != schema.Count)
+ {
+ throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}");
+ }
+
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}");
+ return false;
}
+ }
+
+ private void Backup()
+ {
+ using var sourceConn = GetConnection();
+ using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup);
+ sourceConn.BackupDatabase(backupConn);
+ }
+
+ private int CountDirectories()
+ {
+ using var conn = GetConnection();
+ using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn);
+ var reader = cmd.ExecuteReader();
+ reader.Read();
+ return reader.GetInt32(0);
+ }
+
+ private int CountFiles()
+ {
+ using var conn = GetConnection();
+ using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn);
+ var reader = cmd.ExecuteReader();
+ reader.Read();
+ return reader.GetInt32(0);
+ }
+
+ private void CreateTables()
+ {
+ using var conn = GetConnection();
- SQLite = new SqliteConnection($"Data Source={Path.Combine(Program.AppDirectory, "data", "shares.db")};cache=shared");
- SQLite.Open();
+ conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);");
+
+ conn.ExecuteNonQuery("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);");
+
+ conn.ExecuteNonQuery("DROP TABLE IF EXISTS files; CREATE TABLE files " +
+ "(maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, " +
+ "extension TEXT, attributeJson TEXT NOT NULL);");
+ }
- using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite);
- cmd.ExecuteNonQuery();
+ private SqliteConnection GetConnection(string connectionString = null)
+ {
+ var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares);
+ conn.Open();
+ return conn;
+ }
+
+ private void InsertDirectory(string name)
+ {
+ using var conn = GetConnection();
+
+ conn.ExecuteNonQuery("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", cmd =>
+ {
+ cmd.Parameters.AddWithValue("name", name);
+ });
}
- private void InsertFilename(string filename)
+ private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file)
{
- using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite);
- cmd.Parameters.AddWithValue("filename", filename);
- cmd.ExecuteNonQuery();
+ using var conn = GetConnection();
+
+ conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " +
+ "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson) " +
+ "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson;", cmd =>
+ {
+ cmd.Parameters.AddWithValue("maskedFilename", maskedFilename);
+ cmd.Parameters.AddWithValue("originalFilename", originalFilename);
+ cmd.Parameters.AddWithValue("size", file.Size);
+ cmd.Parameters.AddWithValue("touchedAt", touchedAt.ToLongDateString());
+ cmd.Parameters.AddWithValue("code", file.Code);
+ cmd.Parameters.AddWithValue("extension", file.Extension);
+ cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson());
+ });
+
+ conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd =>
+ {
+ cmd.Parameters.AddWithValue("maskedFilename", maskedFilename);
+ });
}
- private void ResetCache()
+ private IEnumerable<string> ListDirectories()
{
- CreateTable();
- MaskedDirectories = new HashSet<string>();
- MaskedFiles = new Dictionary<string, File>();
- State.SetValue(state => state with { Directories = 0, Files = 0 });
+ var results = new List<string>();
+
+ using var conn = GetConnection();
+
+ using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn);
+ var reader = cmd.ExecuteReader();
+
+ while (reader.Read())
+ {
+ results.Add(reader.GetString(0));
+ }
+
+ return results;
+ }
+
+ private IEnumerable<File> ListFiles(string directory = null)
+ {
+ var results = new List<File>();
+
+ SqliteCommand cmd = default;
+ using var conn = GetConnection();
+
+ try
+ {
+ if (string.IsNullOrEmpty(directory))
+ {
+ cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn);
+ }
+ else
+ {
+ cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn);
+ cmd.Parameters.AddWithValue("match", directory + '%');
+ }
+
+ var reader = cmd.ExecuteReader();
+
+ while (reader.Read())
+ {
+ var filename = reader.GetString(0);
+ var code = reader.GetInt32(1);
+ var size = reader.GetInt64(2);
+ var extension = reader.GetString(3);
+ var attributeJson = reader.GetString(4);
+
+ var attributeList = attributeJson.FromJson<List<FileAttribute>>();
+
+ var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList);
+
+ results.Add(file);
+ }
+
+ return results;
+ }
+ finally
+ {
+ cmd?.Dispose();
+ }
}
}
} \ No newline at end of file