-
Notifications
You must be signed in to change notification settings - Fork 7
/
api.go
75 lines (63 loc) · 1.86 KB
/
api.go
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
package kobo
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"strconv"
"time"
)
// UpgradeCheckResult represents an update check result from the Kobo API.
type UpgradeCheckResult struct {
Data interface{}
ReleaseNoteURL string
UpgradeType UpgradeType
UpgradeURL string
}
var verRe = regexp.MustCompile(`[0-9]+\.[0-9]+(\.[0-9]+)?`)
// ParseVersion tries to extract the version from the UpgradeURL. It returns 0.0.0 if none is present.
func (u UpgradeCheckResult) ParseVersion() string {
m := verRe.FindString(u.UpgradeURL)
if !u.UpgradeType.IsUpdate() || m == "" {
return "0.0.0"
}
return m
}
// UpgradeType represents an upgrade type.
type UpgradeType int
// Upgrade types.
const (
UpgradeTypeNone UpgradeType = 0 // No upgrade available.
UpgradeTypeAvailable UpgradeType = 1 // Optional update, but never seen this before.
UpgradeTypeRequired UpgradeType = 2 // Automatic update.
)
func (u UpgradeType) String() string {
switch u {
case UpgradeTypeNone:
return "None"
case UpgradeTypeAvailable:
return "Available"
case UpgradeTypeRequired:
return "Required"
default:
return "Unknown (" + strconv.Itoa(int(u)) + ")"
}
}
// IsUpdate checks if an UpdateType signifies an available update.
func (u UpgradeType) IsUpdate() bool {
return u != UpgradeTypeNone
}
// CheckUpgrade queries the Kobo API for an update.
func CheckUpgrade(device, affiliate, curVersion, serial string) (*UpgradeCheckResult, error) {
resp, err := (&http.Client{Timeout: time.Second * 10}).Get(fmt.Sprintf("https://api.kobobooks.com/1.0/UpgradeCheck/Device/%s/%s/%s/%s", device, affiliate, curVersion, serial))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("response status %d", resp.StatusCode)
}
var res UpgradeCheckResult
err = json.NewDecoder(resp.Body).Decode(&res)
return &res, err
}