├── .gitattributes ├── .gitignore ├── Img ├── FirstUpload.png └── OAuthWindow.png ├── PSImgur.psd1 ├── PSImgur.psm1 ├── Private ├── Get-DecryptedValue.ps1 ├── Get-ImgurCode.ps1 ├── Get-ImgurToken.ps1 ├── ScriptIdea.ps1 └── Show-oAuthWindow.ps1 ├── Public ├── Connect-ImgurAccount.ps1 ├── Get-ImgurAccount.ps1 ├── Get-ImgurImage.ps1 ├── New-ImgurImage.ps1 └── Test-ImgurToken.ps1 ├── README.md └── license /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | 45 | creds.txt -------------------------------------------------------------------------------- /Img/FirstUpload.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1RedOne/PSImgur/c2d7604b076b4c5bd009805fd87612791f87e289/Img/FirstUpload.png -------------------------------------------------------------------------------- /Img/OAuthWindow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1RedOne/PSImgur/c2d7604b076b4c5bd009805fd87612791f87e289/Img/OAuthWindow.png -------------------------------------------------------------------------------- /PSImgur.psd1: -------------------------------------------------------------------------------- 1 | # 2 | # Module manifest for module 'PSImgur' 3 | # 4 | # Generated by: FoxDeploy 5 | # 6 | # Generated on: 9/10/2015 7 | # 8 | 9 | @{ 10 | 11 | # Script module or binary module file associated with this manifest. 12 | RootModule = 'PSImgur.psm1' 13 | 14 | # Version number of this module. 15 | ModuleVersion = '0.0.1' 16 | 17 | # ID used to uniquely identify this module 18 | GUID = '2cc850b4-4052-4766-941c-49d6c042051b' 19 | 20 | # Author of this module 21 | Author = 'Rob McCoy, FoxDeploy' 22 | 23 | # Company or vendor of this module 24 | #CompanyName = 'Unknown' 25 | 26 | # Copyright statement for this module 27 | Copyright = '(c) 2015 FoxDeploy. All rights reserved.' 28 | 29 | # Description of the functionality provided by this module 30 | Description = 'PowerShell module to query the Imgur API' 31 | 32 | # Minimum version of the Windows PowerShell engine required by this module 33 | PowerShellVersion = '3.0' 34 | 35 | # Name of the Windows PowerShell host required by this module 36 | # PowerShellHostName = '' 37 | 38 | # Minimum version of the Windows PowerShell host required by this module 39 | # PowerShellHostVersion = '' 40 | 41 | # Minimum version of Microsoft .NET Framework required by this module 42 | # DotNetFrameworkVersion = '' 43 | 44 | # Minimum version of the common language runtime (CLR) required by this module 45 | # CLRVersion = '' 46 | 47 | # Processor architecture (None, X86, Amd64) required by this module 48 | # ProcessorArchitecture = '' 49 | 50 | # Modules that must be imported into the global environment prior to importing this module 51 | # RequiredModules = @() 52 | 53 | # Assemblies that must be loaded prior to importing this module 54 | # RequiredAssemblies = @() 55 | 56 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 57 | # ScriptsToProcess = @() 58 | 59 | # Type files (.ps1xml) to be loaded when importing this module 60 | # TypesToProcess = @() 61 | 62 | # Format files (.ps1xml) to be loaded when importing this module 63 | # FormatsToProcess = 'PSStackExchange.Format.ps1xml' 64 | 65 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 66 | # NestedModules = @() 67 | 68 | # Functions to export from this module 69 | FunctionsToExport = '*' 70 | 71 | # Cmdlets to export from this module 72 | CmdletsToExport = '*' 73 | 74 | # Variables to export from this module 75 | VariablesToExport = '*' 76 | 77 | # Aliases to export from this module 78 | AliasesToExport = '*' 79 | 80 | # DSC resources to export from this module 81 | # DscResourcesToExport = @() 82 | 83 | # List of all modules packaged with this module 84 | # ModuleList = @() 85 | 86 | # List of all files packaged with this module 87 | # FileList = @() 88 | 89 | # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. 90 | PrivateData = @{ 91 | 92 | PSData = @{ 93 | 94 | # Tags applied to this module. These help with module discovery in online galleries. 95 | # Tags = @() 96 | 97 | # A URL to the license for this module. 98 | # LicenseUri = '' 99 | 100 | # A URL to the main website for this project. 101 | # ProjectUri = '' 102 | 103 | # A URL to an icon representing this module. 104 | # IconUri = '' 105 | 106 | # ReleaseNotes of this module 107 | # ReleaseNotes = '' 108 | 109 | } # End of PSData hashtable 110 | 111 | } # End of PrivateData hashtable 112 | 113 | # HelpInfo URI of this module 114 | # HelpInfoURI = '' 115 | 116 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 117 | # DefaultCommandPrefix = '' 118 | 119 | } 120 | 121 | -------------------------------------------------------------------------------- /PSImgur.psm1: -------------------------------------------------------------------------------- 1 | #Get public and private function definition files. 2 | $PublicFunction = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -Exclude *tests* -ErrorAction SilentlyContinue ) 3 | $PrivateFunction = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -Exclude *tests* -ErrorAction SilentlyContinue ) 4 | 5 | #Dot source the files 6 | Foreach($import in @($PublicFunction + $PrivateFunction)) 7 | { 8 | "importing $import" 9 | Try 10 | { 11 | . $import.fullname 12 | } 13 | Catch 14 | { 15 | Write-Error -Message "Failed to import function $($import.fullname): $_" 16 | } 17 | } 18 | 19 | # Here I might... 20 | # Read in or create an initial config file and variable 21 | # Export Public functions ($Public.BaseName) for WIP modules 22 | # Set variables visible to the module and its functions only 23 | 24 | #Initialize our variables. I know, I know... 25 | 26 | $configDir = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config.ps1xml" 27 | $confusername = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config_username.ps1xml" 28 | if (Test-Path $configDir){ 29 | Write-Verbose "Cached Credential found, importing" 30 | 31 | Try 32 | { 33 | #Import the config 34 | $password = Import-Clixml -Path $configDir -ErrorAction STOP | ConvertTo-SecureString 35 | $username = Import-Clixml -Path $confusername -ErrorAction STOP | ConvertTo-SecureString 36 | 37 | } 38 | catch { 39 | Write-Warning "Corrupt Password file found, rerun with -Force to fix this" 40 | } 41 | 42 | 43 | if ($password){Get-DecryptedValue -inputObj $password -name Imgur_accessToken} 44 | if ($username){Get-DecryptedValue -inputObj $username -name Imgur_username} 45 | } 46 | else{ 47 | Write-Output "Run Connect-ImgurAccount to begin" 48 | } 49 | 50 | 51 | Export-ModuleMember -Function $PublicFunction.Basename -------------------------------------------------------------------------------- /Private/Get-DecryptedValue.ps1: -------------------------------------------------------------------------------- 1 | Function Get-DecryptedValue{ 2 | param($inputObj,$name) 3 | 4 | $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($inputObj) 5 | $result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr) 6 | [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr) 7 | New-Variable -Scope Global -Name $name -Value $result -PassThru -Force 8 | 9 | } -------------------------------------------------------------------------------- /Private/Get-ImgurCode.ps1: -------------------------------------------------------------------------------- 1 | #this function calls the authorize API, using the Show-oAuthWindow to show a, uh, window for the user to login to 2 | Function Get-ImgurAuthCode{ 3 | param($ClientID,$ResponseType) 4 | 5 | $url = "https://api.imgur.com/oauth2/authorize?client_id=$clientID&response_type=$ResponseType" 6 | 7 | If($ClientID -eq $null){ 8 | Write-warning "Must provide the `-ClientID of your Imgur App to display a login Window" 9 | break} 10 | 11 | Show-OAuthWindow -url $url 12 | 13 | #After this, there should be a variable called $uri, which has our code!!!!!!!!!!! 14 | #(?<=code=)(.*)(?=&) 15 | $regex = '(?<=code=)(.*)' 16 | try {$authCode = ($uri | Select-string -pattern $regex -ErrorAction STOP).Matches[0].Value} 17 | catch{"didn't get a code, trying again" 18 | Show-OAuthWindow -url $url } 19 | "new auth code $authCode" 20 | $global:authCode = $authCode 21 | Write-output "Received an authCode, $authcode" 22 | } 23 | #Next, get an access token by presenting the code -------------------------------------------------------------------------------- /Private/Get-ImgurToken.ps1: -------------------------------------------------------------------------------- 1 | Function Get-ImgurAuthToken{ 2 | [CmdletBinding()] 3 | param($ClientID,$clientSecret,$authCode) 4 | #params 5 | $tokenURL = 'https://api.imgur.com/oauth2/token' 6 | #The money shot, this will have our token that we'll use 7 | try { 8 | $result = Invoke-RestMethod $tokenURL -Method Post ` 9 | -Body @{client_id=$clientId; 10 | client_secret=$clientSecret; 11 | grant_type="authorization_code"; 12 | code=$authCode} ` 13 | -ContentType "application/x-www-form-urlencoded" -ErrorAction STOP 14 | } 15 | catch{ 16 | Write-Warning "Something didn't work" 17 | Write-debug "Test the -body params for the Rest command" 18 | } 19 | 20 | Write-Debug 'go through the results of $result, looking for our token' 21 | if ($result.access_token){ 22 | Write-Output "Updated Authorization Token" 23 | $result 24 | $global:imgur_accessToken = $result.access_token 25 | $global:imgur_refreshToken = $result.refresh_token 26 | $global:imgur_username = $result.account_username 27 | 28 | } 29 | 30 | } 31 | 32 | <#refresh tokens, not implemented yet 33 | 34 | $result = Invoke-RestMethod $tokenURL -Method Post ` 35 | -Body @{ 36 | refresh_token = $Imgur_refreshtoken; 37 | client_id=$clientId; 38 | client_secret=$clientSecret; 39 | grant_type="refresh_token"; 40 | } -ContentType "application/x-www-form-urlencoded" -ErrorAction STOP 41 | 42 | #> -------------------------------------------------------------------------------- /Private/ScriptIdea.ps1: -------------------------------------------------------------------------------- 1 | For (;;){ 2 | $files = dir c:\CheerPhotos\ -Recurse *.png,*.jpg 3 | ForEach ($thisfile in $files){ 4 | if ($thisfile.Name -in (import-csv .\Status.csv){ 5 | Write-output "already uploaded, skipping $($thisfile.Name)" 6 | } 7 | else{ 8 | #File wasn't uploaded yet, let's upload 9 | #try this command and see if it errors. If not, we'll have the filename and status, stored in $status 10 | try {$status = New-ImgurImage -filepath $thisfile.FullName -ErrorAction Stop | select FileName,Status} 11 | #if the above command errored, run this instead. In this case, we'll make an object called status, with the file name and the word 'Failed' for status 12 | catch{$status = [pscustomobject]@{FileName=$thisFile.Name;Status="Failed"}} 13 | #whether it errored or not, track this file in the csv 14 | finally{$status | convertto-csv -NoTypeInformation | Export-Csv -Append .\Status.csv} 15 | 16 | } 17 | 18 | #EndofThisFile 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /Private/Show-oAuthWindow.ps1: -------------------------------------------------------------------------------- 1 |  #region mini window, made by (Insert credits here) 2 | Function Show-OAuthWindow { 3 | param($url) 4 | Add-Type -AssemblyName System.Windows.Forms 5 | 6 | $form = New-Object -TypeName System.Windows.Forms.Form -Property @{Width=440;Height=640} 7 | $web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{Width=420;Height=600;Url=($url -f ($Scope -join "%20")) } 8 | $DocComp = { 9 | $Global:uri = $web.Url.AbsoluteUri 10 | if ($Global:Uri -match "error=[^&]*|code=[^&]*") {$form.Close() } 11 | } 12 | $web.ScriptErrorsSuppressed = $true 13 | $web.Add_DocumentCompleted($DocComp) 14 | $form.Controls.Add($web) 15 | $form.Add_Shown({$form.Activate()}) 16 | $form.ShowDialog() | Out-Null 17 | } 18 | #endregion 19 | 20 | #login to get an access code -------------------------------------------------------------------------------- /Public/Connect-ImgurAccount.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Use this cmdlet to connect to a Imgur account for management via PowerShell 4 | .DESCRIPTION 5 | With one cmdlet, you can connect to your Imgur account via the REST API. After using this cmdlet, you can use any of the other *Imgur cmdlets to do things like upload an image or an album, etc (to come later) 6 | .EXAMPLE 7 | Connect-ImgurAccount -ClientID [String] -ClientSecret [ClientSecret] 8 | 9 | Sign up at http://api.imgur.com/oauth2/addclient and make a new application ID, which is needed to query to Imgur API. While you're there, specify a redirect URL, which should be the URL of any random site. You'll receive a ClientID, ClientSecret which you must provide to this cmdlet. 10 | 11 | Upon running, a Internet Explorer com object window will be displayed, prompting you to login and authorize your Application ID (PowerShell, effectively) to interact with your Imgur account. Click the appropriate boxes, and then close the browser window when you see the window get redirected. 12 | 13 | Behind the scenes, this cmdlet will retrieve an Access Token, convert it to an Authorization Token, and store it safely within your profile. Other PSImgur API calls require this Authorization token, and it will be automatically provided when needed. 14 | .EXAMPLE 15 | Connect-ImgurAccount -Force 16 | 17 | If you need to renew your API key (roughly once a month), then rerun the cmdlet with -Force 18 | #> 19 | Function Connect-ImgurAccount { 20 | [CmdletBinding()] 21 | param($ClientID,$clientSecret,[Switch]$force) 22 | 23 | #load private functions 24 | $PrivateFunctions = get-childitem "$((Get-Module PSImgur).ModuleBase)\Private" 25 | 26 | Foreach ($import in $PrivateFunctions) 27 | { 28 | Try 29 | { 30 | . $import.fullname 31 | } 32 | Catch 33 | { 34 | Write-Error -Message "Failed to import function $($import.fullname): $_" 35 | } 36 | } 37 | 38 | 39 | $configDir = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config.ps1xml" 40 | $confusername = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config_username.ps1xml" 41 | $ConfRefresh = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config_refresh.ps1xml" 42 | if (-not (Test-Path $configDir) -or $force){ 43 | if ($force){"`$force detected"} 44 | New-item -Force -Path "$configDir" -ItemType File 45 | 46 | #response type must be code 47 | Get-ImgurCode -ClientID $ClientID -ResponseType code 48 | 49 | Get-ImgurToken -ClientID $ClientID -clientSecret $clientSecret -authCode $authCode 50 | 51 | #store the token and the username, securely 52 | $password = ConvertTo-SecureString $imgur_accessToken -AsPlainText -Force 53 | $password | ConvertFrom-SecureString | Export-Clixml $configDir -Force 54 | 55 | $username = ConvertTo-SecureString $imgur_username -AsPlainText -Force 56 | $username | ConvertFrom-SecureString | Export-Clixml $Confusername -Force 57 | 58 | $refreshtkn = ConvertTo-SecureString $imgur_refreshToken -AsPlainText -Force 59 | $refreshtkn | ConvertFrom-SecureString | Export-Clixml $ConfRefresh -Force 60 | 61 | } 62 | else{ 63 | 64 | try { 65 | $password = Import-Clixml -Path $configDir -ErrorAction STOP | ConvertTo-SecureString 66 | $imgur_username = Import-Clixml -Path $Confusername -ErrorAction STOP | ConvertTo-SecureString 67 | $imgur_refreshToken = Import-Clixml -Path $ConfRefresh -ErrorAction STOP | ConvertTo-SecureString 68 | } 69 | catch { 70 | Write-Warning "Corrupt Password file found, rerun with -Force to fix this" 71 | BREAK 72 | } 73 | #$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password) 74 | #$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr) 75 | #[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr) 76 | #$global:imgur_accessToken = $result 77 | 'Found cached Cred' 78 | 79 | Get-DecryptedValue -inputObj $password -name Imgur_accessToken 80 | Get-DecryptedValue -inputObj $username -name Imgur_username 81 | Get-DecryptedValue -inputObj $imgur_refreshToken -name Imgur_refreshtoken 82 | 83 | Test-ImgurToken 84 | 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /Public/Get-ImgurAccount.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Gets information about the currently logged in user 4 | .Description 5 | After you've connected using Connect-ImgurAccount, you can use this cmdlet to get information about the currently logged in user 6 | .PARAMETER username 7 | Required. Specifies which username profile you'd like to look at 8 | .PARAMETER accesstoken 9 | Optional. Defaults to the current user imported with Connect-ImgurAccount. If instead, you'd like to view a different user and have their access token, use this param. 10 | .SWITCH favorites 11 | Optional. Specifies to return a list of user's favorite'd images 12 | .Example 13 | Get-ImgurAccount -favorites 14 | 15 | 16 | Title : Phone flop 17 | Link : http://i.imgur.com/gsWiMw3h.gif 18 | Bandwidth(mb) : 34820664 19 | Created : 10/14/2015 2:15:59 AM 20 | views : 597229 21 | Upvotes : 7522 22 | Downvotes : 114 23 | 24 | 25 | Title : This jerkface just pooped on a chihuahua at the petstore. She's not even sorry. 26 | Link : http://i.imgur.com/pQWtGJs.jpg 27 | Bandwidth(mb) : 10226 28 | Created : 10/14/2015 12:26:43 AM 29 | views : 233445 30 | Upvotes : 3913 31 | Downvotes : 121 32 | 33 | To see a listing of all of your favorites, specify the -Favorites Switch 34 | .Example 35 | Get-ImgurAccount 36 | 37 | UserName Reputation Created Expiration 38 | -------- ---------- ------- ---------- 39 | FoxDeploy 0 10/13/2015 1:34:40 PM False 40 | 41 | See various information about your account. 42 | .LINK 43 | https://github.com/1RedOne/PSImgur 44 | #> 45 | Function Get-ImgurAccount { 46 | [CmdletBinding()] 47 | Param($accessToken=$Global:imgur_accessToken, 48 | $username=$Global:imgur_username, 49 | [switch]$favorites, 50 | [switch]$uploads) 51 | write-verbose @{"Authorization" = "Bearer $accessToken"} 52 | if ($favorites){ 53 | try {$result = Invoke-RestMethod https://api.imgur.com/3/account/$username/favorites -Method Get -Headers @{"Authorization" = "Bearer $accessToken"}} 54 | catch{throw "Check Credentials, error 400";break} 55 | 56 | #convert epoch time to normal human time 57 | $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 58 | 59 | ForEach ($result in $result.data){ 60 | $created = $origin.AddSeconds($result.datetime) 61 | [pscustomobject]@{Title=$result.title;Link=$result.link;'Bandwidth(mb)'=$result.bandwidth / 1mb -as [int];Created=$created;views=$result.views;Upvotes=$result.ups;Downvotes=$result.downs} 62 | 63 | break 64 | } 65 | 66 | } 67 | try {$result = Invoke-RestMethod https://api.imgur.com/3/account/$username -Method Get -Headers @{"Authorization" = "Bearer $accessToken"}} 68 | catch{throw "Check Credentials, error 400";break} 69 | 70 | #convert epoch time to normal human time 71 | $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 72 | $created = $origin.AddSeconds($result.data.created) 73 | 74 | [pscustomobject]@{UserName=$result.data.url;Reputation=$result.data.reputation;Created=$created;Expiration=$result.data.pro_expiration} 75 | 76 | 77 | Write-Debug "Test results" 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /Public/Get-ImgurImage.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | View information about images you've uploaded on Imgur using this cmdlet 4 | .Description 5 | After you've connected using Connect-ImgurAccount, you can use this cmdlet to review all of your images 6 | .Example 7 | Get-ImgurImage 8 | 9 | Title : My first Image Upload 10 | Link : http://i.imgur.com/CpuHZtX.jpg 11 | Bandwidth(kb) : 484 12 | Created : 1/1/1970 12:00:00 AM 13 | views : 2 14 | Upvotes : 15 | Downvotes : 16 | Width : 900 17 | Height : 598 18 | Size : 247657 19 | description : This image was uploaded using PowerShell! 20 | 21 | Simply specify the name of an image to directly upload from your PC to Imgur 22 | .LINK 23 | https://github.com/1RedOne/PSImgur 24 | #> 25 | Function Get-ImgurImage { 26 | [CmdletBinding()] 27 | Param($accessToken=$Global:imgur_accessToken 28 | ) 29 | #for testing headers 30 | write-verbose @{"Authorization" = "Bearer $accessToken"} 31 | 32 | 33 | try {$result = Invoke-RestMethod https://api.imgur.com/3/account/$username/images -Method Get -Headers @{"Authorization" = "Bearer $accessToken"} -ErrorAction Stop} 34 | catch{write-debug "Check Credentials, error 400"} 35 | 36 | 37 | if ($result.status -eq 200){ 38 | write-host -ForegroundColor Green "SUCCESS!" 39 | } 40 | 41 | #convert epoch time to normal human time 42 | $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 43 | 44 | ForEach ($image in $result.data){ 45 | $created = $origin.AddSeconds($result.datetime) 46 | [pscustomobject]@{Title=$image.title; 47 | Link=$image.link; 48 | 'Bandwidth(kb)'=$image.bandwidth / 1kb -as [int]; 49 | Created=$created; 50 | views=$image.views; 51 | Upvotes=$image.ups; 52 | Downvotes=$image.downs 53 | Width=$image.width; 54 | Height=$image.height; 55 | Size=$image.size; 56 | description=$image.description} 57 | } 58 | 59 | Write-Debug "Test results" 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /Public/New-ImgurImage.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Upload an image to imgur using this one simple cmdlet 4 | .Description 5 | After you've connected using Connect-ImgurAccount, you can use this cmdlet to push an image up to imgur 6 | .PARAMETER filepath 7 | Required. Specifies the filepath of the image you're uploading 8 | .PARAMETER title 9 | Optional. The title, as you'd like it to appear on imgur 10 | .PARAMETER name 11 | Optional. The name, as you'd like it to appear on imgur 12 | .PARAMETER description 13 | Optional. Specifies an optional description of an image. 14 | .PARAMETER album 15 | Optional. The **album ID** of an album to upload to. 16 | .Example 17 | New-ImgurImage -filepath C:\temp\fox1.jpg -name "FoxDeploy" -title "My first Image Upload" -description "This image was uploaded using PowerShell!" 18 | SUCCESS! 19 | 20 | Title : My first Image Upload 21 | Width : 900 22 | Height : 598 23 | Size : 247657 24 | Created : 10/14/2015 7:42:06 PM 25 | URL : http://i.imgur.com/CpuHZtX.jpg 26 | description : This image was uploaded using PowerShell! 27 | 28 | Simply specify the name of an image to directly upload from your PC to Imgur 29 | .Example 30 | New-ImgurAccount -filepath C:\temp\fox2.jpg 31 | 32 | SUCCESS! 33 | 34 | 35 | Title : 36 | Width : 900 37 | Height : 678 38 | Size : 156373 39 | Created : 10/14/2015 7:47:05 PM 40 | URL : http://i.imgur.com/jid8uHI.jpg 41 | description : 42 | 43 | This shows how little info you need to push an image. Just put in the file path and you're done! 44 | .LINK 45 | https://github.com/1RedOne/PSImgur 46 | #> 47 | Function New-ImgurImage { 48 | [CmdletBinding()] 49 | Param($accessToken=$Global:imgur_accessToken, 50 | [Parameter(Mandatory=$true)]$filepath, 51 | $album,$name,$title,$description 52 | ) 53 | #for testing headers 54 | If ($VerbosePreference){ @{"Authorization" = "Bearer $accessToken"} } 55 | 56 | #trying a new, faster way to base64 compress 57 | $time = measure-command -expression {$image = [convert]::ToBase64String([System.IO.File]::ReadAllBytes((get-item $filepath).FullName))} 58 | 59 | Write-Verbose "file encode completed in $($time.Milliseconds) milliseconds" 60 | 61 | #old way of encoding, super duper slow. 62 | #$image = [convert]::ToBase64String((get-content $filepath -encoding byte)) 63 | 64 | #for legacy sake, this didn't work 65 | #$image = (get-content $filepath -encoding byte) 66 | 67 | #imgur wants a hashtable of values, most are optional though, so we'll build a hashtable to send 68 | $body=@{image=$image} 69 | 70 | if ($album){ 71 | $body.Add('album',$album) 72 | } 73 | if ($name){ 74 | $body.Add('name',$name) 75 | } 76 | if ($title){ 77 | $body.Add('title',$title) 78 | } 79 | if ($description){ 80 | $body.Add('description',$description) 81 | } 82 | 83 | try {$result = Invoke-RestMethod -uri https://api.imgur.com/3/image.json ` 84 | -Method Post -Headers @{"Authorization" = "Bearer $accessToken"} ` 85 | -Body $body -UseBasicParsing -ErrorAction Stop} 86 | catch{write-debug "Check Credentials, error 400"} 87 | #finally{ 88 | write-debug "test" 89 | #convert epoch time to normal human time 90 | #$origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 91 | #$created = $origin.AddSeconds($result.data.created) 92 | #parse the result here 93 | #[pscustomobject]@{UserName=$result.data.url;Reputation=$result.data.reputation;Created=$created;Expiration=$result.data.pro_expiration} 94 | 95 | # } 96 | if ($result.status -eq 200){ 97 | write-host -ForegroundColor Green "SUCCESS!" 98 | } 99 | 100 | $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 101 | $created = $origin.AddSeconds($result.data.datetime) 102 | 103 | [pscustomobject]@{Title=$result.data.title; 104 | Width=$result.data.width; 105 | Height=$result.data.height; 106 | Size=$result.data.size; 107 | Created=$created; 108 | URL=$result.data.link; 109 | description=$result.data.description; 110 | status='Success'} 111 | 112 | Write-Debug "Test results" 113 | 114 | 115 | } 116 | -------------------------------------------------------------------------------- /Public/Test-ImgurToken.ps1: -------------------------------------------------------------------------------- 1 | Function Test-ImgurToken{ 2 | [CmdletBinding()] 3 | param($ClientID,$clientSecret,$authCode) 4 | #URL to use, and place to store credentials 5 | $tokenURL = 'https://api.imgur.com/oauth2/token' 6 | $configDir = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config.ps1xml" 7 | $confusername = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config_username.ps1xml" 8 | $ConfRefresh = "$Env:AppData\WindowsPowerShell\Modules\PSImgur\0.1\Config_refresh.ps1xml" 9 | 10 | #verify that the keys work 11 | try {$success = Get-ImgurAccount -ErrorAction Stop} 12 | catch {Write-warning "Token expired, trying to refresh" 13 | Invoke-RestMethod -Uri $tokenURL -Method Post ` 14 | -Body @{ 15 | refresh_token = $Imgur_refreshtoken; 16 | client_id=$clientId; 17 | client_secret=$clientSecret; 18 | grant_type="refresh_token"; 19 | } -ContentType "application/x-www-form-urlencoded" -ErrorAction STOP | tee -Variable result 20 | 21 | Write-Debug 'go through the results of $result, looking for our token' 22 | if ($result.access_token){ 23 | Write-Output "Updated Authorization Token" 24 | #result 25 | $global:imgur_accessToken = $result.access_token 26 | $global:imgur_refreshToken = $result.refresh_token 27 | $global:imgur_username = $result.account_username 28 | 29 | #store the token and the username, securely 30 | $password = ConvertTo-SecureString $imgur_accessToken -AsPlainText -Force 31 | $password | ConvertFrom-SecureString | Export-Clixml $configDir -Force 32 | 33 | $username = ConvertTo-SecureString $imgur_username -AsPlainText -Force 34 | $username | ConvertFrom-SecureString | Export-Clixml $Confusername -Force 35 | 36 | $refreshtkn = ConvertTo-SecureString $imgur_refreshToken -AsPlainText -Force 37 | $refreshtkn | ConvertFrom-SecureString | Export-Clixml $ConfRefresh -Force 38 | #End Update Tokens 39 | } 40 | else{ 41 | Write-Warning "Couldn't update tokens, try Connect-ImgurAccount -Force" 42 | } 43 | 44 | #End Catch 45 | } 46 | 47 | 48 | 49 | if ($success -ne $null){Write-Host -ForegroundColor Green "Token good"} 50 | #Eof 51 | } 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PSImgur v0.1 2 | A PowerShell Module for working with Imgur via the REST API 3 | 4 | This module makes it easy to connect to your Imgur account. 5 | 6 | ####Exposed Cmdlets 7 | 8 | * Connect-ImgurAccount 9 | * Get-ImgurAccount 10 | * Get-ImgurImage 11 | * New-ImgurImage 12 | 13 | ####Planned cmdlets or features 14 | 15 | Name | Planned Version | Delivered? 16 | ------------- | ------------- | --- 17 | Connect/Get-ImgurAccount | v0.beta | YES! 18 | New-ImgurImage | v0.1 | YES! 19 | Get-ImgurAlbum | v0.2 | ? 20 | New-ImgurAlbum | v0.2 | ? 21 | Remove-ImgurAccount | v0.3 | ? 22 | Automatically update tokens | v0.2 | ? 23 | ? | v0.? | ? 24 | 25 | ![alt tag](https://github.com/1RedOne/PSImgur/blob/master/Img/OAuthWindow.png) 26 | 27 | ### How to use 28 | 29 | * Create a [project on Imgur](https://api.imgur.com/oauth2/addclient) 30 | * Clone this Repo 31 | * Import the module 32 | ```PowerShell 33 | Import-Module PSImgur 34 | ``` 35 | * Use Connect-ImgurAccount to authenticate, and retrieve an Access Token. 36 | ```PowerShell 37 | Connect-ImgurAccount -ClientID [your app id] -ClientSecret [your client secret] 38 | >Returns $Global:AccessToken, automatically passed to all subsequnet cmdlets 39 | ``` 40 | * The accessToken is safely stored using Windows API storage, in the users own roaming app data. Subsequent cmdlets are aware of this storage location and will retrieve the key for you. 41 | * You can test your Credential using Get-ImgurAccount 42 | ```PowerShell 43 | PS C:\git\PSImgur> Get-ImgurAccount -username FoxDeploy 44 | 45 | UserName Reputation Created Expiration 46 | -------- ---------- ------- ---------- 47 | FoxDeploy 0 10/13/2015 1:34:40 PM False 48 | ``` 49 | 50 | ```PowerShell 51 | New-ImgurImage -filepath C:\temp\fox1.jpg -name "FoxDeploy" -title "My first Image Upload" -description "This image was uploaded using PowerShell!" 52 | SUCCESS! 53 | 54 | Title : My first Image Upload 55 | Width : 900 56 | Height : 598 57 | Size : 247657 58 | Created : 10/14/2015 7:42:06 PM 59 | URL : http://i.imgur.com/CpuHZtX.jpg 60 | description : This image was uploaded using PowerShell! 61 | ``` 62 | ![alt tag](https://github.com/1RedOne/PSImgur/blob/master/Img/FirstUpload.png) 63 | 64 | ###Whats next? 65 | 66 | * Get-ImgurAlbum - to see albums our token has access to 67 | * New-ImgurAlbum - to make a new album 68 | * Remove-ImgurAccount - to make it easy to remove credentials and readd them 69 | * Multi account support - uh, sure, maybe we can do this too! 70 | * Automatically update tokens | v0.2 | ? 71 | * Find [useful looking API endpoints](http://api.imgur.com/endpoints) and write wrappers for using them, using Get-ImgurAccount as an example. 72 | Automate the creation of albums. Automate the mirroring of image resources from other sites. Automate everything! 73 | 74 | ####Known issues 75 | 76 | Currently, we don't have a working refresh token process. We're saving the refresh token, but not doing anything with it. In a future verson, we should fix this. 77 | 78 | ###Change log 79 | v0.1 New-ImgurImage upload works! 80 | In a first for me, finally figured out how to upload files using Invoke-WebRequest. Awww yeessss! 81 | 82 | v0.beta Connect-ImgurAccount and Get-ImgurAccount both working 83 | 84 | Use Connect-ImgurAccount to connect to your account, you must provide your client secret and client ID. 85 | use Get-ImgurAccount to verify that you're able to see account data 86 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------