~f4814n/frost

ref: dd5581fb05b3aa1be810685d837e9116379c18ce frost/cmd/frost/room_view.go -rw-r--r-- 13.3 KiB
dd5581fbFabian Geiselhart RoomView: Fix request spamming when history is unreadable 1 year, 9 days 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/sirupsen/logrus"
	"golang.org/x/exp/shiny/materialdesign/icons"

	"gioui.org/layout"
	"gioui.org/unit"
	"gioui.org/widget"
	"gioui.org/widget/material"
	"git.sr.ht/~f4814n/matrix"
)

type SentRoomEvent struct {
	Err error
}

type RoomView struct {
	rx, tx chan Event

	matrixEvents chan matrix.Event
	pastEvents   chan matrix.Event

	cli         *matrix.Client
	room        matrix.Room
	history     matrix.History
	roomHistory *roomHistory

	backButton     *widget.Clickable
	settingsButton *widget.Clickable
	userListButton *widget.Clickable

	messageComposer *messageComposer

	log *logrus.Entry
}

func NewRoomView(cli *matrix.Client, room matrix.Room) *RoomView {
	return &RoomView{
		cli:             cli,
		matrixEvents:    make(chan matrix.Event, 100),
		pastEvents:      make(chan matrix.Event, 100),
		room:            room,
		roomHistory:     newRoomHistory(cli.User().ID),
		history:         room.History(),
		backButton:      new(widget.Clickable),
		settingsButton:  new(widget.Clickable),
		userListButton:  new(widget.Clickable),
		messageComposer: newMessageComposer(),
		log:             logrus.WithField("component", "room_view"),
	}
}

func (r *RoomView) Start(rx, tx chan Event) {
	r.rx, r.tx = rx, tx

	r.room.Notify(r.matrixEvents)

	// TODO Only load history which is actually needed
	// TODO Stop this goroutine
	go func() {
		for r.history.Next() {
			if r.history.Err != nil {
				r.log.WithField("error", r.history.Err).Warn("Error while traversing history")
				// 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
			}
		}
	}()
}

func (r *RoomView) update() {
	if r.backButton.Clicked() {
		r.tx <- BackEvent{}
	}

	if r.settingsButton.Clicked() {
		r.log.Warn("Not implemented")
	}

	if r.userListButton.Clicked() {
		r.log.Info("Opening UsersView")
		r.tx <- LoadViewEvent{
			View:     NewUsersView(r.room),
			Position: Right,
		}
	}

	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}
		}()
	}

	for {
		select {
		case event := <-r.rx:
			r.log.WithField("event", event).Trace("Received event")

			switch event := event.(type) {
			case SentRoomEvent:
				r.messageComposer.Reenable(event.Err)
			default:
				r.log.WithField("event", event).Warn("Unexpected event")
			}
		case event := <-r.matrixEvents:
			switch event.(type) {
			// EphemeralEvents should not be added to the room History
			case matrix.EphemeralEvent:
			default:
				r.roomHistory.AddEvent(event)
			}
		case event := <-r.pastEvents:
			r.roomHistory.AddPastEvent(event)
		default:
			return
		}
	}
}

func (r *RoomView) Stop() {
}

func (r *RoomView) Layout(gtx Gtx) Dims {
	r.update()

	return layout.Flex{Alignment: layout.Start, Axis: layout.Vertical}.Layout(gtx,
		layout.Rigid(r.topbar),
		layout.Flexed(1, r.roomHistory.Layout),
		layout.Rigid(r.messageComposer.Layout),
	)
}

func (r *RoomView) topbar(gtx Gtx) Dims {
	return layout.Stack{Alignment: layout.SW}.Layout(gtx,
		layout.Expanded(fill{theme.Color.Primary}.Layout),
		layout.Stacked(func(gtx Gtx) Dims {
			return layout.Flex{Alignment: layout.Middle}.Layout(gtx,
				layout.Rigid(func(gtx Gtx) Dims {
					btn := material.IconButton(theme, r.backButton, mustIcon(icons.NavigationArrowBack))
					return btn.Layout(gtx)
				}),
				layout.Flexed(1, func(gtx Gtx) Dims {
					gtx.Constraints.Min.X = gtx.Constraints.Max.X
					lbl := material.H6(theme, r.room.Displayname())
					lbl.Color = rgb(0xffffff)
					lbl.MaxLines = 1
					return lbl.Layout(gtx)
					// return Dims{Size: image.Point{X: gtx.Constraints.Max.X}}
				}),
				layout.Rigid(func(gtx Gtx) Dims {
					btn := material.IconButton(theme, r.userListButton, mustIcon(icons.ActionViewList))
					return btn.Layout(gtx)
				}),
				layout.Rigid(func(gtx Gtx) Dims {
					btn := material.IconButton(theme, r.settingsButton, mustIcon(icons.ActionSettings))
					return btn.Layout(gtx)
				}),
			)
		}),
	)
}

// roomHistory is a widget that displays the chat history of a room
// TODO Decide where and how different matrix.Event s are handled
type roomHistory struct {
	user   string
	list   *layout.List
	events []matrix.Event
}

func newRoomHistory(user string) *roomHistory {
	return &roomHistory{
		user:   user,
		events: make([]matrix.Event, 0),
		list:   &layout.List{Axis: layout.Vertical, ScrollToEnd: true},
	}
}

func (w *roomHistory) AddEvent(event matrix.Event) {
	w.events = append(w.events, event)
}

func (w *roomHistory) AddPastEvent(event matrix.Event) {
	w.events = append([]matrix.Event{event}, w.events...)
}

// Layout implements the layout.Widget interface
func (w *roomHistory) Layout(gtx Gtx) Dims {
	if w.list == nil {
		return Dims{}
	}
	return w.list.Layout(gtx, len(w.events), w.element)
}

func (w *roomHistory) element(gtx Gtx, index int) Dims {
	msg := w.events[index]
	in := layout.Inset{Top: unit.Dp(16), Left: unit.Dp(16), Right: unit.Dp(40)}
	if ownEvent(w.user, msg) {
		in.Left, in.Right = in.Right, in.Left
	}
	return in.Layout(gtx, event{
		Event: msg,
		Own:   ownEvent(w.user, msg),
		log:   logrus.WithField("event", msg),
	}.Layout)
}

// event is a widget that displays a single event in the room history
type event struct {
	Event matrix.Event
	Own   bool

	log *logrus.Entry
}

func (e event) Layout(gtx Gtx) Dims {
	switch e.Event.(type) {
	case matrix.StateEvent:
		return e.layoutStateEvent(gtx)
	case matrix.RoomEvent:
		return e.layoutRoomEvent(gtx)
	default:
		panic("Unknown event type. What is going on?")
	}
}

func (e event) layoutStateEvent(gtx Gtx) Dims {
	align := layout.Center
	bgcol := rgb(0xeeeeee)

	return align.Layout(gtx, func(gtx Gtx) Dims {
		bg := Background{
			Color: bgcol,
			Inset: layout.Inset{
				Top:    unit.Dp(8),
				Bottom: unit.Dp(8),
				Left:   unit.Dp(12),
				Right:  unit.Dp(12),
			},
			Radius: unit.Dp(10),
		}

		return bg.Layout(gtx, e.layoutStateEventContent)
	})
}

func (e event) layoutStateEventContent(gtx Gtx) Dims {
	ev := e.Event.(matrix.StateEvent)
	senderName := ev.Sender.Displayname()

	switch e.Event.Base().Type {
	case "m.room.member":
		lbl := material.Body1(theme, fmt.Sprintf("%s changed their profile", ev.StateKey))
		return lbl.Layout(gtx)
	case "m.room.create":
		lbl := material.Body1(theme, fmt.Sprintf("%s created the room", senderName))
		return lbl.Layout(gtx)
	case "m.room.power_levels":
		lbl := material.Body1(theme, fmt.Sprintf("Room power levels were changed by %s", senderName))
		return lbl.Layout(gtx)
	case "m.room.join_rules":
		lbl := material.Body1(theme, fmt.Sprintf("Join rules were changed by %s", senderName))
		return lbl.Layout(gtx)
	case "m.room.name":
		lbl := material.Body1(theme, fmt.Sprintf("%s changed the room name to \"%s\"",
			senderName, ev.Room.Displayname()))
		return lbl.Layout(gtx)
	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)
			e.log.Debug("Invalid event")
		}
		lbl := material.Body1(theme, str)
		return lbl.Layout(gtx)
	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 {
			e.log.Debug("Invalid event")
			str = "Invalid"
		}
		return material.Body1(theme, str).Layout(gtx)

	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 {
			e.log.Debug("Invalid event")
			str = "Invalid"
		}
		return material.Body1(theme, str).Layout(gtx)
	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)
		}
		return material.Body1(theme, str).Layout(gtx)
	default:
		lbl := material.Body1(theme, "[Unformattable Event]")
		lbl.Color = rgb(0xff0000)
		return lbl.Layout(gtx)
	}
}

func (e event) layoutRoomEvent(gtx Gtx) Dims {
	align := layout.W
	bgcol := theme.Color.Primary
	if e.Own {
		align = layout.E
		bgcol = rgb(0xeeeeee)
	}

	return align.Layout(gtx, func(gtx Gtx) Dims {
		bg := Background{
			Color: bgcol,
			Inset: layout.Inset{
				Top:    unit.Dp(8),
				Bottom: unit.Dp(8),
				Left:   unit.Dp(12),
				Right:  unit.Dp(12),
			},
			Radius: unit.Dp(10),
		}

		var msgWidth int
		timecol := argb(0xaaaaaaaa)

		return bg.Layout(gtx, func(gtx Gtx) Dims {
			return layout.Flex{Axis: layout.Vertical}.Layout(gtx,
				layout.Rigid(func(gtx Gtx) Dims {
					senderName := e.Event.(matrix.RoomEvent).Sender.Displayname()
					lbl := material.Body2(theme, senderName)
					lbl.Color = initialColor(senderName[0])
					return lbl.Layout(gtx)
				}),

				layout.Rigid(func(gtx Gtx) Dims {
					return e.layoutRoomEventContent(gtx, &msgWidth)
				}),

				layout.Rigid(func(gtx Gtx) Dims {
					gtx.Constraints.Min.X = msgWidth
					f := layout.Flex{
						Axis:      layout.Horizontal,
						Spacing:   layout.SpaceBetween,
						Alignment: layout.Middle,
					}

					var children []layout.FlexChild
					child := layout.Rigid(func(gtx Gtx) Dims {
						time := formatTime(timeEvent(e.Event))
						lbl := material.Caption(theme, time)
						lbl.Color = timecol
						return lbl.Layout(gtx)
					})
					children = append(children, child)

					return f.Layout(gtx, children...)
				}),
			)
		})
	})
}

func (e event) layoutRoomEventContent(gtx Gtx, msgWidth *int) Dims {
	var content layout.Widget
	switch e.Event.Base().Type {
	case "m.room.message":
		lbl := material.Body2(theme, e.Event.(matrix.RoomEvent).Content["body"].(string))
		if e.Own {
			lbl.Color = rgb(0x000000)
		} else {
			lbl.Color = rgb(0xffffff)
		}
		content = lbl.Layout
	default:
		lbl := material.Body1(theme, "[Unformattable Event]")
		lbl.Color = rgb(0xff0000)
		content = lbl.Layout
	}

	dims := content(gtx)
	dims.Size.Y += gtx.Px(unit.Dp(4))
	*msgWidth = dims.Size.X
	return dims
}

type messageComposer struct {
	editor *widget.Editor
	submit *widget.Clickable

	disabled  bool
	sendError error
}

func newMessageComposer() *messageComposer {
	return &messageComposer{
		editor:   &widget.Editor{Submit: true, SingleLine: false},
		submit:   new(widget.Clickable),
		disabled: false,
	}
}

func (m *messageComposer) Layout(gtx Gtx) Dims {
	in := layout.Inset{
		Top:    unit.Dp(8),
		Left:   unit.Dp(8),
		Right:  unit.Dp(8),
		Bottom: unit.Dp(4),
	}

	if mh := gtx.Px(unit.Dp(200)); gtx.Constraints.Max.Y > mh {
		gtx.Constraints.Max.Y = mh
	}

	if m.disabled {
		gtx = gtx.Disabled()
	}

	var minHeight int
	return in.Layout(gtx, func(gtx Gtx) Dims {
		return layout.Flex{Axis: layout.Horizontal}.Layout(gtx,
			layout.Flexed(1, func(gtx Gtx) Dims {
				return m.layoutEditor(gtx, &minHeight)
			}),
			layout.Rigid(func(gtx Gtx) Dims {
				dims := layout.Inset{Left: unit.Dp(8)}.Layout(gtx, func(gtx Gtx) Dims {
					btn := material.IconButton(theme, m.submit, mustIcon(icons.ContentSend))
					btn.Size = unit.Dp(24)
					btn.Inset = layout.UniformInset(unit.Dp(6))
					return btn.Layout(gtx)
				})
				minHeight = dims.Size.Y
				return dims
			}),
		)
	})
}

func (m *messageComposer) layoutEditor(gtx Gtx, minHeight *int) Dims {
	gtx.Constraints.Min.X = gtx.Constraints.Max.X

	bg := Background{
		Color:  rgb(0xeeeeee),
		Inset:  layout.Inset{Left: unit.Dp(8), Right: unit.Dp(8)},
		Radius: unit.Dp(10),
	}

	return layout.Flex{Axis: layout.Vertical}.Layout(gtx,
		layout.Rigid(func(gtx Gtx) Dims {
			if m.sendError != nil {
				lbl := material.Body2(theme, m.sendError.Error())
				lbl.Color = rgb(0xff0000)
				return lbl.Layout(gtx)
			}
			return Dims{}
		}),
		layout.Rigid(func(gtx Gtx) Dims {
			return bg.Layout(gtx, func(gtx Gtx) Dims {
				return layout.W.Layout(gtx, func(gtx Gtx) Dims {
					gtx.Constraints.Min.X = gtx.Constraints.Max.X
					gtx.Constraints.Min.Y = *minHeight
					ed := material.Editor(theme, m.editor, "Send a message")
					ed.TextSize = unit.Sp(12)
					return ed.Layout(gtx)
				})
			})
		}),
	)
}

func (m *messageComposer) Submitted() bool {
	return m.submit.Clicked()
}

func (m *messageComposer) Text() string {
	return m.editor.Text()
}

func (m *messageComposer) Disable() {
	m.disabled = true
}

// Reenable activates the composer after a event has been sent. If the error
// is not nil, then the editor is cleared
func (m *messageComposer) Reenable(err error) {
	m.disabled = false
	m.sendError = err
	m.editor.SetText("")
}

func ownEvent(me string, ev matrix.Event) bool {
	switch ev := ev.(type) {
	case matrix.AccountDataEvent:
		return true
	case matrix.RoomEvent:
		return ev.Sender.ID == me
	case matrix.StateEvent:
		return ev.Sender.ID == me
	}

	return false
}

func timeEvent(ev matrix.Event) time.Time {
	switch ev := ev.(type) {
	case matrix.RoomEvent:
		return ev.OriginServerTS
	case matrix.StateEvent:
		return ev.OriginServerTS
	default:
		return time.Time{}
	}
}