forked from valpackett/transmitter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
52 lines (48 loc) · 1.43 KB
/
common.js
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
'use strict'
////// RPC
function rpcCall (meth, args) {
return browser.storage.local.get('server').then(({server}) => {
const myHeaders = {
'Content-Type': 'application/json',
'x-transmission-session-id': server.session,
}
if (server.username !== '' || server.password !== '') {
myHeaders['Authorization'] = 'Basic ' + btoa((server.username || '') + ':' + (server.password || ''))
}
return fetch(server.base_url + 'rpc', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify({method: meth, arguments: args}),
credentials: 'include' // allows HTTPS client certs!
}).then(response => {
const session = response.headers.get('x-transmission-session-id')
if (session) {
browser.storage.local.get('server').then(({server}) => {
server.session = session
browser.storage.local.set({server})
})
}
if (response.status === 409) {
return rpcCall(meth, args)
}
if (response.status >= 200 && response.status < 300) {
return response
}
const error = new Error(response.statusText)
error.response = response
throw error
}).then(response => response.json())
})
}
////// Util
function formatSpeed (s) {
// Firefox shows 4 characters max
if (s < 1000 * 1000) {
return (s / 1000).toFixed() + 'K'
}
if (s < 1000 * 1000 * 1000) {
return (s / 1000 / 1000).toFixed() + 'M'
}
// You probably don't have that download speed…
return (s / 1000 / 1000 / 1000).toFixed() + 'T'
}