<# .SYNOPSIS ezfs: upload files to ezfileshare from the command line and get one download link. .DESCRIPTION ezfs.ps1 report.pdf photos.zip $link = .\ezfs.ps1 -Quiet release.zip The link is the script's output; progress goes to the screen and errors to the error stream. The exit code is 0 only when the link was created. Runs in Windows PowerShell 5.1 and PowerShell 7 (Windows, macOS, Linux); nothing to install. It sends files with curl (curl.exe ships with Windows 10 and 11) when there is one, and with .NET's own HTTP client otherwise. Everything it does goes through the site's API (backend/main.py): GET /api/info limits (files per link, size per file) POST /api/shares announce the files; returns a share id and upload token PUT /api/shares/{id}/files/{fileId} send one file GET /api/shares/{id}/progress follow the virus scan; "ready" means the link works GET /api/shares/{id} the published link's expiry date build.sh fills in the version and the default site. No double curly braces anywhere in this file: the web server treats them as a template when it serves the script. .PARAMETER Server The ezfileshare site to upload to. Default: the EZFS_SERVER environment variable, else the site this script came from. .PARAMETER Quiet Print only the link, no progress. .PARAMETER Version Print the version and exit. #> [CmdletBinding(PositionalBinding = $false)] param( [Alias('s')][string]$Server, [Alias('q')][switch]$Quiet, [Alias('V')][switch]$Version, [Parameter(ValueFromRemainingArguments = $true)][string[]]$Files ) $EzfsVersion = '4508abbc1ee1' $DefaultServer = 'https://ezfileshare.io' $Attempts = 3 # per file, for failures that may pass (network, busy server) $ScanWait = 4200 # seconds to wait for the virus scan; the server gives up after an hour idle $ErrorActionPreference = 'Stop' function Say([string]$Text) { if (-not $Quiet) { [Console]::Error.WriteLine($Text) } } function Fail([string]$Text) { [Console]::Error.WriteLine("ezfs: error: $Text") exit 1 } # The same spellings as the shell script (--quiet, --server SITE, ...) work here too. $named = @() if (-not $Files) { $Files = @() } for ($i = 0; $i -lt $Files.Count; $i++) { switch -Regex ($Files[$i]) { '^--quiet$' { $Quiet = $true; continue } '^--version$' { $Version = $true; continue } '^--help$' { $Files = @(); $named = @(); $i = [int]::MaxValue - 1; continue } '^--server$' { $i++; if ($i -lt $Files.Count) { $Server = $Files[$i] } else { Fail '--server needs a site address' }; continue } default { $named += $Files[$i] } } } $Files = $named if ($Version) { "ezfs $EzfsVersion"; exit 0 } if (-not $Files -or $Files.Count -eq 0) { [Console]::Error.WriteLine("Usage: ezfs [options] ...`n`nUploads the files and prints one download link for all of them. No account needed.`nOptions:`n -s, --server SITE the ezfileshare site to upload to (or set EZFS_SERVER)`n -q, --quiet print only the link, no progress`n -V, --version print the version and exit") exit 2 } if ($EzfsVersion -ne 'dev') { if ($DefaultServer -notmatch '^https://') { Fail 'updates require an HTTPS release site' } [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $release = $DefaultServer.TrimEnd('/') + '/cli' $manifest = (Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 30 "$release/SHA256SUMS").Content if ($manifest -is [byte[]]) { $manifest = [Text.Encoding]::ASCII.GetString($manifest) } if ($manifest -notmatch '(?m)^([a-f0-9]{64}) +ezfs\.ps1\s*$') { Fail 'invalid release checksum' } $expected = $Matches[1] if ((Get-FileHash -LiteralPath $PSCommandPath -Algorithm SHA256).Hash -ne $expected) { $candidate = "$PSCommandPath.$([Guid]::NewGuid()).tmp" try { Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -TimeoutSec 30 "$release/ezfs.ps1" -OutFile $candidate if ((Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash -ne $expected) { Fail 'update checksum mismatch' } [IO.File]::Replace($candidate, $PSCommandPath, "$candidate.previous") Remove-Item -LiteralPath "$candidate.previous" } finally { if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate } } & $PSCommandPath -Server $Server -Quiet:$Quiet -Files $Files exit $LASTEXITCODE } } if (-not $Server) { $Server = $env:EZFS_SERVER } if (-not $Server) { $Server = $DefaultServer } $Server = $Server.TrimEnd('/') if ($Server -notmatch '://') { $Server = "https://$Server" } # ---------- how to talk HTTP ---------- # Windows PowerShell 5.1 defaults to old TLS versions and doesn't load the HTTP client itself. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 Add-Type -AssemblyName System.Net.Http $Http = New-Object System.Net.Http.HttpClient $Http.Timeout = [System.Threading.Timeout]::InfiniteTimeSpan # a large file takes as long as it takes $Agent = "ezfs-cli/$EzfsVersion (powershell)" [void]$Http.DefaultRequestHeaders.TryAddWithoutValidation('User-Agent', $Agent) $Token = '' # The real curl program, if there is one ("curl" alone is an alias in Windows PowerShell). # EZFS_TOOL=dotnet skips it (for testing). $Curl = $null if ($env:EZFS_TOOL -ne 'dotnet') { $Curl = Get-Command curl.exe, curl -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 } # Sends a request with .NET. Returns @{ Status = 201; Body = '...' }; Status 0 means no # answer, and Body then says why. function Invoke-Api([string]$Method, [string]$Url, $Content = $null) { $request = New-Object System.Net.Http.HttpRequestMessage ((New-Object System.Net.Http.HttpMethod $Method), $Url) if ($script:Token) { [void]$request.Headers.TryAddWithoutValidation('X-Upload-Token', $script:Token) } if ($null -ne $Content) { $request.Content = $Content } try { $response = $Http.SendAsync($request).GetAwaiter().GetResult() $body = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() return @{ Status = [int]$response.StatusCode; Body = $body } } catch { $cause = $_.Exception while ($cause.InnerException) { $cause = $cause.InnerException } return @{ Status = 0; Body = $cause.Message } } finally { $request.Dispose() } } # Sends one file as the body of a PUT, streamed from disk. Same return value as Invoke-Api. function Send-FileBody([string]$Url, [System.IO.FileInfo]$File) { if ($Curl) { $reply = [System.IO.Path]::GetTempFileName() try { $bar = '--silent' if (-not $Quiet -and -not [Console]::IsErrorRedirected) { $bar = '--progress-bar' } $curlArgs = @($bar, '--show-error', '-X', 'PUT', '-T', $File.FullName, '-A', $Agent, '-H', 'Content-Type: application/octet-stream', '-H', "X-Upload-Token: $script:Token", '-H', 'Expect:', '-o', $reply, '-w', '%{http_code}', $Url) $code = & $Curl.Source @curlArgs $status = 0 if ("$code" -match '^[1-5]\d\d$') { $status = [int]"$code" } $body = "curl could not connect" if ($status -ne 0) { $body = [System.IO.File]::ReadAllText($reply) } return @{ Status = $status; Body = $body } } finally { Remove-Item -LiteralPath $reply -ErrorAction SilentlyContinue } } $stream = [System.IO.File]::OpenRead($File.FullName) try { $content = New-Object System.Net.Http.StreamContent $stream $content.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue 'application/octet-stream' $content.Headers.ContentLength = $File.Length return Invoke-Api 'PUT' $Url $content } finally { $stream.Dispose() } } # ---------- small helpers ---------- # "1.5 GB", 1024-based like the web app. function Format-Size([double]$Bytes) { $units = 'B', 'KB', 'MB', 'GB', 'TB' $i = 0 while ($Bytes -ge 1000 -and $i -lt 4) { $Bytes /= 1024; $i++ } $format = 'N1' if ($i -eq 0 -or $Bytes -ge 100) { $format = 'N0' } return $Bytes.ToString($format, [Globalization.CultureInfo]::InvariantCulture) + ' ' + $units[$i] } function ConvertFrom-Reply($Reply) { try { return $Reply.Body | ConvertFrom-Json } catch { return $null } } # Why a request failed, as a sentence. function Get-Problem($Reply) { $detail = '' $json = ConvertFrom-Reply $Reply if ($json -and $json.detail) { if ($json.detail -is [string]) { $detail = " ($($json.detail))" } elseif ($json.detail[0].msg) { $detail = " ($($json.detail[0].msg))" } } switch ($Reply.Status) { 0 { return "can't reach $Server ($($Reply.Body))" } 404 { return 'the server no longer knows this upload (it may have timed out)' } 409 { return 'the server is still handling an earlier attempt' } { $_ -in 413, 422 } { return "the server refused the files$detail" } default { return "the server answered $($Reply.Status)$detail" } } } function Test-Retryable($Reply) { return $Reply.Status -in 0, 409, 429 -or $Reply.Status -ge 500 } # ---------- 1. limits ---------- $maxFiles = 100 $maxSize = 16GB # replaced by what the server says $info = Invoke-Api 'GET' "$Server/api/info" if ($info.Status -eq 0) { Fail (Get-Problem $info) } $limits = ConvertFrom-Reply $info if ($info.Status -eq 200 -and $limits -and $limits.service -eq 'ezfileshare') { $maxFiles = [int]$limits.max_files $maxSize = [long]$limits.max_file_size } # Any other answer: an older server without /api/info. Carry on with the usual limits; # the server checks them itself anyway. # ---------- 2. check the files, before anything is sent ---------- if ($Files.Count -gt $maxFiles) { Fail "$($Files.Count) files given, but one link holds at most $maxFiles" } $items = @() foreach ($path in $Files) { if (Test-Path -LiteralPath $path -PathType Container) { Fail "$path is a folder; zip it first, or name the files in it" } if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { Fail "${path}: no such file" } $file = Get-Item -LiteralPath $path -Force if ($file.Length -gt $maxSize) { Fail "$path is $(Format-Size $file.Length); the limit is $(Format-Size $maxSize) per file" } $items += $file } # ---------- 3. announce the files ---------- $spec = @{ files = @($items | ForEach-Object { @{ name = $_.Name; size = $_.Length } }) } | ConvertTo-Json -Depth 4 -Compress $created = Invoke-Api 'POST' "$Server/api/shares" (New-Object System.Net.Http.StringContent ($spec, [Text.Encoding]::UTF8, 'application/json')) if ($created.Status -in 404, 405) { Fail "$Server doesn't look like an ezfileshare site (it answered $($created.Status))" } if ($created.Status -ne 201) { Fail "couldn't start the upload: $(Get-Problem $created)" } $share = ConvertFrom-Reply $created if (-not $share -or -not $share.id -or -not $share.token -or @($share.files).Count -ne $items.Count) { Fail "unexpected answer from $Server; is this an ezfileshare site?" } $Token = $share.token $ids = @($share.files | ForEach-Object { $_.id }) # in the order given # ---------- 4. send each file ---------- # One file, trying again after failures that may pass. function Send-File([int]$Index) { $file = $items[$Index] $label = "[$($Index + 1)/$($items.Count)] $($file.Name)" for ($try = 1; ; $try++) { Say "$label $(Format-Size $file.Length)" $reply = Send-FileBody "$Server/api/shares/$($share.id)/files/$($ids[$Index])" $file if ($reply.Status -in 200, 202) { return } if (-not (Test-Retryable $reply) -or $try -ge $Attempts) { Fail "$($file.Name): $(Get-Problem $reply)" } Say " $(Get-Problem $reply); trying again ($($try + 1) of $Attempts)" Start-Sleep -Seconds (($try + 1) * 2) } } for ($i = 0; $i -lt $items.Count; $i++) { Send-File $i } # ---------- 5. wait for the virus scan ---------- # The server scans files in the background after they arrive. A file whose scan failed on # the server's side is sent again; a file with malware ends the upload. $resent = @{} $failures = 0 $announced = $false $deadline = (Get-Date).AddSeconds($ScanWait) while ($true) { $reply = Invoke-Api 'GET' "$Server/api/shares/$($share.id)/progress" $progress = ConvertFrom-Reply $reply if ($reply.Status -eq 200 -and $progress) { $failures = 0 if ($progress.ready) { break } foreach ($state in @($progress.files)) { $index = [Array]::IndexOf($ids, $state.id) if ($index -lt 0) { continue } $name = $items[$index].Name switch ($state.status) { 'infected' { Fail "$name was blocked: malware detected. No link was created" } 'scanning' { if (-not $announced) { Say 'Checking for viruses...'; $announced = $true } } 'error' { $resent[$state.id] = 1 + [int]$resent[$state.id] if ($resent[$state.id] -ge $Attempts) { Fail "${name}: the server couldn't check the file for viruses; try again later" } Say " ${name}: the virus check failed on the server; sending it again" Send-File $index } } } } else { $failures++ if (-not (Test-Retryable $reply) -or $failures -gt 10) { Fail "couldn't confirm the upload: $(Get-Problem $reply)" } } if ((Get-Date) -gt $deadline) { Fail "the server didn't finish checking the files in time; try again later" } Start-Sleep -Seconds 1 } # ---------- 6. the link ---------- # When it expires is nice to know, but not worth failing for. $until = '' $published = ConvertFrom-Reply (Invoke-Api 'GET' "$Server/api/shares/$($share.id)") if ($published -and $published.expires_at) { $day = [DateTimeOffset]::FromUnixTimeSeconds([long]$published.expires_at).LocalDateTime $until = ', valid until ' + $day.ToString('d MMMM yyyy', [Globalization.CultureInfo]::InvariantCulture) } Say "Link ready${until}:" "$Server/s/$($share.id)" exit 0