Created
July 28, 2015 13:14
-
-
Save Kevin-Bronsdijk/57c1a87503b0a623d5f5 to your computer and use it in GitHub Desktop.
kraken-image-optimizer-and-azure-blob-storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Azure details | |
$storageAccount = "storageAccount" | |
$storageKey = "storageKey" | |
$container_name = "blob container name" | |
# Kraken details | |
$uri = "https://api.kraken.io/v1/url" | |
$api_key = "kraken api key" | |
$api_secret = "kraken api secret" | |
$content_type_supported = "image/png", "image/gif", "image/jpeg" | |
# store images and log locally | |
$local_storage = "D:\Dev\images\" | |
$local_storage_backup = ($local_storage + "backup\") | |
$logfile = ($local_storage + "kraken.log") | |
# Backup images | |
New-Item -ItemType directory -Path $local_storage_backup -Force | |
$context = New-AzureStorageContext –StorageAccountName $storageAccount -StorageAccountKey $storageKey -Protocol Http | |
Get-AzureStorageBlob -Context $context -Container $container_name | | |
ForEach-Object { | |
# Proceed if supported by Kraken | |
If ($content_type_supported -contains $_.ContentType.ToLower()) | |
{ | |
$url = $context.BlobEndPoint + $container_name + "/" + $_.Name | |
$json = " | |
{ | |
""auth"": { | |
""api_key"": ""$api_key"", | |
""api_secret"": ""$api_secret"" | |
}, | |
""url"": ""$url"", | |
""wait"": true | |
}" | |
$kraken_response = $null | |
Try | |
{ | |
$kraken_response = Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Body $json | |
} | |
Catch [system.exception] | |
{ | |
Add-content $Logfile -value ("Error processing " + $url) | |
} | |
# Only if kraken is smaller | |
if ($kraken_response -ne $null -and $kraken_response.saved_bytes -gt 0) | |
{ | |
Add-content $Logfile -value ($url + " " + $kraken_response.saved_bytes) | |
$wc = New-Object System.Net.WebClient | |
$fileName = [System.IO.Path]::GetFileName($url) | |
# Download the version created by kranen | |
$wc.DownloadFile($kraken_response.kraked_url, $local_storage + $fileName) | |
# Backup the old file, just in case | |
$wc.DownloadFile($url, $local_storage_backup + $fileName) | |
# Update Azure Blob | |
Try | |
{ | |
Set-AzureStorageBlobContent -File ($local_storage + $fileName) -Blob $_.Name -Container $container_name -Context $context -Force | |
} | |
Catch [system.exception] | |
{ | |
Add-content $Logfile -value ("Error updating " + $url) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment