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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
|
import Auth from './src/auth.js'
//import Collection from './src/collection.js'
export default class {
// There needs to be a new object map for each tag
constructor(
graffitiURL="https://graffiti.garden",
objectMapConstructor=()=>({})) {
this.graffitiURL = graffitiURL
this.objectMapConstructor = objectMapConstructor
this.open = false
this.eventTarget = new EventTarget()
this.tagMap = {}
this.#initialize()
}
async #initialize() {
// Perform authorization
this.authParams = await Auth.connect(this.graffitiURL)
// Rewrite the URL
this.wsURL = new URL(this.graffitiURL)
this.wsURL.host = "app." + this.wsURL.host
if (this.wsURL.protocol == 'https:') {
this.wsURL.protocol = 'wss:'
} else {
this.wsURL.protocol = 'ws:'
}
if (this.authParams.token) {
this.wsURL.searchParams.set("token", this.authParams.token)
}
// Commence connection
this.#connect()
}
async opened() {
if (!this.open) {
await new Promise(resolve => {
this.eventTarget.addEventListener("graffitiOpen", () => resolve() )
})
}
}
#connect() {
this.ws = new WebSocket(this.wsURL)
this.ws.onmessage = this.#onMessage.bind(this)
this.ws.onclose = this.#onClose.bind(this)
this.ws.onopen = this.#onOpen.bind(this)
}
// authorization functions
get myID() { return this.authParams.myID }
toggleLogIn() {
this.myID? Auth.logOut() : Auth.logIn(this.graffitiURL)
}
async #onClose() {
this.open = false
console.error("lost connection to graffiti server, attemping reconnect soon...")
await new Promise(resolve => setTimeout(resolve, 2000))
this.#connect()
}
async #request(msg) {
if (!this.open) {
throw { 'error': 'Not connected!' }
}
// Create a random message ID
const messageID = crypto.randomUUID()
// Create a listener for the reply
const dataPromise = new Promise(resolve => {
this.eventTarget.addEventListener(messageID, (e) => {
resolve(e.data)
})
})
// Send the request
msg.messageID = messageID
this.ws.send(JSON.stringify(msg))
// Await the reply
const data = await dataPromise
delete data.messageID
if (data.type == 'error') {
throw data
} else {
return data['reply']
}
}
#onMessage(event) {
const data = JSON.parse(event.data)
if ('messageID' in data) {
// It's a reply
// Forward it back to the sender
const messageEvent = new Event(data.messageID)
messageEvent.data = data
this.eventTarget.dispatchEvent(messageEvent)
} else if ('update' in data) {
this.#updateCallback(data['update'])
} else if ('remove' in data) {
this.#removeCallback(data['remove'])
} else if (data.type == 'error') {
if (data.reason == 'authorization') {
Auth.logOut()
}
throw data
}
}
#updateCallback(object) {
const uuid = this.#objectUUID(object)
let originalObject = null
for (const tag of object._tags) {
if (!(tag in this.tagMap)) continue
const objectMap = this.tagMap[tag].objectMap
if (uuid in objectMap) {
// Copy the original object if
// one exists, in case of failure
originalObject = Object.assign({},objectMap[uuid])
// Replace the object by copying
// so references to it don't break
this.#recursiveCopy(objectMap[uuid], object)
} else {
// Add properties to the object
// so it can be updated and removed
// without the collection
Object.defineProperty(object, '_update', { value: ()=>this.update(object) })
Object.defineProperty(object, '_remove', { value: ()=>this.remove(object) })
objectMap[uuid] = object
}
}
// Return the original in case of failure
return originalObject
}
#removeCallback(object) {
const uuid = this.#objectUUID(object)
let originalObject = null
for (const tag of object._tags) {
if (!(tag in this.tagMap)) continue
const objectMap = this.tagMap[tag].objectMap
if (!(uuid in objectMap)) return
originalObject = Object.assign({},objectMap[uuid])
delete objectMap[uuid]
}
}
async update(object) {
if (!this.myID) {
throw 'you can\'t update objects without logging in!'
}
// Add by/to fields
object._by = this.myID
if ('_to' in object && !Array.isArray(object._to)) {
throw new Error("_to must be an array")
}
// Pre-generate the object's ID if it does not already exist
if (!object._key) object._key = crypto.randomUUID()
// Immediately replace the object
const originalObject = this.#updateCallback(object)
// Send it to the server
try {
await this.#request({ update: object })
} catch(e) {
if (originalObject) {
// Restore the original object
this.#updateCallback(originalObject)
} else {
// Delete the temp object
this.#removeCallback(object)
}
throw e
}
}
async remove(object) {
if (!this.myID) {
throw 'you can\'t remove objects without logging in!'
}
if (this.myID != object._by) {
throw 'you can\'t remove an object that isn\'t yours!'
}
// Immediately remove the object
// but store it in case there is an error
const originalObject = this.#removeCallback(object)
try {
return await this.#request({ remove: object._key })
} catch(e) {
// Delete failed, restore the object
if (originalObject) this.#updateCallback(originalObject)
throw e
}
}
async myTags() {
return await this.#request({ ls: null })
}
async objectByKey(userID, objectKey) {
return await this.#request({ get: {
_by: userID,
_key: objectKey
}})
}
objectsByTags(...tags) {
for (const tag of tags) {
if (!(tag in this.tagMap)) {
throw `You are not subscribed to '${tag}'`
}
}
// Merge by UUID to combine all the maps
const combinedMaps = Object.assign({},
...tags.map(tag=> this.tagMap[tag].objectMap))
// Return just the array
return Object.values(combinedMaps)
}
async subscribe(...tags) {
// Look at what is already subscribed to
const subscribingTags = []
for (const tag of tags) {
if (tag in this.tagMap) {
// Increase the count
this.tagMap[tag].count++
} else {
// Create a new slot
this.tagMap[tag] = {
objectMap: this.objectMapConstructor(),
count: 1
}
subscribingTags.push(tag)
}
}
// Begin subscribing in the background
if (subscribingTags.length)
await this.#request({ subscribe: subscribingTags })
}
async unsubscribe(...tags) {
// Decrease the count of each tag,
// removing and marking if necessary
const unsubscribingTags = []
for (const tag of tags) {
this.tagMap[tag].count--
if (!this.tagMap[tag].count) {
unsubscribingTags.push(tag)
delete this.tagMap[tag]
}
}
// Unsubscribe from all remaining tags
if (unsubscribingTags.length)
await this.#request({ unsubscribe: unsubscribingTags })
}
async #onOpen() {
console.log("connected to the graffiti socket")
this.open = true
this.eventTarget.dispatchEvent(new Event("graffitiOpen"))
// Clear data
for (let tag in this.tagMap) {
const objectMap = this.tagMap[tag].objectMap
for (let uuid in objectMap) delete objectMap[uuid]
}
// Resubscribe
const tags = Object.keys(this.tagMap)
if (tags.length) await this.#request({ subscribe: tags })
}
// Utility function to get a universally unique string
// that represents a particular object
#objectUUID(object) {
if (!object._by || !object._key) {
throw {
type: 'error',
content: 'the object you are trying to identify does not have an owner or key',
object
}
}
return object._by + object._key
}
#recursiveCopy(target, source) {
for (const field in target) {
if (!(field in source)) {
delete target[field]
}
}
for (const field in source) {
if (field in target && typeof target[field] == 'object' && typeof source[field] == 'object') {
this.#recursiveCopy(target[field], source[field])
} else {
target[field] = source[field]
}
}
}
}
|