summaryrefslogtreecommitdiff
path: root/danmaku/dmmsg/danmu.go
blob: a18a9aada3e88db7ac9e7aeb85d644a08a237577 (plain)
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
package dmmsg

/*
Decoder of raw danmaku messages.
*/

import (
	"fmt"
)

type RawDanMuMessage = BaseRawMessage[[]interface{}, interface{}]

type DanMuMessage struct {
	Content    string
	SourceUser struct {
		Nickname string
		UID      int64
	}
}

func (dm DanMuMessage) String() string {
	return fmt.Sprintf("(user: %v, uid: %v) %v",
		dm.SourceUser.Nickname, dm.SourceUser.UID, dm.Content)
}

const InvalidDanmakuJson = "invalid danmaku JSON document"

func ParseDanmakuMessage(body RawDanMuMessage) (dmm DanMuMessage, err error) {
	if len(body.Info) < 16 {
		err = fmt.Errorf("%s: \"info\" length < 16", InvalidDanmakuJson)
		return
	}

	dmm.Content, err = castValue[string](body.Info[1])
	if err != nil {
		return
	}

	userInfo, err := castValue[[]interface{}](body.Info[2])

	var ok bool
	uid, ok := userInfo[0].(float64)
	if !ok {
		err = fmt.Errorf("%s: uid is not a float64: %v", InvalidDanmakuJson, userInfo[0])
		return
	}
	dmm.SourceUser.UID = int64(uid)

	dmm.SourceUser.Nickname, ok = userInfo[1].(string)
	if !ok {
		err = fmt.Errorf("%s: nickname is not a string: %v", InvalidDanmakuJson, userInfo[1])
		return
	}
	return
}