From 00595609af53514ffd39d9aeab0d33e6d84cbdb5 Mon Sep 17 00:00:00 2001 From: Keuin Date: Wed, 7 Sep 2022 12:45:46 +0800 Subject: More comprehensive danmaku message handling. --- danmaku/dmmsg/danmu.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 danmaku/dmmsg/danmu.go (limited to 'danmaku/dmmsg/danmu.go') diff --git a/danmaku/dmmsg/danmu.go b/danmaku/dmmsg/danmu.go new file mode 100644 index 0000000..2cc5dfa --- /dev/null +++ b/danmaku/dmmsg/danmu.go @@ -0,0 +1,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 kInvalidDanmakuJson = "invalid danmaku JSON document" + +func ParseDanmakuMessage(body RawDanMuMessage) (dmm DanMuMessage, err error) { + if len(body.Info) != 16 { + err = fmt.Errorf("%s: \"info\" length != 16", kInvalidDanmakuJson) + 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", kInvalidDanmakuJson, 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", kInvalidDanmakuJson, userInfo[1]) + return + } + return +} -- cgit v1.2.3