Remove Ballmer

ご主人様
not manx 5 years ago
parent 5c2c2a627d
commit a9e861eefd
Signed by: C-xC-c
GPG Key ID: F52ED472284EF2F4

63
.gitattributes vendored

@ -1,63 +0,0 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

342
.gitignore vendored

@ -1,343 +1 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
appsettings.json
src/config.lisp src/config.lisp
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
/BantFlags/wwwroot/flags/*.png
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- Backup*.rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29411.108
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BantFlags", "BantFlags\BantFlags.csproj", "{DDDE290B-44A9-485A-B0F4-E7D696EAFF8D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DDDE290B-44A9-485A-B0F4-E7D696EAFF8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DDDE290B-44A9-485A-B0F4-E7D696EAFF8D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDDE290B-44A9-485A-B0F4-E7D696EAFF8D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDDE290B-44A9-485A-B0F4-E7D696EAFF8D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {252385AC-0BBA-43F2-858A-BA3877F33106}
EndGlobalSection
EndGlobal

@ -1,12 +0,0 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "3.1.0",
"commands": [
"dotnet-ef"
]
}
}
}

@ -1,24 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Copyright>Manx</Copyright>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="7.14.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Razor" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.0" />
<PackageReference Include="MySql.Data" Version="8.0.18" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Nito.AsyncEx" Version="5.0.0" />
</ItemGroup>
</Project>

@ -1,84 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using BantFlags.Data;
using BantFlags.Data.Database;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace BantFlags.Controllers
{
[ApiController]
[Route("api")]
public class FlagsController : Controller
{
private DatabaseService Database { get; }
public FlagsController(DatabaseService db)
{
Database = db;
}
/// <summary>
/// Retrives flags from the database from the posts sent in post_nrs
/// </summary>
/// <param name="post_nrs">The comma seperated list of post numbers from the thread.</param>
/// <param name="board">Currently should only be /bant/. Not checked here because we don't need to care what they send.</param>
/// <param name="version">The version of the userscript.</param>
[HttpPost]
[Route("get")]
[Consumes("application/x-www-form-urlencoded")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Get([FromForm]string post_nrs, [FromForm]string board, [FromForm]int? version)
{
int ver = version ?? 0;
if (ver > 1)
{
// Improved data structuring, see Docs/get
return Json(await Database.GetPosts_V2(post_nrs, board));
}
return Json(await Database.GetPosts_V1(post_nrs, board));
}
/// <summary>
/// Posts flags in the database.
/// </summary>
/// <param name="post_nr">The post number to associate the flags to.</param>
/// <param name="board">Currently should only be /bant/.</param>
/// <param name="regions">List of flags to associate with the post. Split by "||" in API V1 and "," in V2.</param>
/// <param name="version">The version of the userscript.</param>
[HttpPost]
[Route("post")]
[Consumes("application/x-www-form-urlencoded")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Post([FromForm]string post_nr, [FromForm]string board, [FromForm]string regions, [FromForm]int? version)
{
string splitFlag = (version ?? 0) > 1 ? "," : "||"; // comma for v2+, else || for backwards compatibility.
(PostModel flag, string error) = PostModel.Create(post_nr, board, regions, splitFlag, Database.KnownFlags, Database.Boards);
if (flag is null)
{
return Problem(error, statusCode: StatusCodes.Status400BadRequest);
}
await Database.InsertPost(flag);
return Ok(flag);
}
/// <summary>
/// Gets the list of supported flags.
/// </summary>
[HttpGet]
[Route("flags")]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult Flags() => Ok(Database.FlagList);
}
}

@ -1,115 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace BantFlags.Data.Database
{
/// <summary>
/// Functions for interacting with the database.
/// </summary>
public partial class DatabaseService
{
private MySqlConnectionPool ConnectionPool { get; }
public string FlagList { get; private set; }
public HashSet<string> KnownFlags { get; private set; }
public HashSet<string> Boards { get; private set; }
public DatabaseService(DatabaseServiceConfig dbConfig)
{
ConnectionPool = new MySqlConnectionPool(dbConfig.ConnectionString, dbConfig.PoolSize);
Boards = dbConfig.Boards;
UpdateKnownFlags().Wait(); // It's okay to deadlock here since it's only initialised at startup.
}
public async Task UpdateKnownFlags()
{
var flags = await GetFlags();
flags.Remove("empty, or there were errors. Re-set your flags."); // So users can't select this.
FlagList = string.Join("\n", flags);
KnownFlags = flags.ToHashSet();
}
public async Task InsertPost(PostModel post)
{
using (var rentedConnection = await ConnectionPool.RentConnectionAsync())
{
await rentedConnection.Object.UseStoredProcedure("insert_post")
.SetParam("@post_nr", post.PostNumber)
.SetParam("@board", post.Board)
.ExecuteNonQueryAsync();
using (var query = rentedConnection.Object.UseStoredProcedure("insert_post_flags"))
{
query.SetParam("@post_nr", post.PostNumber);
post.Flags.ForEach(async f =>
await query.SetParam("@flag", f)
.ExecuteNonQueryAsync(reuse: true));
}
}
}
/// <summary>
/// Returns all of the flags that we support.
/// </summary>
public async Task<List<string>> GetFlags()
{
using var rentedConnected = await ConnectionPool.RentConnectionAsync();
DataTable table = await rentedConnected.Object.CreateQuery("SELECT flags.flag FROM flags")
.ExecuteTableAsync();
return table.AsEnumerable()
.Select(x => x.GetValue<string>("flag"))
.ToList();
}
public async Task InsertFlagAsync(Flag flag)
{
using var rentedConnection = await ConnectionPool.RentConnectionAsync();
await rentedConnection.Object.UseStoredProcedure("insert_flag")
.SetParam("@flag", flag.Name)
.ExecuteNonQueryAsync();
}
public async Task RenameFlagAsync(Flag flag)
{
using var rentedConnection = await ConnectionPool.RentConnectionAsync();
await rentedConnection.Object.UseStoredProcedure("rename_flag")
.SetParam("@old", flag.OldName)
.SetParam("@new", flag.Name)
.ExecuteNonQueryAsync();
}
public async Task DeleteFlagAsync(Flag flag)
{
using var rentedConnection = await ConnectionPool.RentConnectionAsync();
await rentedConnection.Object.UseStoredProcedure("delete_flag")
.SetParam("@flag", flag.Name)
.ExecuteNonQueryAsync();
}
}
/// <summary>
/// Configuration data passed by appsettings.
/// </summary>
public class DatabaseServiceConfig
{
public string ConnectionString { get; set; }
public int PoolSize { get; set; }
public HashSet<string> Boards { get; set; }
}
}

@ -1,58 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace BantFlags.Data.Database
{
public partial class DatabaseService
{
// Maybe this could be better but I don't know SQL lol
private readonly string GetPostsQuery = @"SELECT posts.post_nr, flags.flag FROM flags LEFT JOIN (postflags) ON (postflags.flag = flags.id) LEFT JOIN (posts) ON (postflags.post_nr = posts.id) WHERE FIND_IN_SET(posts.post_nr, (@posts)) AND posts.board = @board";
/// <summary>
/// Returns the post numbers and their flags from the post numbers in the input.
/// </summary>
/// <param name="post_nr">List of post numbers on the page.</param>
public async Task<IEnumerable<IGrouping<int, DataRow>>> GetPosts(string post_nr, string board)
{
using var rentedConnection = await ConnectionPool.RentConnectionAsync();
DataTable table = await rentedConnection.Object.CreateQuery(GetPostsQuery)
.SetParam("@posts", post_nr)
.SetParam("@board", board)
.ExecuteTableAsync();
return table.AsEnumerable()
.GroupBy(x => x.GetValue<int>("post_nr"));
}
public async Task<List<Dictionary<string, string>>> GetPosts_V1(string post_nr, string board)
{
List<Dictionary<string, string>> posts = new List<Dictionary<string, string>>();
var x = await GetPosts(post_nr, board);
x.ForEach(x => posts.Add(new Dictionary<string, string>
{
{"post_nr", x.Key.ToString() },
{"region", string.Join("||", x.AsEnumerable().Select(y => y.GetValue<string>("flag")))}
}));
return posts;
}
public async Task<Dictionary<int, IEnumerable<string>>> GetPosts_V2(string post_nr, string board)
{
var posts = await GetPosts(post_nr, board);
return posts
.ToDictionary(
x => x.Key,
x => x.AsEnumerable().Select(x => x.GetValue<string>("flag"))
);
}
}
}

@ -1,20 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using System;
using System.Collections.Generic;
namespace BantFlags.Data
{
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (T item in enumeration)
{
action(item);
}
}
}
}

@ -1,61 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using MySql.Data.MySqlClient;
using Nito.AsyncEx;
using System;
using System.Data;
using System.Threading.Tasks;
namespace BantFlags.Data
{
public class MySqlConnectionPool : IDisposable
{
public AsyncCollection<MySqlConnection> Connections { get; }
protected string ConnectionString { get; }
protected int PoolSize { get; }
public MySqlConnectionPool(string connectionString, int poolSize)
{
PoolSize = poolSize;
ConnectionString = connectionString;
Connections = new AsyncCollection<MySqlConnection>(poolSize);
for (int i = 0; i < poolSize; i++)
{
var connection = new MySqlConnection(connectionString);
connection.Open();
Connections.Add(connection);
}
}
public async Task<PoolObject<MySqlConnection>> RentConnectionAsync()
{
return new PoolObject<MySqlConnection>(await Connections.TakeAsync(), obj =>
{
if (obj.State != ConnectionState.Open)
{
obj.Open();
}
Connections.Add(obj);
});
}
public void Dispose()
{
for (int i = 0; i < PoolSize; i++)
{
var connection = Connections.Take();
connection.Dispose();
}
}
}
}

@ -1,48 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using MySql.Data.MySqlClient;
using System;
using System.Data;
namespace BantFlags.Data
{
public static class MySqlExtensions
{
public static Query CreateQuery(this MySqlConnection connection, string sql)
{
connection.EnsureConnectionIsOpen();
return new Query(new MySqlCommand(sql, connection));
}
public static Query UseStoredProcedure(this MySqlConnection connection, string sql)
{
connection.EnsureConnectionIsOpen();
return new Query(new MySqlCommand(sql, connection)
{
CommandType = CommandType.StoredProcedure
});
}
public static T GetValue<T>(this DataRow row, string column)
{
object value = row[column];
if (value == null || value == DBNull.Value)
return default;
return (T)value;
}
private static void EnsureConnectionIsOpen(this MySqlConnection connection)
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
}
}
}

@ -1,29 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using System;
namespace BantFlags.Data
{
public class PoolObject<T> : IDisposable
{
public T Object { get; }
private Action<T> ReturnAction { get; }
public PoolObject(T o, Action<T> returnAction)
{
Object = o;
ReturnAction = returnAction;
}
public void Dispose()
{
ReturnAction(Object);
}
public static implicit operator T(PoolObject<T> poolObject)
=> poolObject.Object;
}
}

@ -1,52 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using System.Collections.Generic;
using System.Linq;
namespace BantFlags.Data
{
public class PostModel
{
public int PostNumber { get; private set; }
public string Board { get; private set; }
public string[] Flags { get; private set; }
private PostModel(int post_nr, string board, string[] flags)
{
PostNumber = post_nr;
Board = board;
Flags = flags;
}
public static (PostModel, string) Create(string post_nr, string board, string regions, string splitFlag, HashSet<string> knownFlags, HashSet<string> boards)
{
string[] empty = { "empty, or there were errors. Re-set your flags." };
if (!int.TryParse(post_nr, out int postNumber))
return (default, "Invalid post number.");
if (!boards.Contains(board))
return (default, "Invalid board parameter.");
if (regions == null)
return (new PostModel(postNumber, board, empty), default);
var flags = regions.Split(splitFlag);
if (flags.Count() > 30)
return (default, "Too many flags.");
foreach (string flag in flags)
{
if (!knownFlags.Contains(flag)) // Not ideal but it's better than doing it in the controller or passing the database here.
return (new PostModel(postNumber, board, empty), default);
}
return (new PostModel(postNumber, board, flags), default);
}
}
}

@ -1,65 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Threading.Tasks;
namespace BantFlags.Data
{
/// <summary>
/// Succinct methods for creating and executing database queries
/// </summary>
public class Query : IDisposable
{
private MySqlCommand Command { get; }
public Query(MySqlCommand cmd)
{
Command = cmd;
}
public async Task<DataTable> ExecuteTableAsync()
{
using (var reader = await Command.ExecuteReaderAsync())
{
DataTable table = new DataTable();
table.Load(reader);
return table;
}
}
public async Task ExecuteNonQueryAsync(bool reuse = false)
{
await Command.ExecuteNonQueryAsync();
if (!reuse)
{
Dispose();
}
}
public Query SetParam(string parameter, object value)
{
// When we reuse a query, we write over the parameter.
if (Command.Parameters.Contains(parameter))
{
Command.Parameters[parameter].Value = value;
}
else
{
Command.Parameters.AddWithValue(parameter, value);
}
return this;
}
public void Dispose()
{
Command.Dispose();
}
}
}

@ -1,150 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using ImageMagick;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace BantFlags.Data
{
public class Staging
{
public List<Flag> Flags { get; set; }
public string Password { get; }
public HashSet<string> Names { get; set; }
public Staging(string password)
{
Flags = new List<Flag>();
Password = password;
}
public void Clear()
{
Flags = new List<Flag>();
}
}
public enum Method
{
Add = 0,
Delete = 1,
Rename = 2
}
public class Flag
{
public string Name { get; set; }
public string OldName { get; set; }
public bool IsChecked { get; set; }
public Method FlagMethod { get; set; }
// This is bad but we need it so Flags can be generated by the input tag helper
public Flag()
{
}
private Flag(string name, Method method)
{
Name = name;
FlagMethod = method;
}
private Flag(string name, string oldName, Method method)
{
Name = name;
OldName = oldName;
FlagMethod = method;
}
public static Flag CreateFromDelete(string name) => new Flag(name, Method.Delete); // We don't need any validation for deleted flags.
public static (Flag, string) CreateFromRename(string oldName, string newName, HashSet<string> names)
{
(bool valid, string error) = ValidateFileName(newName, names);
if (!valid)
{
return (default, error);
}
return (new Flag(newName, oldName, Method.Rename), default);
}
public static async Task<(Flag, string)> CreateFromFile(IFormFile upload, HashSet<string> names)
{
byte[] PNGHeader = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
if (upload.ContentType.ToLower() != "image/png")
return (default, "Image must be a png.");
if (upload.Length > 15 * 1024)
return (default, "File too big. Max size is 15kb.");
var name = Path.GetFileNameWithoutExtension(upload.FileName);
(bool valid, string error) = ValidateFileName(name, names);
if (!valid)
return (default, error);
using (var memoryStream = new MemoryStream())
{
await upload.CopyToAsync(memoryStream);
memoryStream.Position = 0;
using (var image = new MagickImage(memoryStream))
{
if (image.Width != 16 || image.Height != 11)
return (default, "Invalid image dimensions. Flags should be 16px by 11px.");
}
using (var reader = new BinaryReader(memoryStream))
{
reader.BaseStream.Position = 0;
if (!reader.ReadBytes(PNGHeader.Length).SequenceEqual(PNGHeader))
return (default, "Invalid png header.");
}
}
return (new Flag(name, Method.Add), default);
}
/// <summary>
/// Filters file names created by users.
/// </summary>
/// <param name="name">The file name to validate.</param>
/// <param name="names">The list of current file names.</param>
private static (bool, string) ValidateFileName(string name, HashSet<string> names)
{
if (string.IsNullOrWhiteSpace(name))
return (false, "Flag name can't be empty.");
if (name.Length > 100)
return (false, "Flag name too long.");
if (name == "empty, or there were errors. Re - set your flags.")
return (false, "Invalid flag name.");
if (name.Contains("||") || name.Contains(","))
return (false, "Flag name contains invalid characters. You can't use \"||\" or \",\".");
if (names.Contains(name))
return (false, "A flag with that name already exists.");
return (true, name);
}
}
}

@ -1,21 +0,0 @@
@* (C) Copyright 2019 C-xC-c <boku@plum.moe>
This file is part of BantFlags.
BantFlags is licensed under the GNU AGPL Version 3.0 or later.
see the LICENSE file or <https: //www.gnu.org/licenses/agpl-3.0.en.html /> *@
@page
@model BantFlags.Pages.IndexModel
@{
ViewData["Title"] = "BantFlags";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>/bant/ Flags</h1>
<p>E<span lang="jp">メール</span>: boku (at) plum (dot) moe</p>
<a href="~/bantflags.user.js">Install Bantflags</a>
<br />
<br />
<a href="https://nineball.party/srsbsn/3521#bottom">Official Thread</a>
<br />
<br />
<a asp-page="Upload">Upload Flags</a>

@ -1,15 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BantFlags.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}

@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"]</title>
@RenderSection("Head", required: false)
</head>
<body style="text-align: center;">
@RenderBody()
@RenderSection("Scripts", required: false)
</body>
</html>

@ -1,123 +0,0 @@
@* (C) Copyright 2019 C-xC-c <boku@plum.moe>
This file is part of BantFlags.
BantFlags is licensed under the GNU AGPL Version 3.0 or later.
see the LICENSE file or <https: //www.gnu.org/licenses/agpl-3.0.en.html /> *@
@page
@using BantFlags.Data
@model BantFlags.UploadModel
@{
ViewData["Title"] = "Upload";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>Upload</h1>
<img src="~/montage.png" />
<h2 id="message">@Model.Message</h2>
<h2>Add a Flag</h2>
<form method="post" asp-page-handler="Add" enctype="multipart/form-data">
<input type="file" name="upload" />
<input type="checkbox" name="gloss" value="true" /><span>Apply Gloss?</span>
<br />
<br />
<input type="submit" value="Upload Flag" />
</form>
<h2>Manage Existing Flags</h2>
<form method="post">
<select name="flag">
@foreach (string s in Model.StagedFlags.Names)
{
<option>@s</option>
}
</select>
<input type="text" name="newName" />
<br />
<br />
<button asp-page-handler="Delete" type="submit">Delete Flag</button>
<button asp-page-handler="Rename" type="submit">Rename Flag</button>
</form>
<h2>Commit Changes</h2>
<form method="post" asp-page-handler="Commit" enctype="multipart/form-data">
<label>Password:</label>
<input type="text" name="password" />
<br />
<br />
<input type="submit" value="Commit Changes" />
</form>
@if (Model.StagedFlags.Flags.Any())
{
<h2>Pending Changes</h2>
<form method="post" asp-page-handler="Unstage">
<input type="text" name="password" />
<br />
<br />
<button type="submit">Remove from staging</button>
<h3>Deleted Flags</h3>
@for (int i = 0; i < Model.StagedFlags.Flags.Count(); i++)
{
if (Model.StagedFlags.Flags[i].FlagMethod == Method.Delete)
{
<div class="flag">
<label>@(Model.StagedFlags.Flags[i].Name)</label>
<img src="~/flags/@(Model.StagedFlags.Flags[i].Name).png" />
<input type="hidden" name="flags[@i].Name" value="@Model.StagedFlags.Flags[i].Name" />
<input type="hidden" name="flags[@i].FlagMethod" value="@Model.StagedFlags.Flags[i].FlagMethod" />
<input type="checkbox" name="flags[@i].IsChecked" value="true" />
</div>
}
}
<h3>Renamed Flags</h3>
@for (int i = 0; i < Model.StagedFlags.Flags.Count(); i++)
{
if (Model.StagedFlags.Flags[i].FlagMethod == Method.Rename)
{
<div class="flag">
<label>@(Model.StagedFlags.Flags[i].Name)</label>
<img src="~/flags/@(Model.StagedFlags.Flags[i].OldName).png" />
<input type="hidden" name="flags[@i].Name" value="@Model.StagedFlags.Flags[i].Name" />
<input type="hidden" name="flags[@i].FlagMethod" value="@Model.StagedFlags.Flags[i].FlagMethod" />
<input type="checkbox" name="flags[@i].IsChecked" value="true" />
</div>
}
}
<h3>Added Flags</h3>
@for (int i = 0; i < Model.StagedFlags.Flags.Count(); i++)
{
if (Model.StagedFlags.Flags[i].FlagMethod == Method.Add)
{
<div class="flag">
<label>@(Model.StagedFlags.Flags[i].Name)</label>
<img src="~/flags/staging/@(Model.StagedFlags.Flags[i].Name).png" />
<input type="hidden" name="flags[@i].Name" value="@Model.StagedFlags.Flags[i].Name" />
<input type="hidden" name="flags[@i].FlagMethod" value="@Model.StagedFlags.Flags[i].FlagMethod" />
<input type="checkbox" name="flags[@i].IsChecked" value="true" />
</div>
}
}
</form>
}
@section Head {
<link rel="stylesheet" href="~/upload.css" />
}
@section Scripts {
@* Place flag image inside the <select> because ASP removes "invalid HTML" *@
<script>
window.addEventListener('load', function (e) {
let x = document.getElementsByTagName('select')[0].children
Array.prototype.slice.call(x).forEach(function (y) {
var name = y.innerHTML;
y.innerHTML = "<img src=\"flags/" + name + ".png\">" + name
});
}, { once: true });
</script>
}

@ -1,191 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using BantFlags.Data;
using BantFlags.Data.Database;
using ImageMagick;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace BantFlags
{
public class UploadModel : PageModel
{
private DatabaseService Database { get; set; }
public Staging StagedFlags { get; set; }
public string Message { get; private set; }
private string WebRoot { get; }
public HashSet<string> AllNames => StagedFlags.Names.Concat(StagedFlags.Flags.Select(x => x.Name)).ToHashSet();
public UploadModel(DatabaseService dbs, Staging ns, IWebHostEnvironment env)
{
Database = dbs;
StagedFlags = ns;
WebRoot = env.WebRootPath;
}
public void OnGet()
{
StagedFlags.Names = StagedFlags.Names ?? Database.KnownFlags;
}
public IActionResult OnPostDelete(string flag)
{
var stagingFlag = Flag.CreateFromDelete(flag);
StagedFlags.Flags.Add(stagingFlag);
StagedFlags.Names.Remove(stagingFlag.Name);
Message = $"{stagingFlag.Name} deleted.";
return Page();
}
public IActionResult OnPostRename(string flag, string newName)
{
(Flag stagingFlag, string error) = Flag.CreateFromRename(flag, newName, AllNames);
if (stagingFlag is null)
{
Message = error;
return Page();
}
StagedFlags.Flags.Add(stagingFlag);
StagedFlags.Names.Add(stagingFlag.Name);
Message = $"{stagingFlag.OldName} renamed to {stagingFlag.Name}.";
return Page();
}
public async Task<IActionResult> OnPostAddAsync(IFormFile upload, bool gloss)
{
(Flag stagingFlag, string error) = await Flag.CreateFromFile(upload, AllNames);
if (stagingFlag is null)
{
Message = error;
return Page();
}
using var memoryStream = new MemoryStream();
await upload.CopyToAsync(memoryStream);
memoryStream.Position = 0;
// Magic.NET is a huge dependency to be used like this
// Maybe we should switch to a Process and expect to have
// ImageMagick installed on the target machine.
using var image = new MagickImage(memoryStream);
if (gloss)
{
using var glossImage = new MagickImage(WebRoot + "/gloss.png");
glossImage.Composite(image, new PointD(0, 0), CompositeOperator.Over);
}
image.Write(WebRoot + "/flags/staging/" + upload.FileName);
StagedFlags.Flags.Add(stagingFlag);
Message = $"{stagingFlag.Name} uploaded";
return Page();
}
public IActionResult OnPostUnstage(Flag[] flags, string password)
{
if (password != StagedFlags.Password)
{
Message = "Incorrect Password";
return Page();
}
for (int i = flags.Length - 1; i >= 0; i--)
{
if (flags[i].IsChecked != true)
{
continue;
}
StagedFlags.Flags.RemoveAt(i);
var flag = flags[i];
switch (flag.FlagMethod)
{
case Method.Add:
System.IO.File.Delete(WebRoot + "/flags/staging/" + flag.Name);
StagedFlags.Names.Remove(flag.Name);
break;
case Method.Delete:
StagedFlags.Names.Add(flag.Name);
break;
case Method.Rename:
StagedFlags.Names.Remove(flag.Name);
break;
default:
throw new Exception();
}
}
Message = "Removed flags from staging";
return Page();
}
public async Task<IActionResult> OnPostCommit(string password)
{
if (password != StagedFlags.Password)
{
Message = "Incorrect Password";
return Page();
}
foreach (var flag in StagedFlags.Flags)
{
string flagname = flag.Name + ".png";
switch (flag.FlagMethod)
{
case Method.Add:
await Database.InsertFlagAsync(flag);
Directory.Move(WebRoot + "/flags/staging/" + flagname, WebRoot + "/flags/" + flagname);
break;
case Method.Delete:
await Database.DeleteFlagAsync(flag);
Directory.Move(WebRoot + "/flags/" + flagname, WebRoot + "/flags/dead/" + Guid.NewGuid().ToString()); // Use a GUID so flags with the same name can be deleted.
break;
case Method.Rename:
await Database.RenameFlagAsync(flag);
Directory.Move(WebRoot + "/flags/" + flag.OldName + ".png", WebRoot + "/flags/" + flagname);
break;
default:
throw new Exception();
}
}
await Database.UpdateKnownFlags();
StagedFlags.Names = Database.KnownFlags;
StagedFlags.Clear();
Message = "Changes committed successfully";
return Page();
}
}
}

@ -1,3 +0,0 @@
@using BantFlags
@namespace BantFlags.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@ -1,3 +0,0 @@
@{
Layout = "_Layout";
}

@ -1,31 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.IO;
namespace BantFlags
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((host, config) =>
{
// Explicitly look for appsettings.json in the program's directory
config.AddJsonFile(Path.Join(System.AppDomain.CurrentDomain.BaseDirectory + "appsettings.json"), optional: false, reloadOnChange: false);
});
}
}

@ -1,30 +0,0 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:17777",
"sslPort": 44366
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"BantFlags": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}

@ -1,83 +0,0 @@
// (C) Copyright 2019 C-xC-c <boku@plum.moe>
// This file is part of BantFlags.
// BantFlags is licensed under the GNU AGPL Version 3.0 or later.
// see the LICENSE file or <https://www.gnu.org/licenses/>
using BantFlags.Data;
using BantFlags.Data.Database;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using System.IO;
namespace BantFlags
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson(); // So we can format complex datatypes into JSON
services.AddRazorPages();
if (!Directory.Exists(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "keys/")))
{
Directory.CreateDirectory(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "keys/"));
}
services.AddDataProtection()
.SetApplicationName("BantFlags")
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "keys")));
services.AddSingleton(new DatabaseService(Configuration.GetSection("dbconfig").Get<DatabaseServiceConfig>()));
services.AddSingleton(new Staging(Configuration.GetValue<string>("staging-password")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
string webroot = Configuration.GetValue<string>("webroot");
if (Directory.Exists(webroot))
{
env.WebRootPath = webroot;
env.WebRootFileProvider = new PhysicalFileProvider(env.WebRootPath);
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "text/plain"
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
}
}

@ -1,14 +0,0 @@
{
"AllowedHosts": "*",
"dbconfig": {
"connectionstring": "Server=localhost;Port=3306;User ID=user;Password=password;Database=bantflags",
"poolsize": 2,
"boards": [
"bant",
"nap",
"srsbsn"
]
},
"webroot": "/var/www/html",
"staging-password": "supersecretpassword"
}

@ -1,4 +0,0 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

@ -1,4 +0,0 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

Binary file not shown.

Before

Width:  |  Height:  |  Size: 436 B

@ -1,28 +0,0 @@
body {
background: #ffe url(fade.png) top center repeat-x;
}
h1, h2, h3 {
color: maroon;
}
h3 {
clear: both;
padding-top: 20px;
}
.flag-container {
width: 60%;
margin: auto;
}
.flag {
margin: auto;
width: 12%;
display: inline-block;
padding-bottom: 10px;
}
#message {
color: #ee0;
}
Loading…
Cancel
Save