aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/github.js
blob: 5a06f54ac82220a6e21f7f2b4e773bbc730b9c3d (plain)
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
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 fetchLayoutAndKeymap() {
  const data = await request(
    `${config.apiBaseUrl}/github/keyboard-files/${encodeURIComponent(installation.id)}/${encodeURIComponent(repositories[0].full_name)}`,
    { headers: { Authorization: `Bearer ${localStorage.auth_token}`} }
  ).then(res => res.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(layout, keymap) {
  const installationId = encodeURIComponent(installation.id)
  const repository = encodeURIComponent(repositories[0].full_name)
  const url = `${config.apiBaseUrl}/github/keyboard-files/${installationId}/${repository}`

  return request(url, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ layout, keymap })
  })
}