forked from moul/go-freebox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreebox.go
367 lines (313 loc) · 9.75 KB
/
freebox.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package freebox
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/Sirupsen/logrus"
)
// ApiVersion is returned by requesting `GET /api_version`
type ApiVersion struct {
FreeboxID string `json:"uid",omitempty`
DeviceName string `json:"device_name",omitempty`
Version string `json:"api_version",omitempty`
BaseURL string `json:"api_base_url",omitempty`
DeviceType string `json:"device_type",omitempty`
}
type App struct {
Identifier string `json:"app_id",omitempty`
Name string `json:"app_name",omitempty`
Version string `json:"app_version",omitempty`
DeviceName string `json:"device_name",omitempty`
token string `json:-`
trackID int
status string
loggedIn bool
challenge string
password string
passwordSalt string
sessionToken string
permissions []string
}
type apiResultDownloadsStats struct {
NbRSSItemsUnread int `json:"nb_rss_items_unread"`
NbTasks int `json:"nb_tasks"`
NbTasksActive int `json:"nb_tasks_active"`
NbTasksChecking int `json:"nb_tasks_checking"`
NbTasksDone int `json:"nb_tasks_done"`
NbTasksDownloading int `json:"nb_tasks_downloading"`
NbTasksError int `json:"nb_tasks_error"`
NbTasksExtracting int `json:"nb_tasks_extracting"`
NbTasksQueued int `json:"nb_tasks_queue"`
NbTasksRepairing int `json:"nb_tasks_repairing"`
NbTasksSeeding int `json:"nb_tasks_seeding"`
NbTasksStopped int `json:"nb_tasks_stopped"`
NbTasksStopping int `json:"nb_tasks_stopping"`
RXRate int `json:"rx_rate"`
TXRate int `json:"tx_rate"`
ThrottlingIsScheduled bool `json:"throttling_is_scheduled"`
ThrottlingMode string `json:"throttling_mode"`
ThrottlingRate struct {
RXRate int `json:"rx_rate"`
TXRate int `json:"tx_rate"`
} `json:"throttling_rate"`
}
type apiResponseDownloadsStats struct {
Success bool `json:"success"`
Result apiResultDownloadsStats `json:"result"`
}
type apiRequestLoginSession struct {
AppID string `json:"app_id",omitempty`
AppVersion string `json:"app_version",omitempty`
Password string `json:"password",omitempty`
}
type apiResponseLoginAuthorize struct {
Success bool `json:"success"`
Result struct {
AppToken string `json:"app_token",omitempty`
TrackID int `json:"track_id",omitempty`
} `json:"result"`
}
type apiResponseLoginSession struct {
Success bool `json:"success"`
Result struct {
SessionToken string `json:"session_token",omitempty`
Challenge string `json:"",omitempty`
PasswordSalt string `json:"",omitempty`
Permissions map[string]bool `json:"",omitempty`
} `json:"result"`
}
type apiResponseLoginAuthorizeTrack struct {
Success bool `json:"success"`
Result struct {
Status string `json:"status",omitempty`
Challenge string `json:"challenge",omitempty`
PasswordSalt string `json:"password_salt",omitempty`
} `json:"result"`
}
type apiResponseLogin struct {
Success bool `json:"success"`
Result struct {
LoggedIn bool `json:"logged_in",omitempty`
Challenge string `json:"challenge",omitempty`
PasswordSalt string `json:"password_salt",omitempty`
} `json:"result"`
}
// Client is the Freebox API client
type Client struct {
URL string
App App
apiVersion ApiVersion
client *http.Client
}
type apiCallEntry struct {
Success bool `json:"success"`
Result []CallEntry `json:"result"`
}
// New returns a `Client` object with standard configuration
func New() *Client {
client := Client{
URL: "http://mafreebox.freebox.fr/",
client: &http.Client{},
App: App{
Identifier: "go-freebox",
Name: "Go Freebox",
Version: "0.8.0",
DeviceName: "Golang",
},
}
if os.Getenv("GOFBX_TOKEN") != "" {
client.App.token = os.Getenv("GOFBX_TOKEN")
}
if os.Getenv("GOFBX_URL") != "" {
client.URL = os.Getenv("GOFBX_URL")
}
if os.Getenv("GOFBX_ID") != "" {
client.App.Identifier = os.Getenv("GOFBX_ID")
}
if os.Getenv("GOFBX_NAME") != "" {
client.App.Name = os.Getenv("GOFBX_NAME")
}
return &client
}
// ApiVersion returns an `ApiVersion` structure field with the configuration fetched during `Connect()`
func (c *Client) ApiVersion() *ApiVersion {
return &c.apiVersion
}
func (a *ApiVersion) ApiCode() string {
return "v" + strings.Split(a.Version, ".")[0]
}
// GetApiResource performs low-level GET request on the Freebox API
func (c *Client) GetResource(resource string, authenticated bool) ([]byte, error) {
return c.httpRequest("GET", resource, nil, authenticated)
}
// PostResource post data and returns body
func (c *Client) PostResource(resource string, data interface{}, authenticated bool) ([]byte, error) {
return c.httpRequest("POST", resource, data, authenticated)
}
// PostResource post data and returns body
func (c *Client) PutResource(resource string, data interface{}, authenticated bool) ([]byte, error) {
return c.httpRequest("PUT", resource, data, authenticated)
}
func (a *ApiVersion) authBaseURL() string {
return strings.TrimLeft(a.BaseURL, "/") + a.ApiCode() + "/"
}
// performs low-level http request, and reauthen if needed
func (c *Client) httpRequest(verb, resource string, data interface{}, authenticated bool) ([]byte, error) {
resp, body, err := c.httpRequest2(verb, resource, data, authenticated)
if authenticated && err == nil && resp.StatusCode == 403 {
// session expired, do it again
c.Login()
resp, body, err = c.httpRequest2(verb, resource, data, authenticated)
}
if resp.StatusCode > 299 {
err = fmt.Errorf("Status code: %d", resp.StatusCode)
}
return body, err
}
// httpRequest performs low-level http request on the Freebox API
func (c *Client) httpRequest2(verb, resource string, data interface{}, authenticated bool) (*http.Response, []byte, error) {
var url string
var req *http.Request
var err error
if authenticated {
url = fmt.Sprintf("%s%s%s/%s", strings.TrimRight(c.URL, "/"), c.apiVersion.BaseURL, c.apiVersion.ApiCode(), resource)
} else {
url = fmt.Sprintf("%s%s", c.URL, resource)
}
if data != nil {
payload := new(bytes.Buffer)
encoder := json.NewEncoder(payload)
if err = encoder.Encode(data); err != nil {
return nil, nil, err
}
payloadString := strings.TrimSpace(fmt.Sprintf("%s", payload))
logrus.Debugf(">>> %s %s payload=%s", verb, url, payloadString)
req, err = http.NewRequest(verb, url, payload)
} else {
logrus.Debugf(">>> %s %q", verb, url)
req, err = http.NewRequest(verb, url, nil)
if err != nil {
return nil, nil, err
}
}
req.Header.Set("Content-Type", "application/json")
if authenticated {
req.Header.Set("X-Fbx-App-Auth", c.App.sessionToken)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
logrus.Debugf("<<< %s", body)
return resp, body, err
}
// Connect tries to contact the Freebox API, and fetches API versions
func (c *Client) Connect() error {
body, err := c.GetResource("api_version", false)
if err != nil {
return err
}
logrus.Debugf("API response: %s", string(body))
err = json.Unmarshal(body, &c.apiVersion)
if err != nil {
return err
}
logrus.Infof("API version: FreeboxID=%q DeviceName=%q Version=%q DeviceType=%q", c.apiVersion.FreeboxID, c.apiVersion.DeviceName, c.apiVersion.Version, c.apiVersion.DeviceType)
return nil
}
func (c *Client) Authorize() error {
if c.App.token != "" {
logrus.Debugf("App already registered, skiping `Authorize()`")
return nil
}
body, err := c.PostResource(c.apiVersion.authBaseURL()+"login/authorize", c.App, false)
if err != nil {
return err
}
var response apiResponseLoginAuthorize
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
c.App.token = response.Result.AppToken
c.App.trackID = response.Result.TrackID
logrus.Infof("Authorize: Token=%q TrackID=%d", c.App.token, c.App.trackID)
for {
body, err := c.GetResource(c.apiVersion.authBaseURL()+fmt.Sprintf("login/authorize/%d", c.App.trackID), false)
if err != nil {
return err
}
var response apiResponseLoginAuthorizeTrack
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
if response.Result.Status == "denied" {
return fmt.Errorf("App denied")
}
if response.Result.Status == "granted" {
break
}
time.Sleep(5 * time.Second)
}
return nil
}
func (c *Client) Login() error {
if c.App.token == "" {
return fmt.Errorf("You need to get a token with `Authorize()` first")
}
body, err := c.GetResource(c.apiVersion.authBaseURL()+"login", false)
if err != nil {
return err
}
var response apiResponseLogin
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
c.App.loggedIn = response.Result.LoggedIn
c.App.challenge = response.Result.Challenge
c.App.passwordSalt = response.Result.PasswordSalt
hash := hmac.New(sha1.New, []byte(c.App.token))
hash.Write([]byte(c.App.challenge))
c.App.password = fmt.Sprintf("%x", hash.Sum(nil))
if !c.App.loggedIn {
data := apiRequestLoginSession{
AppID: c.App.Identifier,
AppVersion: c.App.Version,
Password: c.App.password,
}
body, err := c.PostResource(c.apiVersion.authBaseURL()+"login/session/", data, false)
if err != nil {
return err
}
var response apiResponseLoginSession
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
c.App.sessionToken = response.Result.SessionToken
}
return nil
}
func (c *Client) DownloadsStats() (*apiResultDownloadsStats, error) {
body, err := c.GetResource("downloads/stats", true)
if err != nil {
return nil, err
}
var response apiResponseDownloadsStats
err = json.Unmarshal(body, &response)
if err != nil {
return nil, err
}
return &response.Result, nil
}