summaryrefslogtreecommitdiff
path: root/danmaku/dmpkg/auth.go
blob: 5a205adc7716af13ca56d181783c3bbb748970dd (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
/*
This file implements the auth exchange.
When Bilibili live client established the WebSocket connection successfully,
it sends this message at first. The server then responses a OpConnectOk exchange with body `{"code":0}` which indicates success.
*/
package dmpkg

import (
	"bilibili-livestream-archiver/common"
	"encoding/json"
	"fmt"
)

type authInfo struct {
	UID      uint64 `json:"uid"`
	RoomId   uint64 `json:"roomid"`
	ProtoVer int    `json:"protover"`
	Platform string `json:"platform"`
	Type     int    `json:"type"`
	Key      string `json:"key"`
}

// NewAuth creates a new authentication exchange.
func NewAuth(protocol ProtocolVer, roomId common.RoomId, authKey string) (exc DanmakuExchange) {
	exc, _ = NewPlainExchange(OpConnect, authInfo{
		UID:      kUidGuest,
		RoomId:   uint64(roomId),
		ProtoVer: int(protocol),
		Platform: kPlatformWeb,
		Type:     kAuthTypeDefault,
		Key:      authKey,
	})
	return
}

func IsAuthOk(serverResponse DanmakuExchange) (bool, error) {
	if op := serverResponse.Operation; op != OpConnectOk {
		return false, fmt.Errorf("server operation is not OpConnectOk: %w", op)
	}
	var body struct {
		Code int `json:"code"`
	}
	body.Code = 1
	err := json.Unmarshal(serverResponse.Body, &body)
	if err != nil {
		return false, fmt.Errorf("JSON decode error: %w", err)
	}
	if c := body.Code; c != 0 {
		return false, fmt.Errorf("server response code is non-zero: %w", c)
	}
	return true, nil
}