Skip to content

Instantly share code, notes, and snippets.

@Toyz
Last active October 12, 2022 18:43
Show Gist options
  • Save Toyz/74859ac6ba9dc0c61356a1d5670a2dfd to your computer and use it in GitHub Desktop.
Save Toyz/74859ac6ba9dc0c61356a1d5670a2dfd to your computer and use it in GitHub Desktop.
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param (
[Parameter(Mandatory, HelpMessage = "Search term to use")]
[string]$query = "@Silriti",
[Parameter(HelpMessage = "100/110/111/etc (sfw/sketchy/nsfw)")]
[string]$purity = "110",
[Parameter(HelpMessage = "100/101/111/etc (general/anime/people)")]
[string]$categories = "010",
[Parameter(HelpMessage = "APIKey")]
[string]$apikey = $env:WALLHAVEN_API_KEY,
[Parameter(HelpMessage = "Wallpaper directory")]
[string]$output = $env:WALLPAPER_DIR ?? [System.IO.Path]::Combine($env:USERPROFILE, "Pictures", "Wallpapers")
)
# clean query to be folder name
function clearQueryName($query) {
$query = $query -replace "@", ""
$query = $query -replace " ", "_"
return $query
}
function getJsonFromPage($page) {
$url = "https://wallhaven.cc/api/v1/search?q=$query&purity=$purity&categories=$categories&page=$page"
# check for api key env variable
if ($apikey) {
$url = $url + "&apikey=$apikey"
}
try {
$json = Invoke-WebRequest -Uri $url
$json = $json.Content | ConvertFrom-Json
return $json
}
catch {
# check if too many requests
if ($_.Exception.Response.StatusCode -eq 429) {
$retryAfter = 10
Write-Host "Too many requests, retry after $retryAfter seconds for page $page"
Start-Sleep $retryAfter
return getJsonFromPage $page
}
}
}
# create output folder
$cleanQuery = clearQueryName($query)
$folder = [System.IO.Path]::Combine($output, $cleanQuery)
if (!(Test-Path $folder)) {
New-Item -ItemType Directory -Path $folder
}
$firstPage = getJsonFromPage(1)
$lastPage = $firstPage.meta.last_page
for ($i = 1; $i -le $lastPage; $i++) {
$json = getJsonFromPage($i)
if ($null -eq $json) {
continue
}
$images = $json.data
for ($j = 0; $j -lt $images.Count; $j++) {
$image = $images[$j]
$url = $image.path
$fileName = $url.Split("/")[-1]
$filePath = [System.IO.Path]::Combine($folder, $fileName)
if (!(Test-Path $filePath)) {
$ProgressPreference = 'SilentlyContinue' # hide progress bar
Invoke-WebRequest -Uri $url -OutFile $filePath
Write-Host "Downloaded $filepath from $url"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment