-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
80 lines (73 loc) · 2.5 KB
/
index.mjs
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
import { HttpAPI } from './src/http-api.mjs'
import { StructureAPI } from './src/structure-api.mjs'
import { TimelineAPI } from './src/timeline-api.mjs'
import { CommandAPI } from './src/command-api.mjs'
import { ProjectList } from './src/project-list.mjs'
import { Project } from './src/project.mjs'
import { discover, errors } from './src/discover-api.mjs'
import { chill } from './src/convenience.mjs'
/*
connect() resolves if the home_server can be connected. It does
not fail but tries to connect endlessly
*/
const connect = (home_server_url) => async (controller) => {
const MAX_CHILL_FACTOR = 64
let chillFactor = 0
let connected = false
while (!connected || controller?.signal?.aborted) {
await chill(chillFactor, controller?.signal)
try {
await discover({ home_server_url })
connected = true
} catch (error) {
if (error.name === 'AbortError') throw error
if (error.code === errors.FAIL_PROMPT) {
connected = true
continue
}
if (chillFactor < MAX_CHILL_FACTOR) chillFactor++
}
}
}
/**
* @typedef {Object} LoginData
* @property {String} user_id
* @property {String} password
* @property {String} home_server_url
*
* @param {LoginData} loginData
* @returns {Object} matrixClient
*/
const MatrixClient = (loginData) => ({
connect: connect(loginData.home_server_url),
projectList: async mostRecentCredentials => {
const credentials = mostRecentCredentials ? mostRecentCredentials : (await HttpAPI.loginWithPassword(loginData))
const httpAPI = new HttpAPI(credentials)
const projectListParames = {
structureAPI: new StructureAPI(httpAPI),
timelineAPI: new TimelineAPI(httpAPI)
}
const projectList = new ProjectList(projectListParames)
projectList.tokenRefreshed = handler => httpAPI.tokenRefreshed(handler)
projectList.credentials = () => (httpAPI.credentials)
return projectList
},
project: async mostRecentCredentials => {
const credentials = mostRecentCredentials ? mostRecentCredentials : (await HttpAPI.loginWithPassword(loginData))
const httpAPI = new HttpAPI(credentials)
const projectParams = {
structureAPI: new StructureAPI(httpAPI),
timelineAPI: new TimelineAPI(httpAPI),
commandAPI: new CommandAPI(httpAPI)
}
const project = new Project(projectParams)
project.tokenRefreshed = handler => httpAPI.tokenRefreshed(handler)
project.credentials = () => (httpAPI.credentials)
return project
}
})
export {
MatrixClient,
connect,
discover
}