pinafore/routes/_api/TimelineStream.js

71 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-02-08 17:22:14 +01:00
import { paramsString } from '../_utils/ajax'
import noop from 'lodash-es/noop'
2018-02-11 22:46:57 +01:00
import { importWebSocketClient } from '../_utils/asyncModules'
2018-01-25 18:03:34 +01:00
2018-02-09 07:29:29 +01:00
function getStreamName (timeline) {
2018-01-25 18:03:34 +01:00
switch (timeline) {
case 'local':
return 'public:local'
case 'federated':
return 'public'
case 'home':
return 'user'
case 'notifications':
return 'user:notification'
}
if (timeline.startsWith('tag/')) {
return 'hashtag'
}
2018-02-11 22:46:57 +01:00
if (timeline.startsWith('list/')) {
return 'list'
}
2018-01-25 18:03:34 +01:00
}
2018-02-09 07:29:29 +01:00
function getUrl (streamingApi, accessToken, timeline) {
2018-01-25 18:03:34 +01:00
let url = `${streamingApi}/api/v1/streaming`
let streamName = getStreamName(timeline)
let params = {
stream: streamName
}
if (timeline.startsWith('tag/')) {
params.tag = timeline.split('/').slice(-1)[0]
2018-02-11 22:46:57 +01:00
} else if (timeline.startsWith('list/')) {
params.list = timeline.split('/').slice(-1)[0]
2018-01-25 18:03:34 +01:00
}
if (accessToken) {
params.access_token = accessToken
}
return url + '?' + paramsString(params)
}
2018-02-11 22:46:57 +01:00
export class TimelineStream {
2018-02-09 07:29:29 +01:00
constructor (streamingApi, accessToken, timeline, opts) {
2018-01-25 18:03:34 +01:00
let url = getUrl(streamingApi, accessToken, timeline)
2018-02-11 22:46:57 +01:00
importWebSocketClient().then(WebSocketClient => {
if (this.__closed) {
return
}
const ws = new WebSocketClient(url, null, { backoff: 'exponential' })
const onMessage = opts.onMessage || noop
2018-01-25 18:03:34 +01:00
2018-02-11 22:46:57 +01:00
ws.onopen = opts.onOpen || noop
ws.onmessage = e => onMessage(JSON.parse(e.data))
ws.onclose = opts.onClose || noop
ws.onreconnect = opts.onReconnect || noop
2018-01-25 18:03:34 +01:00
2018-02-11 22:46:57 +01:00
this._ws = ws
})
2018-01-25 18:03:34 +01:00
}
2018-02-09 07:29:29 +01:00
close () {
2018-02-11 22:46:57 +01:00
this.__closed = true
if (this._ws) {
this._ws.close()
}
2018-01-25 18:03:34 +01:00
}
2018-02-09 07:29:29 +01:00
}