~f4814n/frost

ref: e08ed4ce4543d93070e70e2a427e46b9e5c0be81 frost/view/roomhistory/roomhistory.go -rw-r--r-- 7.2 KiB
e08ed4ceFabian Geiselhart Update README 3 months ago
                                                                                
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
package roomhistory

import (
	"errors"
	"fmt"
	"sync"

	fwidget "git.sr.ht/~f4814n/frost/widget"

	"gioui.org/layout"
	"gioui.org/unit"
	"git.sr.ht/~f4814n/frost"
	"git.sr.ht/~f4814n/matrix"
	"go.uber.org/zap"
)

type (
	g = layout.Context
	d = layout.Dimensions
)

type sentRoomEvent struct {
	Err error
}

func (e sentRoomEvent) FrostEvent() {}

type view struct {
	sync.Mutex

	rx, tx chan frost.Event

	theme fwidget.Theme

	matrixEvents chan matrix.Event
	pastEvents   chan matrix.Event

	self    matrix.User
	room    matrix.Room
	history matrix.History

	list   *layout.List
	events []interface{} // TODO Concrete type. Is either message or statusMessage

	messageComposer *messageComposer

	logger *zap.Logger
}

type message struct {
	fwidget.Message
	event   matrix.RoomEvent
	invalid bool
}

type statusMessage struct {
	fwidget.StatusMessage
	event   matrix.StateEvent
	invalid bool
}

func New(self matrix.User, room matrix.Room, theme fwidget.Theme, logger *zap.Logger) frost.View {
	view := &view{
		matrixEvents:    make(chan matrix.Event, 100),
		pastEvents:      make(chan matrix.Event, 100),
		room:            room,
		self:            self,
		list:            &layout.List{Axis: layout.Vertical, ScrollToEnd: true},
		history:         room.History(),
		logger:          logger,
		theme:           theme,
		messageComposer: newMessageComposer(),
	}

	return view
}

func (r *view) Run(rx, tx chan frost.Event) {
	r.logger.Info("Showing room", zap.String("id", r.room.ID))

	r.rx, r.tx = rx, tx

	r.room.Notify(r.matrixEvents)

	// TODO Only load history which is actually needed
	go func() {
		for r.history.Next() {
			if r.history.Err != nil {
				r.logger.Warn("Error while traversing history", zap.Error(r.history.Err))
				// We probably have insufficient permissions for viewing the history
				// so let's not retry
				if errors.As(r.history.Err, &matrix.LogicError{}) {
					break
				}
				continue
			}

			for _, e := range r.history.Events {
				r.pastEvents <- e
			}
		}
	}()

	for {
		select {
		case event := <-r.rx:
			switch event := event.(type) {
			case sentRoomEvent:
				r.Lock()
				r.messageComposer.Reenable(event.Err)
				r.Unlock()
			}
		case event := <-r.matrixEvents:
			switch event.(type) {
			case matrix.RoomEvent:
				r.addEvent(event, true)
			case matrix.StateEvent:
				r.addEvent(event, true)
			}
		case event := <-r.pastEvents:
			r.addEvent(event, false)
		}
	}
}

func (r *view) addEvent(event matrix.Event, appendToEnd bool) {
	switch event := event.(type) {
	case matrix.RoomEvent:
		e := message{
			Message: fwidget.Message{
				Time:   event.OriginServerTS,
				Sender: event.Sender.Displayname(),
			},
			event: event,
		}

		if event.Type == "m.room.encrypted" {
			var err error
			event, err = event.Decrypt()
			if err != nil {
				e.invalid = true
				e.Text = err.Error()
			}
		}

		if body, ok := event.Content["body"]; event.Type == "m.room.message" && ok {
			e.Text = body.(string)
		} else if e.Text != "" {
			e.invalid = true
			e.Text = "unformattable"
		}

		if appendToEnd {
			r.events = append(r.events, e)
		} else {
			r.events = append([]interface{}{e}, r.events...)
		}
	case matrix.StateEvent:
		text, invalid := statusEventText(event)
		e := statusMessage{
			StatusMessage: fwidget.StatusMessage{
				Text: text,
			},
			event:   event,
			invalid: invalid,
		}

		if appendToEnd {
			r.events = append(r.events, e)
		} else {
			r.events = append([]interface{}{e}, r.events...)
		}
	default:
		panic("Invalid event added")
	}
}

func (r *view) update(gtx g) {
	if r.messageComposer.Submitted() {
		r.messageComposer.Disable()

		go func() {
			_, err := r.room.SendRoomEvent("m.room.message", map[string]interface{}{
				"body":    r.messageComposer.Text(),
				"msgtype": "m.text",
			})
			r.rx <- sentRoomEvent{Err: err}
		}()
	}
}

func (r *view) Stop() {
}

func (r *view) Layout(gtx g) d {
	r.Lock()
	defer r.Unlock()

	r.update(gtx)

	return layout.Flex{Alignment: layout.Start, Axis: layout.Vertical}.Layout(gtx,
		layout.Flexed(1, r.layoutHistory),
		layout.Rigid(func(gtx g) d {
			in := layout.Inset{
				Top:    unit.Dp(8),
				Left:   unit.Dp(8),
				Right:  unit.Dp(8),
				Bottom: unit.Dp(4),
			}

			return in.Layout(gtx,
				fwidget.LayoutTheme(
					r.messageComposer.Layout,
					r.theme.WithContrast(fwidget.PrimaryDefault),
				),
			)
		}),
	)
}

func (r *view) layoutHistory(gtx g) d {
	return r.list.Layout(gtx, len(r.events), func(gtx g, index int) d {
		in := layout.Inset{Top: unit.Dp(16), Left: unit.Dp(16), Right: unit.Dp(40)}

		switch message := r.events[index].(type) {
		case message:
			theme := r.theme.WithContrast(fwidget.PrimaryDark)
			align := layout.W

			if message.event.Sender.User == r.self {
				theme = r.theme.WithContrast(fwidget.SecondaryDefault)
				align = layout.E
			}

			if message.invalid {
				theme = r.theme.WithContrast(fwidget.Error)
			}

			return in.Layout(gtx, func(gtx g) d {
				return align.Layout(gtx, fwidget.LayoutTheme(message.Layout, theme))
			})
		case statusMessage:
			theme := r.theme.WithContrast(fwidget.Accent)
			align := layout.Center

			if message.invalid {
				theme = r.theme.WithContrast(fwidget.Error)
			}

			return in.Layout(gtx, func(gtx g) d {
				return align.Layout(gtx, fwidget.LayoutTheme(message.Layout, theme))
			})
		default:
			panic("invalid type in list of events")
		}
	})
}

func statusEventText(ev matrix.StateEvent) (string, bool) {
	senderName := ev.Sender.Displayname()

	var (
		text    string
		invalid bool
	)

	switch ev.Type {
	case "m.room.member":
		text = fmt.Sprintf("%s changed their profile", ev.StateKey)
	case "m.room.create":
		text = fmt.Sprintf("%s created the room", senderName)
	case "m.room.power_levels":
		text = fmt.Sprintf("Room power levels were changed by %s", senderName)
	case "m.room.join_rules":
		text = fmt.Sprintf("Join rules were changed by %s", senderName)
	case "m.room.name":
		text = fmt.Sprintf("%s changed the room name to \"%s\"", senderName, ev.Room.Displayname())
	case "m.room.topic":
		var str string
		if topic, ok := ev.Content["topic"]; ok {
			str = fmt.Sprintf("%s changed the room topic to \"%s\"", senderName, topic)
		} else {
			str = fmt.Sprintf("%s removed the room topic", senderName)
		}
		text = str
	case "m.room.guest_access":
		var str string
		if access, ok := ev.Content["guest_access"]; ok && access == "can_join" || access == "forbidden" {
			if access == "can_join" {
				str = fmt.Sprintf("%s allowed guest to join", senderName)
			} else {
				str = fmt.Sprintf("%s disallowed guests to join", senderName)
			}
		} else {
			str = "[Unformattable Event]"
			invalid = true
		}
		text = str
	case "m.room.history_visibility":
		var str string
		if access, ok := ev.Content["history_visibility"]; ok {
			str = fmt.Sprintf("%s set the history visibility to \"%s\"", senderName, access)
		} else {
			str = "[Unformattable Event]"
			invalid = true
		}
		text = str
	case "m.room.canonical_alias":
		var str string
		if alias, ok := ev.Content["canonical_alias"]; ok {
			str = fmt.Sprintf("%s changed the canonical alias to \"%s\"", senderName, alias)
		} else {
			str = fmt.Sprintf("%s set no or removed the canonical alias", senderName)
		}
		text = str
	default:
		invalid = true
		text = "[Unformattable Event]"
	}

	return text, invalid
}