summaryrefslogtreecommitdiff
path: root/bilibili/streaming.go
blob: e8a6911a9a73049c4f211cec712373daaec7d8c0 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package bilibili

import (
	"bilibili-livestream-archiver/common"
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// CopyLiveStream read data from a livestream video stream, copy them to a writer.
func (b Bilibili) CopyLiveStream(
	ctx context.Context,
	roomId common.RoomId,
	stream StreamingUrlInfo,
	out io.Writer,
) (err error) {
	url := stream.URL
	if !strings.HasPrefix(url, "https://") &&
		!strings.HasPrefix(url, "http://") {
		return fmt.Errorf("invalid URL: %v", url)
	}

	r, err := b.newGet(url)
	if err != nil {
		b.error.Printf("Cannot create HTTP GET instance on %v: %v", url, err)
		return err
	}

	r.Header.Set("Referer",
		fmt.Sprintf("https://live.bilibili.com/blanc/%d?liteVersion=true", roomId))

	resp, err := b.Do(r)
	if err != nil {
		b.error.Printf("Cannot make HTTP GET request on %v: %v\n", url, err)
		return
	}

	// 404 when not streaming
	if resp.StatusCode == http.StatusNotFound {
		return ErrRoomIsClosed
	}

	err = validateHttpStatus(resp)
	if err != nil {
		return
	}

	defer func() { _ = resp.Body.Close() }()

	// guard the following copy loop
	// if the context is cancelled, stop it by closing the reader
	guardianCtx, cancelGuardian := context.WithCancel(ctx)
	go func() {
		<-guardianCtx.Done()
		_ = resp.Body.Close()
	}()
	defer cancelGuardian()

	// blocking copy
	n, err := common.Copy(ctx, out, resp.Body)

	if err != nil && !errors.Is(err, context.Canceled) {
		// real error happens
		b.error.Printf("Stream copying was interrupted unexpectedly: %v", err)
	}

	if err == nil {
		b.info.Printf("The live is ended. (room %v)", roomId)
	}

	b.info.Printf("Bytes copied: %v", n)
	return err
}