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
|
import * as config from '../../config'
let token
export let installation
export let repositories
function request (...args) {
return fetch(...args).then(res => {
return res.status !== 401 ? res : (
console.error('Authentication failure. Retrying login'),
beginLoginFlow()
)
})
}
export async function init () {
const param = new URLSearchParams(location.search).get('token')
if (!localStorage.auth_token && param) {
history.replaceState({}, null, location.pathname)
localStorage.auth_token = param
}
if (localStorage.auth_token) {
token = localStorage.auth_token
const data = await request(`${config.apiBaseUrl}/github/installation`, {
headers: {
Authorization: `Bearer ${token}`
}
}).then(res => res.json())
if (!data.installation) {
console.log('no installation found for authenticated user')
location.href = `https://github.com/apps/${config.githubAppName}/installations/new`
}
installation = data.installation
repositories = data.repositories
}
}
export function beginLoginFlow () {
localStorage.removeItem('auth_token')
location.href = `${config.apiBaseUrl}/github/authorize`
}
export function isGitHubAuthorized() {
return !!token && installation && repositories && repositories.length
}
export async function fetchRepoBranches(repository) {
const response = await request(
`${config.apiBaseUrl}/github/installation/${encodeURIComponent(installation.id)}/${encodeURIComponent(repository.full_name)}/branches`,
{ headers: { Authorization: `Bearer ${localStorage.auth_token}`} }
)
return response.json()
}
export async function fetchLayoutAndKeymap(repo, branch) {
const repository = repo
const url = new URL(`${config.apiBaseUrl}/github/keyboard-files/${encodeURIComponent(installation.id)}/${encodeURIComponent(repository)}`)
if (branch) {
url.search = new URLSearchParams({ branch }).toString()
}
const response = await request(url.toString(), {
headers: {
Authorization: `Bearer ${localStorage.auth_token}`
}
})
if (response.status === 400) {
console.error('Failed to load keymap and layout from github')
return response.json()
}
const data = await response.json()
const defaultLayout = data.info.layouts.default || data.info.layouts[Object.keys(data.info.layouts)[0]]
return {
layout: defaultLayout.layout,
keymap: data.keymap
}
}
export function commitChanges(repo, branch, layout, keymap) {
const installationId = encodeURIComponent(installation.id)
const repository = encodeURIComponent(repo)
const url = `${config.apiBaseUrl}/github/keyboard-files/${installationId}/${repository}/${encodeURIComponent(branch)}`
return request(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ layout, keymap })
})
}
|