107 lines
5.3 KiB
PowerShell
107 lines
5.3 KiB
PowerShell
param(
|
|
[ValidateSet('Start', 'Stop', 'Serve')][string]$Action = 'Start',
|
|
[ValidateRange(1024, 65535)][int]$Port = 8080
|
|
)
|
|
$ErrorActionPreference = 'Stop'
|
|
$projectRoot = Split-Path -Parent $PSScriptRoot
|
|
$siteRoot = [IO.Path]::GetFullPath((Join-Path $projectRoot 'dist'))
|
|
$statePath = Join-Path $projectRoot '.local-server.json'
|
|
$scriptPath = $PSCommandPath
|
|
|
|
function Get-SiteProcess {
|
|
if (-not (Test-Path -LiteralPath $statePath)) { return $null }
|
|
$state = Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json
|
|
$siteProcess = Get-CimInstance Win32_Process -Filter ('ProcessId = ' + [int]$state.pid)
|
|
if ($siteProcess -and $siteProcess.CommandLine -and $siteProcess.CommandLine.Contains($scriptPath) -and $siteProcess.CommandLine.Contains('-Action Serve')) {
|
|
return [pscustomobject]@{ Process = $siteProcess; Port = [int]$state.port }
|
|
}
|
|
return $null
|
|
}
|
|
|
|
if ($Action -eq 'Stop') {
|
|
$running = Get-SiteProcess
|
|
if ($running) {
|
|
Stop-Process -Id $running.Process.ProcessId
|
|
Write-Host ('MANGABOM stopped: http://localhost:' + $running.Port + '/')
|
|
} else { Write-Host 'MANGABOM is not running.' }
|
|
exit 0
|
|
}
|
|
if ($Action -eq 'Start') {
|
|
& (Join-Path $PSScriptRoot 'index-manga.ps1') | Out-Host
|
|
$running = Get-SiteProcess
|
|
if ($running) {
|
|
Write-Host ('MANGABOM is already running: http://localhost:' + $running.Port + '/')
|
|
exit 0
|
|
}
|
|
$powerShellPath = Join-Path $PSHOME 'powershell.exe'
|
|
$arguments = '-NoProfile -ExecutionPolicy Bypass -File "' + $scriptPath + '" -Action Serve -Port ' + $Port
|
|
$child = Start-Process -FilePath $powerShellPath -ArgumentList $arguments -WindowStyle Hidden -WorkingDirectory $env:SystemRoot -RedirectStandardOutput (Join-Path $projectRoot '.local-server-output.log') -RedirectStandardError (Join-Path $projectRoot '.local-server-error.log') -PassThru
|
|
for ($attempt = 0; $attempt -lt 25; $attempt++) {
|
|
Start-Sleep -Milliseconds 200
|
|
$child.Refresh()
|
|
if ($child.HasExited) { throw ('Server failed. See ' + (Join-Path $projectRoot '.local-server-error.log')) }
|
|
try {
|
|
$response = Invoke-WebRequest -Uri ('http://localhost:' + $Port + '/') -UseBasicParsing -TimeoutSec 2
|
|
if ($response.Headers['X-Mangabom-Local'] -eq '1') {
|
|
Write-Host ('MANGABOM: http://localhost:' + $Port + '/')
|
|
exit 0
|
|
}
|
|
} catch { }
|
|
}
|
|
throw 'Server did not become ready. Check the local server logs.'
|
|
}
|
|
|
|
$mime = @{
|
|
'.html' = 'text/html; charset=utf-8'; '.css' = 'text/css; charset=utf-8'
|
|
'.js' = 'application/javascript; charset=utf-8'; '.json' = 'application/json; charset=utf-8'
|
|
'.webp' = 'image/webp'; '.png' = 'image/png'; '.jpg' = 'image/jpeg'; '.jpeg' = 'image/jpeg'
|
|
'.avif' = 'image/avif'; '.svg' = 'image/svg+xml'; '.ico' = 'image/x-icon'; '.ttf' = 'font/ttf'
|
|
'.woff' = 'font/woff'; '.woff2' = 'font/woff2'; '.txt' = 'text/plain; charset=utf-8'
|
|
}
|
|
$listener = [Net.HttpListener]::new()
|
|
$listener.Prefixes.Add(('http://localhost:' + $Port + '/'))
|
|
try {
|
|
$listener.Start()
|
|
@{ pid = $PID; port = $Port } | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding UTF8
|
|
while ($listener.IsListening) {
|
|
$context = $listener.GetContext()
|
|
$response = $context.Response
|
|
$response.Headers['X-Mangabom-Local'] = '1'
|
|
$response.Headers['X-Content-Type-Options'] = 'nosniff'
|
|
$response.Headers['Cache-Control'] = 'no-cache'
|
|
try {
|
|
if ($context.Request.HttpMethod -notin @('GET', 'HEAD')) {
|
|
$response.StatusCode = 405
|
|
$response.Headers['Allow'] = 'GET, HEAD'
|
|
continue
|
|
}
|
|
$relativePath = [Uri]::UnescapeDataString($context.Request.Url.AbsolutePath).TrimStart('/').Replace('/', '\')
|
|
if (-not $relativePath) { $relativePath = 'index.html' }
|
|
$filePath = [IO.Path]::GetFullPath([IO.Path]::Combine($siteRoot, $relativePath))
|
|
if (-not $filePath.StartsWith($siteRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
|
$response.StatusCode = 403
|
|
continue
|
|
}
|
|
# Refresh from folders when the reader requests the catalogue.
|
|
# This works on SMB shares without unreliable filesystem watchers.
|
|
if ($filePath.Equals((Join-Path $siteRoot 'manga\library.json'), [StringComparison]::OrdinalIgnoreCase)) {
|
|
& (Join-Path $PSScriptRoot 'index-manga.ps1') 6>$null
|
|
}
|
|
if (-not [IO.File]::Exists($filePath)) {
|
|
$response.StatusCode = 404
|
|
continue
|
|
}
|
|
$contentType = $mime[[IO.Path]::GetExtension($filePath).ToLowerInvariant()]
|
|
if (-not $contentType) { $contentType = 'application/octet-stream' }
|
|
$response.ContentType = $contentType
|
|
$file = [IO.File]::OpenRead($filePath)
|
|
try {
|
|
$response.ContentLength64 = $file.Length
|
|
if ($context.Request.HttpMethod -eq 'GET') { $file.CopyTo($response.OutputStream) }
|
|
} finally { $file.Dispose() }
|
|
} catch {
|
|
try { $response.StatusCode = 500 } catch { }
|
|
[Console]::Error.WriteLine($_.Exception.Message)
|
|
} finally { $response.Close() }
|
|
}
|
|
} finally { $listener.Close() } |