Debian Codegraph @

event/content.go

raw
1 // Copyright (c) 2021 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package event
8
9 import (
10 "encoding/gob"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "reflect"
15 )
16
17 // TypeMap is a mapping from event type to the content struct type.
18 // This is used by Content.ParseRaw() for creating the correct type of struct.
19 var TypeMap = map[Type]reflect.Type{
20 StateMember: reflect.TypeOf(MemberEventContent{}),
21 StatePowerLevels: reflect.TypeOf(PowerLevelsEventContent{}),
22 StateCanonicalAlias: reflect.TypeOf(CanonicalAliasEventContent{}),
23 StateRoomName: reflect.TypeOf(RoomNameEventContent{}),
24 StateRoomAvatar: reflect.TypeOf(RoomAvatarEventContent{}),
25 StateServerACL: reflect.TypeOf(ServerACLEventContent{}),
26 StateTopic: reflect.TypeOf(TopicEventContent{}),
27 StateTombstone: reflect.TypeOf(TombstoneEventContent{}),
28 StateCreate: reflect.TypeOf(CreateEventContent{}),
29 StateJoinRules: reflect.TypeOf(JoinRulesEventContent{}),
30 StateHistoryVisibility: reflect.TypeOf(HistoryVisibilityEventContent{}),
31 StateGuestAccess: reflect.TypeOf(GuestAccessEventContent{}),
32 StatePinnedEvents: reflect.TypeOf(PinnedEventsEventContent{}),
33 StatePolicyRoom: reflect.TypeOf(ModPolicyContent{}),
34 StatePolicyServer: reflect.TypeOf(ModPolicyContent{}),
35 StatePolicyUser: reflect.TypeOf(ModPolicyContent{}),
36 StateEncryption: reflect.TypeOf(EncryptionEventContent{}),
37 StateBridge: reflect.TypeOf(BridgeEventContent{}),
38 StateHalfShotBridge: reflect.TypeOf(BridgeEventContent{}),
39 StateSpaceParent: reflect.TypeOf(SpaceParentEventContent{}),
40 StateSpaceChild: reflect.TypeOf(SpaceChildEventContent{}),
41
42 EventMessage: reflect.TypeOf(MessageEventContent{}),
43 EventSticker: reflect.TypeOf(MessageEventContent{}),
44 EventEncrypted: reflect.TypeOf(EncryptedEventContent{}),
45 EventRedaction: reflect.TypeOf(RedactionEventContent{}),
46 EventReaction: reflect.TypeOf(ReactionEventContent{}),
47
48 AccountDataRoomTags: reflect.TypeOf(TagEventContent{}),
49 AccountDataDirectChats: reflect.TypeOf(DirectChatsEventContent{}),
50 AccountDataFullyRead: reflect.TypeOf(FullyReadEventContent{}),
51 AccountDataIgnoredUserList: reflect.TypeOf(IgnoredUserListEventContent{}),
52
53 EphemeralEventTyping: reflect.TypeOf(TypingEventContent{}),
54 EphemeralEventReceipt: reflect.TypeOf(ReceiptEventContent{}),
55 EphemeralEventPresence: reflect.TypeOf(PresenceEventContent{}),
56
57 InRoomVerificationStart: reflect.TypeOf(VerificationStartEventContent{}),
58 InRoomVerificationReady: reflect.TypeOf(VerificationReadyEventContent{}),
59 InRoomVerificationAccept: reflect.TypeOf(VerificationAcceptEventContent{}),
60 InRoomVerificationKey: reflect.TypeOf(VerificationKeyEventContent{}),
61 InRoomVerificationMAC: reflect.TypeOf(VerificationMacEventContent{}),
62 InRoomVerificationCancel: reflect.TypeOf(VerificationCancelEventContent{}),
63
64 ToDeviceRoomKey: reflect.TypeOf(RoomKeyEventContent{}),
65 ToDeviceForwardedRoomKey: reflect.TypeOf(ForwardedRoomKeyEventContent{}),
66 ToDeviceRoomKeyRequest: reflect.TypeOf(RoomKeyRequestEventContent{}),
67 ToDeviceEncrypted: reflect.TypeOf(EncryptedEventContent{}),
68 ToDeviceRoomKeyWithheld: reflect.TypeOf(RoomKeyWithheldEventContent{}),
69 ToDeviceDummy: reflect.TypeOf(DummyEventContent{}),
70
71 ToDeviceVerificationStart: reflect.TypeOf(VerificationStartEventContent{}),
72 ToDeviceVerificationAccept: reflect.TypeOf(VerificationAcceptEventContent{}),
73 ToDeviceVerificationKey: reflect.TypeOf(VerificationKeyEventContent{}),
74 ToDeviceVerificationMAC: reflect.TypeOf(VerificationMacEventContent{}),
75 ToDeviceVerificationCancel: reflect.TypeOf(VerificationCancelEventContent{}),
76 ToDeviceVerificationRequest: reflect.TypeOf(VerificationRequestEventContent{}),
77
78 ToDeviceOrgMatrixRoomKeyWithheld: reflect.TypeOf(RoomKeyWithheldEventContent{}),
79
80 CallInvite: reflect.TypeOf(CallInviteEventContent{}),
81 CallCandidates: reflect.TypeOf(CallCandidatesEventContent{}),
82 CallAnswer: reflect.TypeOf(CallAnswerEventContent{}),
83 CallReject: reflect.TypeOf(CallRejectEventContent{}),
84 CallSelectAnswer: reflect.TypeOf(CallSelectAnswerEventContent{}),
85 CallNegotiate: reflect.TypeOf(CallNegotiateEventContent{}),
86 CallHangup: reflect.TypeOf(CallHangupEventContent{}),
87 }
88
89 // Content stores the content of a Matrix event.
90 //
91 // By default, the raw JSON bytes are stored in VeryRaw and parsed into a map[string]interface{} in the Raw field.
92 // Additionally, you can call ParseRaw with the correct event type to parse the (VeryRaw) content into a nicer struct,
93 // which you can then access from Parsed or via the helper functions.
94 //
95 // When being marshaled into JSON, the data in Parsed will be marshaled first and then recursively merged
96 // with the data in Raw. Values in Raw are preferred, but nested objects will be recursed into before merging,
97 // rather than overriding the whole object with the one in Raw).
98 // If one of them is nil, the only the other is used. If both (Parsed and Raw) are nil, VeryRaw is used instead.
99 type Content struct {
100 VeryRaw json.RawMessage
101 Raw map[string]interface{}
102 Parsed interface{}
103 }
104
105 type Relatable interface {
106 GetRelatesTo() *RelatesTo
107 OptionalGetRelatesTo() *RelatesTo
108 SetRelatesTo(rel *RelatesTo)
109 }
110
111 func (content *Content) UnmarshalJSON(data []byte) error {
112 content.VeryRaw = data
113 err := json.Unmarshal(data, &content.Raw)
114 return err
115 }
116
117 func (content *Content) MarshalJSON() ([]byte, error) {
118 if content.Raw == nil {
119 if content.Parsed == nil {
120 if content.VeryRaw == nil {
121 return []byte("{}"), nil
122 }
123 return content.VeryRaw, nil
124 }
125 return json.Marshal(content.Parsed)
126 } else if content.Parsed != nil {
127 // TODO this whole thing is incredibly hacky
128 // It needs to produce JSON, where:
129 // * content.Parsed is applied after content.Raw
130 // * MarshalJSON() is respected inside content.Parsed
131 // * Custom field inside nested objects of content.Raw are preserved,
132 // even if content.Parsed contains the higher-level objects.
133 // * content.Raw is not modified
134
135 unparsed, err := json.Marshal(content.Parsed)
136 if err != nil {
137 return nil, err
138 }
139
140 var rawParsed map[string]interface{}
141 err = json.Unmarshal(unparsed, &rawParsed)
142 if err != nil {
143 return nil, err
144 }
145
146 output := make(map[string]interface{})
147 for key, value := range content.Raw {
148 output[key] = value
149 }
150
151 mergeMaps(output, rawParsed)
152 return json.Marshal(output)
153 }
154 return json.Marshal(content.Raw)
155 }
156
157 func IsUnsupportedContentType(err error) bool {
158 return errors.Is(err, ErrUnsupportedContentType)
159 }
160
161 var ErrContentAlreadyParsed = errors.New("content is already parsed")
162 var ErrUnsupportedContentType = errors.New("unsupported event type")
163
164 func (content *Content) ParseRaw(evtType Type) error {
165 if content.Parsed != nil {
166 return ErrContentAlreadyParsed
167 }
168 structType, ok := TypeMap[evtType]
169 if !ok {
170 return fmt.Errorf("%w %s", ErrUnsupportedContentType, evtType.Repr())
171 }
172 content.Parsed = reflect.New(structType).Interface()
173 return json.Unmarshal(content.VeryRaw, &content.Parsed)
174 }
175
176 func mergeMaps(into, from map[string]interface{}) {
177 for key, newValue := range from {
178 existingValue, ok := into[key]
179 if !ok {
180 into[key] = newValue
181 continue
182 }
183 existingValueMap, okEx := existingValue.(map[string]interface{})
184 newValueMap, okNew := newValue.(map[string]interface{})
185 if okEx && okNew {
186 mergeMaps(existingValueMap, newValueMap)
187 } else {
188 into[key] = newValue
189 }
190 }
191 }
192
193 func init() {
194 gob.Register(&MemberEventContent{})
195 gob.Register(&PowerLevelsEventContent{})
196 gob.Register(&CanonicalAliasEventContent{})
197 gob.Register(&EncryptionEventContent{})
198 gob.Register(&BridgeEventContent{})
199 gob.Register(&SpaceChildEventContent{})
200 gob.Register(&SpaceParentEventContent{})
201 gob.Register(&RoomNameEventContent{})
202 gob.Register(&RoomAvatarEventContent{})
203 gob.Register(&TopicEventContent{})
204 gob.Register(&TombstoneEventContent{})
205 gob.Register(&CreateEventContent{})
206 gob.Register(&JoinRulesEventContent{})
207 gob.Register(&HistoryVisibilityEventContent{})
208 gob.Register(&GuestAccessEventContent{})
209 gob.Register(&PinnedEventsEventContent{})
210 gob.Register(&MessageEventContent{})
211 gob.Register(&MessageEventContent{})
212 gob.Register(&EncryptedEventContent{})
213 gob.Register(&RedactionEventContent{})
214 gob.Register(&ReactionEventContent{})
215 gob.Register(&TagEventContent{})
216 gob.Register(&DirectChatsEventContent{})
217 gob.Register(&FullyReadEventContent{})
218 gob.Register(&IgnoredUserListEventContent{})
219 gob.Register(&TypingEventContent{})
220 gob.Register(&ReceiptEventContent{})
221 gob.Register(&PresenceEventContent{})
222 gob.Register(&RoomKeyEventContent{})
223 gob.Register(&ForwardedRoomKeyEventContent{})
224 gob.Register(&RoomKeyRequestEventContent{})
225 gob.Register(&RoomKeyWithheldEventContent{})
226 }
227
228 // Helper cast functions below
229
230 func (content *Content) AsMember() *MemberEventContent {
231 casted, ok := content.Parsed.(*MemberEventContent)
232 if !ok {
233 return &MemberEventContent{}
234 }
235 return casted
236 }
237 func (content *Content) AsPowerLevels() *PowerLevelsEventContent {
238 casted, ok := content.Parsed.(*PowerLevelsEventContent)
239 if !ok {
240 return &PowerLevelsEventContent{}
241 }
242 return casted
243 }
244 func (content *Content) AsCanonicalAlias() *CanonicalAliasEventContent {
245 casted, ok := content.Parsed.(*CanonicalAliasEventContent)
246 if !ok {
247 return &CanonicalAliasEventContent{}
248 }
249 return casted
250 }
251 func (content *Content) AsRoomName() *RoomNameEventContent {
252 casted, ok := content.Parsed.(*RoomNameEventContent)
253 if !ok {
254 return &RoomNameEventContent{}
255 }
256 return casted
257 }
258 func (content *Content) AsRoomAvatar() *RoomAvatarEventContent {
259 casted, ok := content.Parsed.(*RoomAvatarEventContent)
260 if !ok {
261 return &RoomAvatarEventContent{}
262 }
263 return casted
264 }
265 func (content *Content) AsTopic() *TopicEventContent {
266 casted, ok := content.Parsed.(*TopicEventContent)
267 if !ok {
268 return &TopicEventContent{}
269 }
270 return casted
271 }
272 func (content *Content) AsTombstone() *TombstoneEventContent {
273 casted, ok := content.Parsed.(*TombstoneEventContent)
274 if !ok {
275 return &TombstoneEventContent{}
276 }
277 return casted
278 }
279 func (content *Content) AsCreate() *CreateEventContent {
280 casted, ok := content.Parsed.(*CreateEventContent)
281 if !ok {
282 return &CreateEventContent{}
283 }
284 return casted
285 }
286 func (content *Content) AsJoinRules() *JoinRulesEventContent {
287 casted, ok := content.Parsed.(*JoinRulesEventContent)
288 if !ok {
289 return &JoinRulesEventContent{}
290 }
291 return casted
292 }
293 func (content *Content) AsHistoryVisibility() *HistoryVisibilityEventContent {
294 casted, ok := content.Parsed.(*HistoryVisibilityEventContent)
295 if !ok {
296 return &HistoryVisibilityEventContent{}
297 }
298 return casted
299 }
300 func (content *Content) AsGuestAccess() *GuestAccessEventContent {
301 casted, ok := content.Parsed.(*GuestAccessEventContent)
302 if !ok {
303 return &GuestAccessEventContent{}
304 }
305 return casted
306 }
307 func (content *Content) AsPinnedEvents() *PinnedEventsEventContent {
308 casted, ok := content.Parsed.(*PinnedEventsEventContent)
309 if !ok {
310 return &PinnedEventsEventContent{}
311 }
312 return casted
313 }
314 func (content *Content) AsEncryption() *EncryptionEventContent {
315 casted, ok := content.Parsed.(*EncryptionEventContent)
316 if !ok {
317 return &EncryptionEventContent{}
318 }
319 return casted
320 }
321 func (content *Content) AsBridge() *BridgeEventContent {
322 casted, ok := content.Parsed.(*BridgeEventContent)
323 if !ok {
324 return &BridgeEventContent{}
325 }
326 return casted
327 }
328 func (content *Content) AsSpaceChild() *SpaceChildEventContent {
329 casted, ok := content.Parsed.(*SpaceChildEventContent)
330 if !ok {
331 return &SpaceChildEventContent{}
332 }
333 return casted
334 }
335 func (content *Content) AsSpaceParent() *SpaceParentEventContent {
336 casted, ok := content.Parsed.(*SpaceParentEventContent)
337 if !ok {
338 return &SpaceParentEventContent{}
339 }
340 return casted
341 }
342 func (content *Content) AsMessage() *MessageEventContent {
343 casted, ok := content.Parsed.(*MessageEventContent)
344 if !ok {
345 return &MessageEventContent{}
346 }
347 return casted
348 }
349 func (content *Content) AsEncrypted() *EncryptedEventContent {
350 casted, ok := content.Parsed.(*EncryptedEventContent)
351 if !ok {
352 return &EncryptedEventContent{}
353 }
354 return casted
355 }
356 func (content *Content) AsRedaction() *RedactionEventContent {
357 casted, ok := content.Parsed.(*RedactionEventContent)
358 if !ok {
359 return &RedactionEventContent{}
360 }
361 return casted
362 }
363 func (content *Content) AsReaction() *ReactionEventContent {
364 casted, ok := content.Parsed.(*ReactionEventContent)
365 if !ok {
366 return &ReactionEventContent{}
367 }
368 return casted
369 }
370 func (content *Content) AsTag() *TagEventContent {
371 casted, ok := content.Parsed.(*TagEventContent)
372 if !ok {
373 return &TagEventContent{}
374 }
375 return casted
376 }
377 func (content *Content) AsDirectChats() *DirectChatsEventContent {
378 casted, ok := content.Parsed.(*DirectChatsEventContent)
379 if !ok {
380 return &DirectChatsEventContent{}
381 }
382 return casted
383 }
384 func (content *Content) AsFullyRead() *FullyReadEventContent {
385 casted, ok := content.Parsed.(*FullyReadEventContent)
386 if !ok {
387 return &FullyReadEventContent{}
388 }
389 return casted
390 }
391 func (content *Content) AsIgnoredUserList() *IgnoredUserListEventContent {
392 casted, ok := content.Parsed.(*IgnoredUserListEventContent)
393 if !ok {
394 return &IgnoredUserListEventContent{}
395 }
396 return casted
397 }
398 func (content *Content) AsTyping() *TypingEventContent {
399 casted, ok := content.Parsed.(*TypingEventContent)
400 if !ok {
401 return &TypingEventContent{}
402 }
403 return casted
404 }
405 func (content *Content) AsReceipt() *ReceiptEventContent {
406 casted, ok := content.Parsed.(*ReceiptEventContent)
407 if !ok {
408 return &ReceiptEventContent{}
409 }
410 return casted
411 }
412 func (content *Content) AsPresence() *PresenceEventContent {
413 casted, ok := content.Parsed.(*PresenceEventContent)
414 if !ok {
415 return &PresenceEventContent{}
416 }
417 return casted
418 }
419 func (content *Content) AsRoomKey() *RoomKeyEventContent {
420 casted, ok := content.Parsed.(*RoomKeyEventContent)
421 if !ok {
422 return &RoomKeyEventContent{}
423 }
424 return casted
425 }
426 func (content *Content) AsForwardedRoomKey() *ForwardedRoomKeyEventContent {
427 casted, ok := content.Parsed.(*ForwardedRoomKeyEventContent)
428 if !ok {
429 return &ForwardedRoomKeyEventContent{}
430 }
431 return casted
432 }
433 func (content *Content) AsRoomKeyRequest() *RoomKeyRequestEventContent {
434 casted, ok := content.Parsed.(*RoomKeyRequestEventContent)
435 if !ok {
436 return &RoomKeyRequestEventContent{}
437 }
438 return casted
439 }
440 func (content *Content) AsRoomKeyWithheld() *RoomKeyWithheldEventContent {
441 casted, ok := content.Parsed.(*RoomKeyWithheldEventContent)
442 if !ok {
443 return &RoomKeyWithheldEventContent{}
444 }
445 return casted
446 }
447 func (content *Content) AsCallInvite() *CallInviteEventContent {
448 casted, ok := content.Parsed.(*CallInviteEventContent)
449 if !ok {
450 return &CallInviteEventContent{}
451 }
452 return casted
453 }
454 func (content *Content) AsCallCandidates() *CallCandidatesEventContent {
455 casted, ok := content.Parsed.(*CallCandidatesEventContent)
456 if !ok {
457 return &CallCandidatesEventContent{}
458 }
459 return casted
460 }
461 func (content *Content) AsCallAnswer() *CallAnswerEventContent {
462 casted, ok := content.Parsed.(*CallAnswerEventContent)
463 if !ok {
464 return &CallAnswerEventContent{}
465 }
466 return casted
467 }
468 func (content *Content) AsCallReject() *CallRejectEventContent {
469 casted, ok := content.Parsed.(*CallRejectEventContent)
470 if !ok {
471 return &CallRejectEventContent{}
472 }
473 return casted
474 }
475 func (content *Content) AsCallSelectAnswer() *CallSelectAnswerEventContent {
476 casted, ok := content.Parsed.(*CallSelectAnswerEventContent)
477 if !ok {
478 return &CallSelectAnswerEventContent{}
479 }
480 return casted
481 }
482 func (content *Content) AsCallNegotiate() *CallNegotiateEventContent {
483 casted, ok := content.Parsed.(*CallNegotiateEventContent)
484 if !ok {
485 return &CallNegotiateEventContent{}
486 }
487 return casted
488 }
489 func (content *Content) AsCallHangup() *CallHangupEventContent {
490 casted, ok := content.Parsed.(*CallHangupEventContent)
491 if !ok {
492 return &CallHangupEventContent{}
493 }
494 return casted
495 }
496 func (content *Content) AsModPolicy() *ModPolicyContent {
497 casted, ok := content.Parsed.(*ModPolicyContent)
498 if !ok {
499 return &ModPolicyContent{}
500 }
501 return casted
502 }