Skip to content

Commit

Permalink
Connect-RedditAccount now works!
Browse files Browse the repository at this point in the history
Your session will be automatically recovered when the module is
imported, sweet!

Get-RedditAccount also works as well
  • Loading branch information
1RedOne committed Sep 16, 2015
1 parent f18d808 commit e7a55eb
Show file tree
Hide file tree
Showing 13 changed files with 295 additions and 6 deletions.
38 changes: 38 additions & 0 deletions PSReddit.format.ps1xml
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,43 @@
</TableRowEntries>
</TableControl>
</View>
<View>
<Name>PSReddit.User</Name>
<ViewSelectedBy>
<TypeName>PSReddit.User</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Width>7</Width>
</TableColumnHeader>
<TableColumnHeader>
<Width>18</Width>
</TableColumnHeader>
<TableColumnHeader>
<Width>5</Width>
</TableColumnHeader>
<TableColumnHeader/>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>created</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>comment_karma</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>link_karma</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
25 changes: 24 additions & 1 deletion PSReddit.psm1
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
[CmdletBinding()]
#Get public and private function definition files.
$PublicFunction = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -Exclude *tests* -ErrorAction SilentlyContinue )
$PrivateFunction = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -Exclude *tests* -ErrorAction SilentlyContinue )

#Dot source the files
Foreach($import in @($PublicFunction + $PrivateFunction))
{
"importing $import"
write-verbose "importing $import"
Try
{
. $import.fullname
Expand All @@ -16,6 +17,28 @@
}
}

#Initialize our variables. I know, I know...

$configDir = "$Env:AppData\WindowsPowerShell\Modules\PSReddit\0.1\Config.ps1xml"
$refreshToken = "$Env:AppData\WindowsPowerShell\Modules\PSReddit\0.1\Config.Refresh.ps1xml"


Try
{
#Import the config
$password = Import-Clixml -Path $configDir -ErrorAction STOP | ConvertTo-SecureString
$refreshToken = Import-Clixml -Path $refreshToken -ErrorAction STOP | ConvertTo-SecureString
}
catch {
Write-Warning "Corrupt Password file found, rerun with -Force to fix this"
BREAK
}

Get-DecryptedValue -inputObj $password -name PSReddit_accessToken
Get-DecryptedValue -inputObj $refreshToken -name PSReddit_refreshToken



# Here I might...
# Read in or create an initial config file and variable
# Export Public functions ($Public.BaseName) for WIP modules
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
9 changes: 9 additions & 0 deletions Private/Get-DecryptedValue.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Function Get-DecryptedValue{
param($inputObj,$name)

$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($inputObj)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
New-Variable -Scope Global -Name $name -Value $result -PassThru -Force

}
7 changes: 5 additions & 2 deletions Private/Show-oAuthWindow.ps1
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
#region mini window, made by (Insert credits here)
Function Show-OAuthWindow {
param($url)
Add-Type -AssemblyName System.Windows.Forms

$form = New-Object -TypeName System.Windows.Forms.Form -Property @{Width=440;Height=640}
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{Width=420;Height=600;Url=($url -f ($Scope -join "%20")) }
$form = New-Object -TypeName System.Windows.Forms.Form -Property @{Width=820;Height=920}
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{Width=800;Height=900;Url=($url -f ($Scope -join "%20")) }
$DocComp = {
$Global:uri = $web.Url.AbsoluteUri
if ($Global:Uri -match "error=[^&]*|code=[^&]*") {$form.Close() }
}

$web.ScrollBarsEnabled = $false
$web.ScriptErrorsSuppressed = $true
$web.Add_DocumentCompleted($DocComp)
$form.Controls.Add($web)
Expand Down
89 changes: 88 additions & 1 deletion Public/Connect-RedditAccount.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,92 @@
Function Connect-RedditAccount {
param($ClientSecret)
[CmdletBinding()]
param(
$ClientSecret,
$ClientID,
$redirectURI,
[Switch]$force)

$configDir = "$Env:AppData\WindowsPowerShell\Modules\PSReddit\0.1\Config.ps1xml"
$refreshToken = "$Env:AppData\WindowsPowerShell\Modules\PSReddit\0.1\Config.Refresh.ps1xml"
#look for a stored password


if (-not (Test-Path $configDir) -or $force){
if ($force){Write-verbose "`$force detected"}
#create the file to store our Access Token
Write-Verbose "cached Access Code not found, or the user instructed us to refresh"

if (-not (Test-Path $refreshToken)){New-item -Force -Path $refreshToken -ItemType file }
New-item -Force -Path "$configDir" -ItemType File

$guid = [guid]::NewGuid()
$URL = "https://www.reddit.com/api/v1/authorize?client_id=$clientID&response_type=code&state=$GUID&redirect_uri=$redirectURI&duration=permanent&scope=identity,history,mysubreddits,read,report,save,submit"

#Display an oAuth login prompt for the user to user authorize our application, returns uri
Show-OAuthWindow -url $URL

#attempt to parse $uri to retrieve our AuthCode
$regex = '(?<=code=)(.*)'

try {$Reddit_authCode = ($uri | Select-string -pattern $regex).Matches[0].Value}
catch {Write-Warning "did not receive an authCode, check ClientID and RedirectURi"
return}

$global:Reddit_authCode = $Reddit_authCode
Write-Verbose "Received an authCode, $Reddit_authCode"

write-debug "Pause here to test value of `$uri"
Write-Verbose "Exchanging authCode for Access Token"

try {
#reddit uses basic auth, which means in PowerShell that we can provide our creds using a credential object
$secpasswd = ConvertTo-SecureString $ClientSecret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($ClientID, $secpasswd)

#retrieve Access Token
$result = Invoke-RestMethod https://ssl.reddit.com/api/v1/access_token -Method Post -Body @{client_id=$clientId; state=$guid ; redirect_uri=$redirectURI; grant_type="authorization_code"; code=$Reddit_authCode} -ContentType "application/x-www-form-urlencoded" -ErrorAction STOP -Credential $credential
}
catch {
Write-Warning "Something didn't work"
Write-debug "Test the -body params for the Rest command"
}

Write-Debug 'go through the results of $result, looking for our token'
if ($result.access_token){
Write-Output "Updated Authorization Token"
$global:PSReddit_accessToken = $result.access_token}

Write-Verbose "Storing token in $configDir"
#store the token
$password = ConvertTo-SecureString $PSReddit_accessToken -AsPlainText -Force
$password | ConvertFrom-SecureString | Export-Clixml $configDir -Force

Write-verbose "Storing refresh token in $refreshToken"
$password = ConvertTo-SecureString $result.refresh_token -AsPlainText -Force
$password | ConvertFrom-SecureString | Export-Clixml $refreshToken -Force

}
else{
#if the user did not specify -Force, or if the file path for a stored token already exists
Write-Verbose "We're looking for a stored token in $configDir"
try {
$password = Import-Clixml -Path $configDir -ErrorAction STOP | ConvertTo-SecureString
$refreshToken = Import-Clixml -Path $refreshToken -ErrorAction STOP | ConvertTo-SecureString
}
catch {
Write-Warning "Corrupt Password file found, rerun with -Force to fix this"
BREAK
}

Get-DecryptedValue -inputObj $password -name PSReddit_accessToken
Get-DecryptedValue -inputObj $refreshToken -name PSReddit_refreshToken
<#
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$global:PSReddit_accessToken = $result #>
'Found cached Cred'
continue
}

}
58 changes: 58 additions & 0 deletions Public/Get-RedditAccount.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<#
.SYNOPSIS
Gets information about the currently logged in user
.Description
After you've connected using Connect-RedditAccount, you can use this cmdlet to get information about the currently logged in user
.PARAMETER redditSession
An optional session to use (like that returned from Connect-RedditSession)
.Example
Get-RedditAccount
name : 1RedOne
hide_from_robots : False
gold_creddits : 0
link_karma : 2674
comment_karma : 19080
over_18 : True
is_gold : False
is_mod : False
gold_expiration :
has_verified_email : True
inbox_count : 2
Created Date : 1/20/2010 6:44:21 PM
.LINK
https://github.com/1RedOne/PSReddit
#>
function Get-RedditAccount
{
[CmdletBinding()]
Param (
[Parameter(
Position = 1,
Mandatory = $false,
ValueFromPipelineByPropertyName = $true
)]
[Alias("Link")]
$accessToken=$Global:PSReddit_accessToken
)


$defaultDisplaySet = 'ID','name','Created Date','comment_karma','link_karma','gold_credits'

#Create the default property display set
$defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet(DefaultDisplayPropertySet,[string[]]$defaultDisplaySet)
$PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)

$uri = 'https://oAuth.reddit.com/api/v1/me'
try {$response = (Invoke-RestMethod $uri -Headers @{"Authorization" = "bearer $accessToken"}) }
catch{write-warning "Authentication failed, we should do something here"}

$origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0
$created = $origin.AddSeconds($response.created)

$response | select -ExcludeProperty created* -Property *,@{Name="Created Date";exp={$created}}

$response.PSObject.TypeNames.Insert(0,'PSReddit.User')
$response | Add-Member MemberSet PSStandardMembers $PSStandardMembers

}
35 changes: 35 additions & 0 deletions Public/Get-RedditComment.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<#
.SYNOPSIS
Gets comments of a Reddit link
.DESCRIPTION
Uses the Reddit API to get comments made on a given link
.PARAMETER id
Internal id of the Reddit link
#>
function Get-RedditComment
{
[CmdletBinding()]
Param (
[Parameter(
Position = 1,
Mandatory = $true,
ValueFromPipelineByPropertyName = $true
)]
[Alias("Link")]
[string]
$id
)

Process
{
$uri = 'http://www.reddit.com/comments/{0}.json' -f $id

$listings = (Invoke-RestMethod $uri) | Where kind -eq 'Listing'

# Comments have a type 't1' in Reddit API
$comments = $listings | %{ $_.data.children } | Where kind -eq 't1' | Select -Expand data

$comments | %{ $_.PSObject.TypeNames.Insert(0,'PowerReddit.Comment'); $_ }
}
}
36 changes: 36 additions & 0 deletions Public/Get-RedditLink.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<#
.SYNOPSIS
Gets a list of Reddit links
.DESCRIPTION
Uses the Reddit API to get Reddit links from given subreddit(s)
.PARAMETER Name
Name of the Subreddit to fetch from. Can be an array.
#>
function Get-RedditLink
{
[CmdletBinding()]
Param (
[Parameter(Position=1, Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("r","Subreddit")]
[string[]]
$Name = 'frontpage'
)

# Construct the Uri. Multiple subreddits can be joined with plusses
$uri = 'http://www.reddit.com/r/{0}.json' -f [string]::Join('+', $Name)

# Run the RestMethod in the current user context
$response = (Invoke-RestMethod $uri -WebSession $script:currentRedditSession)

# This is the listing. Contains before/after for pagination, and links
$listing = $response | Where kind -eq 'Listing' | Select -Expand data

# Links have type "t3" in Reddit API
$links = $listing.children | Where kind -eq 't3' | select -expand data

# Return the links with a custom type of [PowerReddit.Link]. We do this so
# that they can be extended by psxml files, etc.
$links | %{ $_.PSObject.TypeNames.Insert(0,'PowerReddit.Link'); $_ }

}
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
PowerReddit
PSReddit
===========
This is a set of tools for browsing Reddit using the Powershell command line.

Installation
------------
* Copy the "PowerReddit" folder into your module path. Note: You can find an
* Copy the "PSReddit" folder into your module path. Note: You can find an
appropriate directory by running `$ENV:PSModulePath.Split(';')`.
* Run `Import-Module PowerReddit` from your PowerShell command prompt.

Expand Down

0 comments on commit e7a55eb

Please sign in to comment.