carbon/build/static/sync/sync.js

63 lines
1.3 KiB
JavaScript
Raw Normal View History

import {store} from "../store/store.js"
import * as lsm from "../lsm.js"
let lastBatch = null
function sync() {
const url = new URL(`${lsm.get("domain")}/_matrix/client/r0/sync`)
url.searchParams.append("access_token", lsm.get("access_token"))
const filter = {
room: {
// pulling more from the timeline massively increases download size
timeline: {
limit: 5
},
// members are not currently needed
state: {
lazy_load_members: true
}
},
presence: {
// presence is not implemented, ignore it
types: []
}
}
url.searchParams.append("filter", JSON.stringify(filter))
url.searchParams.append("timeout", 20000)
if (lastBatch) {
url.searchParams.append("since", lastBatch)
}
return fetch(url.toString()).then(res => res.json()).then(root => {
lastBatch = root.next_batch
return root
})
}
function manageSync(root) {
try {
// set up directs
const directs = root.account_data.events.find(e => e.type === "m.direct")
if (directs) {
Object.values(directs.content).forEach(ids => {
ids.forEach(id => store.directs.add(id))
})
}
// set up rooms
Object.entries(root.rooms.join).forEach(([id, room]) => {
if (!store.rooms.has(id)) {
store.rooms.askAdd(id, room)
}
})
} catch (e) {
console.error(root)
throw e
}
}
function syncLoop() {
return sync().then(manageSync).then(syncLoop)
}
syncLoop()