Skip to content

Commit

Permalink
Merge branch 'v3' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
ellman12 committed Feb 2, 2024
2 parents 56b53bf + d89f11c commit ecb5b40
Show file tree
Hide file tree
Showing 200 changed files with 8,032 additions and 7,762 deletions.
10 changes: 5 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -520,8 +520,8 @@ $RECYCLE.BIN/

_NCrunch*

PSS/PSS/pss_settings.json
PSS/PSS/wwwroot/pss_backup
PSS/PSS/wwwroot/pss_library
PSS/PSS/wwwroot/pss_tmp
PSS/PSS/wwwroot/pss_upload
# MemoryMosaic-specific ignores.
MemoryMosaic/mm_settings.json
MemoryMosaic/mm_debug_settings.json

MemoryMosaic/wwwroot/css/
23 changes: 23 additions & 0 deletions Initialization/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Initialization;

public static class Constants
{
public const string PostgresVersion = "15";

private const string PostgresBinPath = $"C:/Program Files/PostgreSQL/{PostgresVersion}/bin";

public const string PsqlPath = $"{PostgresBinPath}/psql.exe";

public static readonly string CreateTablesFilePath;

static Constants()
{
#if DEBUG
int index = Environment.CurrentDirectory.LastIndexOf("bin", StringComparison.Ordinal);
string initializationRoot = Environment.CurrentDirectory.Substring(0, index).Replace('\\', '/');
CreateTablesFilePath = Path.Combine(initializationRoot, "Create Tables.sql");
#else
CreateTablesFilePath = "Create Tables.sql";
#endif
}
}
39 changes: 39 additions & 0 deletions Initialization/Create Tables.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
-- Run this file to initialize database for first time use.
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- https://stackoverflow.com/a/12505220

CREATE TABLE IF NOT EXISTS public.library
(
path text UNIQUE NOT NULL, -- A short path, inside the library folder, which could be this format: Unknown/filename.ext, or 2023/10/filename.ext
id uuid UNIQUE NOT NULL DEFAULT uuid_generate_v1(),
date_taken timestamp without time zone,
date_added timestamp without time zone NOT NULL DEFAULT now(),
separate boolean NOT NULL DEFAULT false, -- Is this item in a folder?
starred boolean NOT NULL DEFAULT false,
description text DEFAULT NULL,
date_deleted timestamp without time zone DEFAULT NULL, -- If this has a value, it's in the Trash.
thumbnail text NOT NULL, -- Compressed base64 string representing thumbnail.
PRIMARY KEY (path, id)
) TABLESPACE pg_default;
ALTER TABLE public.library OWNER to postgres;

CREATE TABLE IF NOT EXISTS public.collections
(
id serial UNIQUE NOT NULL,
name text UNIQUE NOT NULL,
cover text REFERENCES library(path) ON UPDATE CASCADE ON DELETE SET NULL DEFAULT NULL,
description text DEFAULT NULL,
folder boolean NOT NULL DEFAULT false, -- If this is a folder and thus its contents should remain separate from rest of library.
readonly boolean NOT NULL DEFAULT false, -- If this Collection has been marked as readonly, it cannot: be renamed, have items added/removed, change if it's a folder or not, appear in CollectionSelector, or be deleted.
last_modified timestamp without time zone NOT NULL DEFAULT now(), -- The last time this item was renamed, added to/removed from, etc.
PRIMARY KEY (id, name)
) TABLESPACE pg_default;
ALTER TABLE public.collections OWNER to postgres;

CREATE TABLE IF NOT EXISTS public.collection_entries
(
collection_id integer NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
item_id uuid NOT NULL REFERENCES library(id) ON DELETE CASCADE,
date_added_to_collection timestamp without time zone NOT NULL DEFAULT now(),
PRIMARY KEY (collection_id, item_id)
) TABLESPACE pg_default;
ALTER TABLE public.collection_entries OWNER to postgres;
66 changes: 66 additions & 0 deletions Initialization/Database.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System.Data;
using System.Diagnostics;
using Npgsql;

namespace Initialization;

public static class Database
{
private static NpgsqlConnection Connection { get; } = new("Host=localhost; Port=5432; Username=postgres; Password=Ph0t0s_Server; Database=postgres");

private static void Connect()
{
if (Connection.State != ConnectionState.Open)
Connection.Open();
}

private static void Close()
{
if (Connection.State != ConnectionState.Closed)
Connection.Close();
}

public static void Create(string name)
{
Connect();
using NpgsqlCommand cmd = new($"CREATE DATABASE \"{name}\" WITH OWNER = postgres ENCODING = 'UTF8' CONNECTION LIMIT = -1", Connection);
cmd.ExecuteNonQuery();
Close();
}

public static void CreateTables(string name)
{
ProcessStartInfo cmd = new()
{
FileName = Constants.PsqlPath,
Arguments = $"-U postgres -d {name} -f \"{Constants.CreateTablesFilePath}\"",
RedirectStandardOutput = true
};

Process p;
do
{
p = Process.Start(cmd) ?? throw new NullReferenceException();
p.WaitForExit();
} while (p.ExitCode != 0);
}

public static void Delete(string name)
{
Connect();
using NpgsqlCommand cmd = new($"DROP DATABASE \"{name}\"", Connection);
cmd.ExecuteNonQuery();
Close();
}

///Returns true if the database with this name exists, false otherwise.
public static bool Exists(string name)
{
Connect();
using NpgsqlCommand cmd = new($"SELECT datname FROM pg_database WHERE datname = '{name}'", Connection);
using var reader = cmd.ExecuteReader();
if (reader.HasRows && reader.Read())
return reader.GetString(0) == name;
return false;
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<RootNamespace>PSS_Init</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\PSS\PSS.csproj" />
<Content Include="Create Tables.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>

<ItemGroup>
<PackageReference Include="Npgsql" Version="6.0.2"/>
</ItemGroup>
</Project>
40 changes: 40 additions & 0 deletions Initialization/Input.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
namespace Initialization;

public static class Input
{
///Writes a message to the console, and prompts for a y/n input.
public static bool GetYN(string prompt, bool defaultValue)
{
prompt = $"{prompt} [{(defaultValue ? 'Y' : 'y')}/{(defaultValue ? 'n' : 'N')}] ";

Console.Write(prompt);

ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();

return key.Key switch
{
ConsoleKey.Enter => defaultValue,
ConsoleKey.Y => true,
ConsoleKey.N => false,
_ => defaultValue
};
}

///Prompts for input until a proper folder path is entered.
public static string GetFolderPath(string prompt) => GetCheck(input => !String.IsNullOrWhiteSpace(input) && Path.IsPathFullyQualified(input) && Path.IsPathRooted(input) && !Path.HasExtension(input), prompt);

///Prompts for input until check returns true.
private static string GetCheck(Predicate<string> check, string prompt)
{
string input;
Console.Write(prompt);
while (true)
{
input = Console.ReadLine()!;
if (check(input)) break;
Output.WriteLine("Invalid format. Please try again.", ConsoleColor.Red);
}
return input;
}
}
12 changes: 12 additions & 0 deletions Initialization/Output.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Initialization;

public static class Output
{
///Writes a colored message to the console.
public static void WriteLine(string message, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ResetColor();
}
}
69 changes: 69 additions & 0 deletions Initialization/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using Initialization;
using Microsoft.VisualBasic.FileIO;

if (!File.Exists(Constants.PsqlPath))
{
Output.WriteLine($"PostgreSQL {Constants.PostgresVersion} not installed! Download it here: https://www.postgresql.org/download/", ConsoleColor.Red);
return;
}

bool debug = Input.GetYN("Is this a debugging and testing instance of MemoryMosaic?", false);
string name = debug ? "MemoryMosaic_Debug" : "MemoryMosaic";

if (Database.Exists(name) && Input.GetYN("Database exists. Overwrite?", true) && Input.GetYN("Are you sure?", true))
{
Output.WriteLine($"Deleting {name}", ConsoleColor.Cyan);
Database.Delete(name);
}

if (!Database.Exists(name))
{
Output.WriteLine($"Creating {name} database", ConsoleColor.Cyan);
Database.Create(name);
Output.WriteLine("Creating tables", ConsoleColor.Cyan);
Database.CreateTables(name);
}

string testLibPath = Input.GetFolderPath("Enter path for mm_library, where the library should be stored: ");
VerifyPathAndCreateFolder(ref testLibPath, "mm_library");

string testImportPath = Input.GetFolderPath("Enter path for mm_import, where items waiting to be imported should be stored: ");
VerifyPathAndCreateFolder(ref testImportPath, "mm_import");

string testTmpPath = Input.GetFolderPath("Enter path to mm_tmp, where temporary files should be stored: ");
VerifyPathAndCreateFolder(ref testTmpPath, "mm_tmp");

string testBackupPath = Input.GetFolderPath("Enter path to mm_backup, where backups should be stored: ");
VerifyPathAndCreateFolder(ref testBackupPath, "mm_backup");

string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), $"MemoryMosaic{(debug ? "_Debug" : "")}");
string filePath = Path.Combine(folderPath, $"mm_settings{(debug ? "_debug" : "")}.json");

string settingsJson = $"{{\"importFolderPath\":\"{testImportPath}\",\"libFolderPath\":\"{testLibPath}\",\"backupFolderPath\":\"{testBackupPath}\",\"tmpFolderPath\":\"{testTmpPath}\",\"showPrompts\":true,\"thumbnailQuality\":7,\"logLevel\":4}}";
Directory.CreateDirectory(folderPath);
File.WriteAllText(filePath, settingsJson);

Output.WriteLine("MemoryMosaic is now ready to use.", ConsoleColor.Green);

#if !DEBUG
Console.ReadLine();
#endif

return;

void VerifyPathAndCreateFolder(ref string path, string mmFolder)
{
path = path.Trim();
if (path.Last() is '/' or '\\')
path = path.Substring(0, path.Length - 1);

if (!path.EndsWith(mmFolder))
{
path = Path.Join(path, mmFolder);
path = path.Replace('\\', '/');
}

if (Directory.Exists(path) && Input.GetYN($"{path} exists and has {Directory.EnumerateFiles(path).Count()} files. Overwrite?", true) && Input.GetYN("Are you sure?", true))
FileSystem.DeleteDirectory(path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
Directory.CreateDirectory(path);
}
12 changes: 6 additions & 6 deletions PSS/PSS.sln → MemoryMosaic.sln
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31515.178
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PSS", "PSS/PSS.csproj", "{622F7209-CF20-4A79-BEF1-2E2183D9F398}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MemoryMosaic", "MemoryMosaic\MemoryMosaic.csproj", "{622F7209-CF20-4A79-BEF1-2E2183D9F398}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PSS-Init", "PSS-Init\PSS-Init.csproj", "{5E38150A-38EC-4490-A478-CBDFAB732424}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Initialization", "Initialization\Initialization.csproj", "{78176CF0-6021-4DD4-B250-36B44166CCC6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -17,10 +17,10 @@ Global
{622F7209-CF20-4A79-BEF1-2E2183D9F398}.Debug|Any CPU.Build.0 = Debug|Any CPU
{622F7209-CF20-4A79-BEF1-2E2183D9F398}.Release|Any CPU.ActiveCfg = Release|Any CPU
{622F7209-CF20-4A79-BEF1-2E2183D9F398}.Release|Any CPU.Build.0 = Release|Any CPU
{5E38150A-38EC-4490-A478-CBDFAB732424}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5E38150A-38EC-4490-A478-CBDFAB732424}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5E38150A-38EC-4490-A478-CBDFAB732424}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5E38150A-38EC-4490-A478-CBDFAB732424}.Release|Any CPU.Build.0 = Release|Any CPU
{78176CF0-6021-4DD4-B250-36B44166CCC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{78176CF0-6021-4DD4-B250-36B44166CCC6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{78176CF0-6021-4DD4-B250-36B44166CCC6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{78176CF0-6021-4DD4-B250-36B44166CCC6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
6 changes: 3 additions & 3 deletions PSS/PSS/App.razor → MemoryMosaic/App.razor
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<title>404 - PSS</title>
<title>404 - MemoryMosaic</title>
<Error/>
</LayoutView>
</NotFound>
</Router>
</Router>
Loading

0 comments on commit ecb5b40

Please sign in to comment.