@ -7,274 +7,181 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages ;
using Microsoft.AspNetCore.Mvc.RazorPages ;
using System ;
using System ;
using System.Collections.Generic ;
using System.Collections.Generic ;
using System.Data ;
using System.IO ;
using System.IO ;
using System.Linq ;
using System.Linq ;
using System.Threading.Tasks ;
using System.Threading.Tasks ;
namespace BantFlags
namespace BantFlags
{
{
// I don't know if I need these anymore.
[RequestFormLimits(ValueCountLimit = 5000)]
[IgnoreAntiforgeryToken(Order = 2000)]
public class UploadModel : PageModel
public class UploadModel : PageModel
{
{
private IWebHostEnvironment Env { get ; }
private DatabaseService Database { get ; set ; }
private DatabaseService Database { get ; set ; }
public Staging StagedFlags { get ; set ; }
public string Message { get ; private set ; }
private readonly byte [ ] PNGHeader = new byte [ ] { 0x89 , 0x50 , 0x4E , 0x47 , 0x0D , 0x0A , 0x1A , 0x0A } ;
private string WebRoot { get ; }
private string FlagsPath { get ; set ; }
public Staging staging { get ; set ; }
public HashSet < string > AllNames = > StagedFlags . Names . Concat ( StagedFlags . Flags . Select ( x = > x . Name ) ) . ToHashSet ( ) ;
public UploadModel ( IWebHostEnvironment env , DatabaseService db , Staging s)
public UploadModel ( DatabaseService db s , Staging n s, IWebHostEnvironment env )
{
{
Env = env ;
Database = dbs ;
Database = db ;
staging = s;
StagedFlags = n s;
FlagsPath = Env . WebRootPath + "/flags/" ;
WebRoot = env . WebRootPath ;
}
}
public string Message { get ; private set ; }
public void OnGet ( )
// TODO: These bound properties should be inlined.
[BindProperty]
public IFormFile Upload { get ; set ; }
[BindProperty]
public bool ShouldGloss { get ; set ; }
public async void OnGet ( )
{
{
if ( staging . Flags = = null )
StagedFlags . Names = StagedFlags . Names ? ? Database . KnownFlags ;
{
staging . Flags = await Database . GetFlags ( ) ; // Because we can't populate Flags in the constructor.
}
}
}
public IActionResult OnPostUnstage ( List < FormFlag > addedAndDeletedFlags , List < RenameFlag > renamedFlags , string password )
public IActionResult OnPostDelete ( string flag )
{
if ( password ! = staging . Password ) // TODO: Maybe we should hash this?
{
Message = "Wrong Password" ;
return Page ( ) ;
}
try // Haha I can't program
{
var addedAndDeleted = addedAndDeletedFlags . Where ( x = > x . IsChecked ) ;
var renamed = renamedFlags . Where ( x = > x . IsChecked ) ;
addedAndDeleted . ForEach ( x = >
_ = x . FormMethod switch
{
{
// Using an enum seems kinda redundant here.
var stagingFlag = Flag . CreateFromDelete ( flag ) . Value ;
Method . Delete = > staging . DeletedFlags . Remove ( staging . DeletedFlags . First ( y = > y . Name = = x . Name ) ) ,
Method . Add = > staging . AddedFlags . Remove ( staging . AddedFlags . First ( y = > y . Name = = x . Name ) ) ,
_ = > throw new Exception ( )
} ) ;
renamed . ForEach ( x = > staging . RenamedFlags . Remove ( staging . RenamedFlags . First ( y = > y . Name = = x . Name ) ) ) ; // These can be reworked to use asp-for and then we can work off the original objects.
StagedFlags . Flags . Add ( stagingFlag ) ;
StagedFlags . Names . Remove ( stagingFlag . Name ) ;
addedAndDeleted . ForEach ( x = > staging . Flags . Add ( x . Name ) ) ;
renamed . ForEach ( x = > staging . Flags . Add ( x . Name ) ) ;
staging . Flags = staging . Flags . Distinct ( ) . OrderBy ( x = > x ) . ToList ( ) ;
Message = $"Successfully unstaged flags" ;
}
catch
{
Message = "Something went very wrong" ;
}
Message = $"{stagingFlag.Name} deleted." ;
return Page ( ) ;
return Page ( ) ;
}
}
public async Task < IActionResult > OnPostCommitAsync ( string password )
public IActionResult OnPostRename ( string flag , string newName )
{
{
if ( password ! = staging . Password )
var stagingFlag = Flag . CreateFromRename ( flag , newName , AllNames ) ;
if ( stagingFlag . Failed )
{
{
Message = "Wrong Password" ;
Message = stagingFlag . ErrorMessage ;
return Page ( ) ;
return Page ( ) ;
}
}
try
{
// TODO: This needs to be rewritten / burnt / both
if ( staging . DeletedFlags . Any ( ) )
{
await Database . DeleteFlagsAsync ( staging . DeletedFlags ) ;
staging . DeletedFlags
StagedFlags . Flags . Add ( stagingFlag . Value ) ;
. ForEach ( flag = > System . IO . File . Copy ( Path . Combine ( FlagsPath , flag . Name + ".png" ) , Path . Combine ( FlagsPath , "dead/" , flag . Name + ".png" ) ) ) ;
StagedFlags . Names . Remove ( stagingFlag . Value . OldName ) ;
}
if ( staging . AddedFlags . Any ( ) )
Message = $"{stagingFlag.Value.OldName} renamed to {stagingFlag.Value.Name}." ;
{
return Page ( ) ;
await Database . InsertFlagsAsync ( staging . AddedFlags ) ;
staging . AddedFlags
. ForEach ( flag = > System . IO . File . Copy ( Path . Combine ( FlagsPath , "staging/" , flag . Name + ".png" ) , Path . Combine ( FlagsPath , flag . Name + ".png" ) ) ) ;
}
}
if ( staging . RenamedFlags . Any ( ) )
public async Task < IActionResult > OnPostAddAsync ( IFormFile upload , bool gloss )
{
{
await Database . RenameFlagsAsync ( staging . RenamedFlags ) ;
var stagingFlag = await Flag . CreateFromFile ( upload , AllNames ) ;
staging . RenamedFlags
. ForEach ( flag = > System . IO . File . Copy ( Path . Combine ( FlagsPath , flag . Name + ".png" ) , Path . Combine ( FlagsPath , flag . NewName + ".png" ) ) ) ;
}
await Database . UpdateKnownFlags ( ) ;
if ( stagingFlag . Failed )
staging . Flags = await Database . GetFlags ( ) ;
staging . Clear ( ) ;
Message = "Changes Commited successfully" ;
}
catch ( Exception e )
{
{
Message = "Something went bang\n" + e . Message ;
Message = stagingFlag . ErrorMessage ;
}
return Page ( ) ;
return Page ( ) ;
}
}
public IActionResult OnPostDelete ( string flag )
using var memoryStream = new MemoryStream ( ) ;
{
await upload . CopyToAsync ( memoryStream ) ;
staging . DeletedFlags . Add ( new FormFlag
{
Name = flag
} ) ;
staging. Flags . Remove ( flag ) ;
memoryStream . Position = 0 ;
return Page ( ) ;
// 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 ) ;
public IActionResult OnPostRename ( string flag , string newName )
if ( gloss )
{
if ( ! ( FileNameIsValid ( newName ) ) )
{
{
Message = "Invalid Filename." ;
using var glossImage = new MagickImage ( WebRoot + "/gloss.png" ) ;
return Page ( ) ;
glossImage . Composite ( image , new PointD ( 0 , 0 ) , CompositeOperator . Over ) ;
}
}
staging . RenamedFlags . Add ( new RenameFlag
image . Write ( WebRoot + "/flags/staging/" + upload . FileName ) ;
{
Name = flag ,
NewName = newName
} ) ;
staging. Flags . Remove ( flag ) ;
StagedFlags . Flags . Add ( stagingFlag . Value ) ;
Message = $"{stagingFlag.Value.Name} uploaded" ;
return Page ( ) ;
return Page ( ) ;
}
}
public async Task < IActionResult > OnPostAddAsync ( )
public IActionResult OnPostUnstage ( Flag [ ] flags , string password )
{
try
{
{
if ( ! ( await ValidateImageAsync ( ) ) )
if ( password ! = StagedFlags . Password )
{
{
Message = "Invalid Image. ";
Message = "Incorrect Password ";
return Page ( ) ;
return Page ( ) ;
}
}
// TODO: maybe there's something no releasing memory here. - can't Directory.Move().
for ( int i = flags . Length - 1 ; i > = 0 ; i - - )
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 ( ShouldGloss )
{
{
using var gloss = new MagickImage ( Env . WebRootPath + "/gloss.png" ) ;
if ( flags [ i ] . IsChecked ! = true )
{
gloss . Composite ( image , new PointD ( 0 , 0 ) , CompositeOperator . Over ) ;
continue ;
}
}
image. Write ( FlagsPath + "staging/" + Upload . FileName ) ;
StagedFlags . Flags . RemoveAt ( i ) ;
staging . AddedFlags . Add ( new FormFlag
var flag = flags [ i ] ;
switch ( flag . FlagMethod )
{
{
Name = Path . GetFileNameWithoutExtension ( Upload . FileName )
case Method . Add :
} ) ;
System . IO . File . Delete ( WebRoot + "/flags/staging/" + flag . Name ) ;
StagedFlags . Names . Remove ( flag . Name ) ;
break ;
Message = "Flag uploaded successfully!" ;
case Method . Delete :
StagedFlags . Names . Add ( flag . Name ) ;
break ;
return Page ( ) ;
case Method . Rename :
StagedFlags . Names . Add ( flag . OldName ) ;
break ;
default :
throw new Exception ( ) ;
}
}
}
catch ( Exception e )
{
Message = $"Something went bang.\n\n\n{e.Message}" ;
Message = "Removed flags from staging" ;
return Page ( ) ;
return Page ( ) ;
}
}
}
// TODO: hash images and check against for duplicates.
public async Task < IActionResult > OnPostCommit ( string password )
// or is that going too far?
/// <summary>
/// Rigorously validates an image to ensure it's a flag.
/// </summary>
public async Task < bool > ValidateImageAsync ( )
{
{
var fileName = Path . GetFileNameWithoutExtension ( Upload . FileName ) ;
if ( password ! = StagedFlags . Password )
if ( ! ( FileNameIsValid ( fileName ) )
| | Upload . Length > 15 * 1024 // 15KB
| | Upload . ContentType . ToLower ( ) ! = "image/png" )
{
{
return false ;
Message = "Incorrect Password" ;
return Page ( ) ;
}
}
using ( var memoryStream = new MemoryStream ( ) )
foreach ( var flag in StagedFlags . Flags )
{
{
await Upload . CopyToAsync ( memoryStream ) ;
string flagname = flag . Name + ".png" ;
memoryStream . Position = 0 ;
switch ( flag . FlagMethod )
using ( var image = new MagickImage ( memoryStream ) )
{
{
if ( image . Width ! = 16 | | image . Height ! = 11 )
case Method . Add :
{
await Database . InsertFlagAsync ( flag ) ;
return false ;
Directory . Move ( WebRoot + "/flags/staging/" + flagname , WebRoot + "/flags/" + flagname ) ;
}
break ;
}
using ( var reader = new BinaryReader ( memoryStream ) )
case Method . Delete :
{
await Database . DeleteFlagAsync ( flag ) ;
reader . BaseStream . Position = 0 ;
Directory . Move ( WebRoot + "/flags/" + flagname , WebRoot + "/flags/dead/" + flagname ) ;
break ;
return reader . ReadBytes ( PNGHeader . Length ) . SequenceEqual ( PNGHeader ) ;
case Method . Rename :
}
await Database . RenameFlagAsync ( flag ) ;
Directory . Move ( WebRoot + "/flags/" + flag . OldName + ".png" , WebRoot + "/flags/" + flagname ) ;
break ;
default :
throw new Exception ( ) ;
}
}
}
}
/// <summary>
await Database . UpdateKnownFlags ( ) ;
/// Matches bad things we don't want in filenames.
StagedFlags . Names = Database . KnownFlags ;
/// Inverts the result - returns false on a match.
StagedFlags . Clear ( ) ;
/// </summary>
/// <param name="fileName">The name of the file to validate.</param>
Message = "Changes committed successfully" ;
/// <returns></returns>
return Page ( ) ;
private bool FileNameIsValid ( string fileName ) = >
}
! ( fileName = = null
| | fileName . Contains ( "||" )
| | fileName . Contains ( "," )
| | Database . KnownFlags . Contains ( fileName )
| | staging . AddedFlags . Select ( x = > x . Name ) . Contains ( fileName )
| | staging . DeletedFlags . Select ( x = > x . Name ) . Contains ( fileName )
| | staging . RenamedFlags . Select ( x = > x . Name ) . Contains ( fileName )
| | staging . RenamedFlags . Select ( x = > x . NewName ) . Contains ( fileName )
| | fileName . Length > 100 ) ;
}
}
}
}