internal/functions/Read-RRChapter.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
function Read-RRChapter {
    <#
    .SYNOPSIS
        Reads a Royal Road chapter and breaks it down into its components.
     
    .DESCRIPTION
        Reads a Royal Road chapter and breaks it down into its components.
        Part of the parsing process to convert Royal Road books into eBooks.
     
    .PARAMETER Url
        Url to the specific RR page to process.
     
    .PARAMETER Index
        The chapter index to include in the return object
 
    .PARAMETER NoHeader
        The book does not include a header in the text portion.
        Will take the chapter-name as header instead.
 
    .PARAMETER Replacements
        A hashtable with replacements.
        At the root level, either use the "Global" index for replacements that apply to all chapters or the number of the chapter it applies to.
        Each value of those key/value pairs contains yet another hashtable, using a label as key (they label is ignored, use this for human documentation in the file) and yet another hashtable as value.
        That hashtable may contain three keys:
        - Pattern (mandatory)
        - Text (mandatory)
        - Weight (optional)
        The Pattern is a piece of text used to find matching text within the current chapter. Uses Regex.
        The Text is what we replace matched content with.
        The Weight - if specified - is the processing order in case of multiple replacements - the lower the number, the earlier is it processed.
     
    .EXAMPLE
        PS C:\> Read-RRChapter -Url https://www.royalroad.com/fiction/12345/evil-incarnate/chapter/666666/1-end-of-all-days
     
        Reads and converts the first chapter of evil incarnate (hint: does not exist)
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Url,
        
        [int]
        $Index,

        [switch]
        $NoHeader,

        [hashtable]
        $Replacements
    )
    
    begin {
        #region functions
        function Get-NextLink {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [parameter(ValueFromPipeline = $true)]
                [string]
                $Line
            )
            process {
                if ($Line -notlike '*<a class="btn btn-primary*>Next <br class="visible-xs" />Chapter</a>*') { return }
                $Line -replace '^.+href="(.+?)".+$', 'https://www.royalroad.com$1'
            }
        }

        function Get-Title {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [parameter(ValueFromPipeline = $true)]
                [string]
                $Line
            )
            process {
                if ($Line -notmatch '<h1 .+?>(.+?)</h1>') { return }
                $matches[1]
            }
        }
        
        function ConvertTo-Markdown {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [Parameter(ValueFromPipeline = $true)]
                [string]
                $Line,

                [switch]
                $NoHeader,

                [string]
                $Title
            )
            
            begin {
                $firstLineCompleted = $false
                
                $badQuotes = @(
                    [char]8220
                    [char]8221
                    [char]8222
                    [char]8223
                )
                $badQuotesPattern = $badQuotes -join "|"
                $badSingleQuotes = @(
                    [char]8216
                    [char]8217
                    [char]8218
                    [char]8219
                )
                $badSingleQuotesPattern = $badSingleQuotes -join "|"

                if ($NoHeader) {
                    '# {0}' -f $Title
                    ''
                }
            }
            process {
                $lineNormalized = ($Line -replace $badQuotesPattern, '"' -replace $badSingleQuotesPattern, "'").Trim()
                if (-not $firstLineCompleted -and -not $NoHeader) {
                    '# {0}' -f ($lineNormalized -replace '</{0,1}p.{0,}?>' -replace '</{0,1}b>' -replace '</{0,1}strong>' -replace '<br>', '<br />')
                    ''
                    $firstLineCompleted = $true
                    return
                }
                
                if ($lineNormalized -eq '<p style="text-align: center">* * *</p>') {
                    @'
## <divide>
  * * *
## </divide>
 
'@

                    return
                }
                
                $lineNormalized | ConvertTo-MarkdownLine
                ''
            }
        }

        function ConvertTo-MarkdownFinal {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [Parameter(ValueFromPipeline = $true)]
                [string]
                $Text,

                [Hashtable]
                $Replacements,

                [int]
                $ChapterIndex
            )
            begin {
                $mapping = @($Replacements.Global.Values) + @($Replacements[$ChapterIndex].Values) | Sort-Object Weight
            }
            process {
                foreach ($item in $mapping) {
                    $Text = $Text -replace $item.Pattern, $item.Text
                }
                $Text
            }
        }
        #endregion functions
    }
    process {
        $found = $false
        try { $allLines = (Invoke-WebRequest -Uri $Url -UseBasicParsing -ErrorAction Stop).Content -split "`n" }
        catch {
            if ($_.ErrorDetails.Message -ne 'Slow down!') { throw }
            Start-Sleep -Seconds 1
            $allLines = (Invoke-WebRequest -Uri $Url -UseBasicParsing -ErrorAction Stop).Content -split "`n"
        }
        $lines = $allLines | Where-Object {
            if ($_ -like '*<div class="chapter-inner chapter-content">*') {
                $found = $true
            }
            if ($_ -like '*<h6 class="bold uppercase text-center">Advertisement</h6>*') {
                $found = $false
            }
            
            # Remove all pictures, they don't close the tags correctly
            if (
                $_ -like '*<img*' -or
                $_ -like '*<input*'
            ) { return }
            $found
        }
        $title = $allLines | Get-Title
        [pscustomobject]@{
            Index    = $Index
            Title    = $title
            RawText  = $allLines -join "`n"
            Text     = $lines -join "`n" -replace '<br>', '<br />' -replace '<div class="chapter-inner chapter-content">', '<div>'
            TextMD   = $lines[1 .. ($lines.Length - 2)] | ConvertTo-Markdown -NoHeader:$NoHeader -Title $Title | Join-String "`n" | ConvertTo-MarkdownFinal -Replacements $Replacements -ChapterIndex $Index
            NextLink = $allLines | Get-NextLink
        }
    }
}