PSKindleWatch.psm1

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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
$ErrorActionPreference = "Stop"

function Import-KindleDataFile {
    Param (
        [Parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path -Path $_ })]
        [string]$DataFile
    )

    Write-Verbose "Importing Kindle Data file"

    try {
        $BookData = Get-Content -Path $DataFile | ConvertFrom-Json
        Write-Output $BookData
    }
    catch {
        Write-Host "Unable to load or parse data file ($DataFile). The exception message is below." -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Red 
    }
}

function Export-KindleDataFile {

    Param(
        [Parameter(Mandatory = $true)]
        [ValidateScript( { Test-Path $_ })]
        [string]$DataFile,

        [Parameter(Mandatory = $true)]
        [psobject]$BookData,

        [Parameter(Mandatory = $false)]
        [string]$Message = $null
    )

    Write-Verbose "Exporting Kindle Data file"

    try {
        $BookData | ConvertTo-Json -Depth 100 | Out-File $DataFile -Force -Encoding utf8
        if ($Message) {
            Write-Host $Message
        }
    }
    catch {
        Write-Host "Unable to write to data file ($DataFile). The exception message is below."  -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Red
    }
}

function Get-AmazonData {

    Param (
        [Parameter(Mandatory = $true)]
        [string]$ASIN,
        [Parameter(Mandatory = $true)]
        [uri]$URL
    )

    Write-Verbose "Querying Amazon API"

    $Body = @{
        method = "getBookData"
        asin   = $ASIN
    }

    try {
        $Result = Invoke-RestMethod -Method Post -ContentType "application/x-www-form-urlencoded" -Uri "https://$($URL.Host)/gp/search-inside/service-data" -Body $Body -ErrorAction Stop
    }
    catch {
        Write-Host "API call was not successful. The exception message is below." -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Red
    }

    Write-Verbose "---- Start API Lookup Result ---------------------"
    Write-Verbose $Result | Out-String
    Write-Verbose "---- End API Lookup Result -----------------------"

    Write-Output $Result

}

function Add-KindleBook {
    [CmdletBinding()]

    Param (
        [Parameter(Mandatory = $true)]
        [ValidateScript( { $_.HostNameType -eq "DNS" })]
        [System.Uri]$BookURL, 

        [Parameter(Mandatory = $false)]
        [string]$DataFile = [Environment]::GetFolderPath("MyDocuments") + "\KindleBooks.json"
    )

    if (!(Test-Path $DataFile)) {
        New-Item -Path $DataFile -ItemType File | Out-Null
        $BookData = @()
    }
    else {
        $BookData = Import-KindleDataFile -DataFile $DataFile

        # We need this because Write-Output in Import-KindleDataFile converts a single item array
        # into an object (essentially dropping the array). This causes issues when we attempt to
        # add other objects to the array
        if ($BookData -is [PSCustomObject]) {
            [array]$BookData = @($BookData)
        }
    }

    $ASIN = $BookURL.ToString().Split("/")
    $ASINIndex = [array]::IndexOf($ASIN, "dp") + 1
    $ASIN = $ASIN[$ASINIndex]

    if ($ASIN.IndexOf("?") -ne -1) {
        $ASIN = $ASIN.Split("?")[0]
    }

    Write-Verbose "Extracted ASIN: $ASIN"  

    Write-Verbose "Checking if ASIN is already present in the data file"
    if ($ASIN -in $BookData.ASIN) {
        Write-Host "Book with ASIN $ASIN already exists in data file ($DataFile)" -ForegroundColor Gray
    }
    else {

        $Result = Get-AmazonData -ASIN $ASIN -URL $BookURL
        
        $Data = @{
            Title         = $Result.title
            Authors       = [array]$Result.authorNameList
            ASIN          = $Result.ASIN
            URL           = $BookURL
            ImageURL      = $Result.thumbnailImage.Replace("._SL75_", "")
            OriginalPrice = [decimal]$Result.buyingPrice.Replace("$", "")
            IsOnSale      = $false
            SalePrice     = 0
        }

        if ($Data.Title) {
            $obj = New-Object -TypeName PSCustomObject -Property $Data

            Write-Verbose "---- Start Object Dump ---------------------"
            Write-Verbose $obj | Out-String
            Write-Verbose "---- End Object Dump -----------------------"    
    
            $BookData += $obj            
            $Message = "Successfull added $($obj.Title)"
            
            Export-KindleDataFile -BookData $BookData -DataFile $DataFile -Message $Message
        }
        else {
            Write-Error "API call did not return required data. Please ensure the URL is of the Kindle edition of the book."
        }
    }

}

function Remove-KindleBook {
    param (
        [Parameter(Mandatory = $true)]
        [string]$BookTitle, 

        [Parameter(Mandatory = $false)]
        [string]$DataFile = [Environment]::GetFolderPath("MyDocuments") + "\KindleBooks.json"
    )

    $BookData = Import-KindleDataFile -DataFile $DataFile
    $BooksToBeRemoved = ($BookData | ? { $_.Title -match $BookTitle }).Title -join "`n -"
    if ($BooksToBeRemoved) {
        Write-Host "Removing: `n -$BooksToBeRemoved"
        $BookData = $BookData | ? { $_.Title -notmatch $BookTitle }


        if ($BookData -eq $null) {
            Write-Host "Book list is empty!"
            $BookData = @()
        }

        Export-KindleDataFile -DataFile $DataFile -BookData $BookData
    }
    else {
        Write-Host "No matching book titles found"
    }
}


function Get-KindleBooks {
    [CmdletBinding()]

    Param (
        [Parameter(Mandatory = $false)]
        [ValidateScript( { Test-Path -Path $_ })]
        [string]$DataFile = [Environment]::GetFolderPath("MyDocuments") + "\KindleBooks.json"
    )

    [array]$BookData = Import-KindleDataFile -DataFile $DataFile
    $Authors = @{Label="Authors";Expression={$_.Authors -join ", "}}

    Write-Output $BookData | Select Title, $Authors, OriginalPrice
}


function Update-KindleBookPrices {
    [CmdletBinding()]

    Param (
        [Parameter(Mandatory = $false)]
        [scriptblock]$AlertScriptBlock = $null,

        [Parameter(Mandatory = $false)]
        [ValidateScript( { Test-Path -Path $_ })]
        [string]$DataFile = [Environment]::GetFolderPath("MyDocuments") + "\KindleBooks.json"
    )

    $i = 0
    [array]$BookData = Import-KindleDataFile -DataFile $DataFile
    $BookCount = $BookData.count

    if ($?) {

        foreach ($Book in $BookData) {

            Write-Progress -Activity "Checking book prices" -Status "Progress:" -PercentComplete ($i / $BookCount * 100)
            $i++
            
            $Body = @{
                method = "getBookData"
                asin   = $Book.ASIN
            }
    
            Write-Host "Checking price of $($Book.Title)"

            $CurrentResult = Get-AmazonData -ASIN $Book.ASIN -URL $Book.URL
            $CurrentPrice = [decimal]$CurrentResult.buyingPrice.Replace("$", "")
            $Message = $null

            # Condition for original price being discounted
            if (($CurrentPrice -lt $Book.OriginalPrice) -and ($Book.IsOnSale -eq $false)) {
                $Message = "Found discount for $($Book.Title), new price is `$$CurrentPrice (original: `$$($Book.OriginalPrice))"
                Write-Host $Message -ForegroundColor Green
                $Book.SalePrice = $CurrentPrice
                $Book.IsOnSale = $true
            }

            # Condition for further discount being applied to existing discount
            if (($CurrentPrice -lt $Book.SalePrice) -and ($Book.IsOnSale -eq $true)) {
                $Message = "Additional discount found for $($Book.Title), new price is `$$CurrentPrice (original: `$$($Book.OriginalPrice))"
                Write-Host $Message -ForegroundColor Green
                $Book.SalePrice = $CurrentPrice
            }

            # Condition for reduced discount being applied to existing discount
            if (($CurrentPrice -gt $Book.SalePrice) -and ($Book.IsOnSale -eq $true)) {
                $Message = "Discount reduced for $($Book.Title), new price is `$$CurrentPrice (up from previous discount of `$$($Book.SalePrice) and original: $($Book.OriginalPrice))"
                Write-Host $Message -ForegroundColor Yellow
                $Book.SalePrice = $CurrentPrice
            }

            # Condition for sale ending
            if (($CurrentPrice -ge $Book.OriginalPrice) -and ($Book.IsOnSale -eq $true)) {
                $Message = "Sale ended for $($Book.Title), current price is `$$CurrentPrice"
                Write-Host $Message -ForegroundColor Red
                $Book.OriginalPrice = $CurrentPrice
                $Book.SalePrice = 0
                $Book.IsOnSale = $false
            }

            # Condition for price increase
            if (($CurrentPrice -gt $Book.OriginalPrice) -and ($Book.IsOnSale -eq $false)) {
                $Message = "Price increased for $($Book.Title), new price is `$$CurrentPrice (original: `$$($Book.OriginalPrice))"
                Write-Host $Message -ForegroundColor Red
                $Book.OriginalPrice = $CurrentPrice
            }

            if ($AlertScriptBlock -and $Message) {
                Write-Verbose "Triggering configured alert"
                Invoke-Command -ScriptBlock $AlertScriptBlock -ArgumentList $Book, $Message
            }

            Start-Sleep -Seconds 1
        }
    }

    Export-KindleDataFile -BookData $BookData -DataFile $DataFile
    Write-Progress -Completed -Activity "Checking book prices"
}