Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/pester-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ jobs:
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module -Name Pester -Force -SkipPublisherCheck
Install-Module -Name PowerShell-Yaml -Force -SkipPublisherCheck

- name: Install pandoc
shell: pwsh
run: |
choco install pandoc -y

- name: Run Pester Tests
shell: pwsh
Expand Down
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,35 @@ A PowerShell library for publishing markdown files authored in markdown to Blogg
Get-BloggerPosts
```

1. Fetch an individual post from your blog

```
Get-BloggerPost -PostId <postid>
```

You can also persist the post to disk as HTML or markdown in the current directory.

When using `HTML` format, files are saved as `<postid>.html`

When using `Markdown` format, files are saved as `<title>.md`

```
Get-BloggerPost -PostId <postid> -Format HTML
Get-BloggerPost -PostId <postid> -Format Markdown
```

You can specify an output directory where the file will be saved.

```
Get-BloggerPost -PostId <postid> -OutDirectory "C:\MyPosts" -Format HTML
```

You can also include a `FolderDateFormat` that uses the `published` property of the blog post to construct a subfolder.

```
Get-BloggerPost -PostId <postId> -OutDirectory ".\Blog" -FolderDateFormat "YYYY\\MM" -Format Markdown
```

1. Publish a markdown file to your blog as draft

```
Expand Down
2 changes: 1 addition & 1 deletion src/public/ConvertTo-HtmlFromMarkdown.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<#
.SYNOPSIS
Convert a file to Markdown using Pandoc
Convert a Markdown file to HTML using Pandoc

.PARAMETER File
The file path of the markdown file
Expand Down
73 changes: 73 additions & 0 deletions src/public/ConvertTo-MarkdownFromHtml.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<#
.SYNOPSIS
Convert HTML content or a HTML file to Markdown using Pandoc

.PARAMETER File
The file path of the html file. Required when Content is not specified.

.PARAMETER Content
The HTML content to convert to Markdown. Required when File is not specified.

.PARAMETER OutFile
The resulting markdown file, if specified.

#>
function ConvertTo-MarkdownFromHtml {
param(
[Parameter(Mandatory, ParameterSetName = "FromFile")]
[ValidateScript({ Test-Path $_ -PathType Leaf })]
[string]$File,

[Parameter(Mandatory, ParameterSetName = "FromContent")]
[string]$Content,

[Parameter(ParameterSetName = "FromFile")]
[Parameter(Mandatory=$false, ParameterSetName = "FromContent")]
[string]$OutFile
)

# when FromContent is specified, write the content to a temporary file
if ($PSCmdlet.ParameterSetName -eq "FromContent") {
# If content is provided, create a temporary file
$tempFile = [System.IO.Path]::GetTempFileName() + ".html"
Set-Content -Path $tempFile -Value $Content
$File = $tempFile
}

# ensure that the file is an absolute path because pandoc.exe doesn't like powershell relative paths
$File = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($File)

# Use pandoc to convert the markdown to Html
$pandocArgs = "`"{0}`" " -f $File
$pandocArgs += "-f {0} " -f $BloggerSession.PandocHtmlFormat
$pandocArgs += "-t {0} " -f $BloggerSession.PandocMarkdownFormat

# add additional command-line arguments
if ($BloggerSession.PandocAdditionalArgs) {
Write-Verbose "Using additional args"
$pandocArgs += "{0} " -f $BloggerSession.PandocAdditionalArgs
}

if (!($OutFile)) {
$OutFile = Join-Path (Split-Path $File -Parent) ((Split-Path $File -LeafBase) + ".md")
Write-Verbose "Using OutFile: $OutFile"
}
# ensure that the file is an absolute path because pandoc.exe doesn't like powershell relative paths
$OutFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutFile)

$pandocArgs += "-o `"{0}`" " -f $OutFile

Write-Verbose ">> pandoc $($pandocArgs)"
Start-Process pandoc -ArgumentList $pandocArgs -NoNewWindow -Wait

$content = Get-Content $OutFile -Raw

# remove temporary files
if ($PSCmdlet.ParameterSetName -eq "FromContent") {
Remove-Item $File
} elseif (!$PSBoundParameters.ContainsKey("OutFile")) {
Remove-Item $OutFile
}

return $content
}
145 changes: 145 additions & 0 deletions src/public/Get-BloggerPost.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<#
.DESCRIPTION
Retrieves an individual post from a specified Blogger blog and optionally saves the content to a file as HTML or Markdown.

.PARAMETER BlogId
The ID of the blog to retrieve the post from. If not specified, uses the BlogId in the user preferences.

.PARAMETER PostId
The ID of the post to retrieve. This parameter is required.

.PARAMETER Format
The format of the post content to retrieve. Use either Markdown or HTML.

.PARAMETER FolderDateFormat
The folder name as expressed in a DateTime format string. For example, "YYYY/MM" which will save files
in a folder structure like "2023/10" based on the date of the post.

.PARAMETER OutDirectory
The directory where the HTML file will be saved. If not specified, uses the current directory.

.EXAMPLE
Get-BloggerPost -PostId "1234567890123456789"

.EXAMPLE
Get-BloggerPost -BlogId "9876543210987654321" -PostId "1234567890123456789" -Format HTML -OutDirectory "C:\temp"

.EXAMPLE
Get-BloggerPost -BlogId "9876543210987654321" -PostId "1234567890123456789" -Format Markdown -DateFormat "YYYY\\MM" -OutDirectory "C:\blogposts"
#>
Function Get-BloggerPost {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = "Default")]
[Parameter(ParameterSetName = "Persist")]
[string]$BlogId,

[Parameter(Mandatory,ParameterSetName = "Default")]
[Parameter(Mandatory,ParameterSetName = "Persist")]
[string]$PostId,

[Parameter(Mandatory, ParameterSetName = "Persist")]
[ValidateSet("HTML", "Markdown")]
[string]$Format,

[Parameter(ParameterSetName ="Persist")]
[string]$FolderDateFormat,

[Parameter(ParameterSetName = "Persist")]
[string]$OutDirectory = (Get-Location).Path
)

if (!$PSBoundParameters.ContainsKey("BlogId")) {
$BlogId = $BloggerSession.BlogId
if ([string]::IsNullOrEmpty($BlogId) -or $BlogId -eq 0) {
throw "BlogId not specified and no default BlogId found in settings."
}
}

if ([string]::IsNullOrEmpty($PostId)) {
throw "PostId is required."
}

try {
$uri = "https://www.googleapis.com/blogger/v3/blogs/$BlogId/posts/$PostId"

$result = Invoke-GApi -uri $uri

if ($null -eq $result) {
throw "No post found with PostId '$PostId' in blog '$BlogId'."
}

# Construct a subfolder based on the published date
if ($FolderDateFormat -and $result.published) {
$date = [datetime]::Parse($result.published)
$formattedDate = $date.ToString($FolderDateFormat)
$OutDirectory = Join-Path -Path $OutDirectory -ChildPath $formattedDate
}

# Ensure the output directory exists
if (!(Test-Path -Path $OutDirectory)) {
try {
New-Item -ItemType Directory -Path $OutDirectory -Force | Out-Null
}
catch {
throw "Failed to create output directory '$OutDirectory': $($_.Exception.Message)"
}
}

# Extract the HTML content
$htmlContent = $result.content

if ([string]::IsNullOrEmpty($htmlContent)) {
Write-Warning "Post '$PostId' has no content."
$htmlContent = ""
}

# Create the output file path
try {

switch ($Format) {

# Save the HTML content to a file
"HTML" {

$fileName = "$PostId.html"
$filePath = Join-Path -Path $OutDirectory -ChildPath $fileName
$htmlContent | Out-File -FilePath $filePath -Encoding UTF8
Write-Verbose "Post content saved to: $filePath"
}

# Save the Post to a Markdown file
"Markdown" {

$title = $result.title
$frontMatter = [ordered]@{
postId = $result.id
}
$file = "$title.md"
$filePath = Join-Path -Path $OutDirectory -ChildPath $file
ConvertTo-MarkdownFromHtml -Content $result.content -OutFile $filePath > $null
Set-MarkdownFrontMatter -File $filePath -Replace $frontMatter
Write-Verbose "Post content saved to: $filePath"
}
}

# Return the post object for further processing if needed
return $result
}
catch {
throw "Failed to save post content to file '$filePath': $($_.Exception.Message)"
}
}
catch {
# Handle specific HTTP errors
if ($_.Exception -like "*404*" -or $_.Exception -like "*Not Found*") {
throw "Post with PostId '$PostId' not found in blog '$BlogId'. Please verify the PostId and BlogId are correct."
}
elseif ($_.Exception -like "*403*" -or $_.Exception -like "*Forbidden*") {
throw "Access denied to blog '$BlogId' or post '$PostId'. Please verify your permissions."
}
else {
Write-Error $_.ToString() -ErrorAction Stop
}
}
}
11 changes: 0 additions & 11 deletions src/tests/ConvertTo-HtmlFromMarkdown.Tests.ps1

This file was deleted.

79 changes: 79 additions & 0 deletions src/tests/ConvertTo-MarkdownFromHtml.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
Describe "ConvertTo-MarkdownFromHtml" {
BeforeAll {
Import-Module $PSScriptRoot\_TestHelpers.ps1 -Force

}

BeforeEach {
Import-Module $PSScriptRoot\..\PSBlogger.psm1 -Force
}

Context "Using Content" {

BeforeEach {
$outFile = "TestDrive:\123.md"
$htmlContent = "<h1>Hello World</h1>"
}

AfterEach {
if (Test-Path $outFile) {
Remove-Item $outFile -Force
}
}

It "Should save HTML content to a markdown file" {
# act
ConvertTo-MarkdownFromHtml -Content $htmlContent -OutFile $outFile

# assert
Test-Path $outFile | Should -BeTrue
}

It "Should convert HTML content to Markdown file" {
# act
$content = ConvertTo-MarkdownFromHtml -Content $htmlContent -OutFile $outFile

# assert
$content = (Get-Content -Path $outFile -Raw).Split("`r")
$content[0] | Should -Be "# Hello World"
}

It "Should not persist to disk if OutFile is not specified" {
# act
$content = ConvertTo-MarkdownFromHtml -Content $htmlContent

# assert
$content | Should -Not -BeNullOrEmpty
Test-Path $outFile | Should -BeFalse
}
}

Context "Using File" {

BeforeEach {
$htmlContent = "<h1>Hello World</h1>"
$htmlFile = "TestDrive:\123.html"
$markdownFile = "TestDrive:\123.md"
Set-Content -Path $htmlFile -Value $htmlContent
}

It "Should convert HTML file to Markdown" {
# act
$content = ConvertTo-MarkdownFromHtml -File $htmlFile -OutFile $markdownFile

# assert
Test-Path $markdownFile | Should -BeTrue
$content = (Get-Content -Path $markdownFile -Raw).Split("`r")
$content[0] | Should -Be "# Hello World"
}

It "Should delete temporary file" {
# act
$content = ConvertTo-MarkdownFromHtml -File $htmlFile

# assert
$content | Should -Not -BeNullOrEmpty
Test-Path $markdownFile | Should -BeFalse
}
}
}
Loading