JHHM

tweed

a Twitch RSS feed generator
git clone https://jhhm.no/repos/tweed.git

tweed/net.go

get raw file: net.go

1package main
2
3import (
4	"context"
5	"encoding/json"
6	"fmt"
7	"io"
8	"net/http"
9	"net/url"
10	"strings"
11	"sync"
12	"time"
13)
14
15type OAuthToken struct {
16	AccessToken string `json:"access_token"`
17	ExpiresIn   int    `json:"expires_in"`
18	TokenType   string `json:"token_type"`
19	AcquiredAt  time.Time
20}
21
22type TwitchResp struct {
23	Data []struct {
24		ID        string `json:"id"`
25		Title     string `json:"title"`
26		StartedAt string `json:"started_at"`
27	} `json:"data"`
28}
29
30var httpClient = &http.Client{Timeout: 15 * time.Second}
31var oauthToken OAuthToken
32var oauthMu sync.Mutex
33
34func (t OAuthToken) Expired() bool {
35	return time.Since(t.AcquiredAt) > time.Duration(t.ExpiresIn-120)*time.Second
36}
37
38func refreshToken(ctx context.Context, cfg *Config) error {
39	oauthMu.Lock()
40	defer oauthMu.Unlock()
41
42	if oauthToken.AccessToken != "" && !oauthToken.Expired() {
43		return nil
44	}
45
46	logDebug("fetching oauth token")
47	endpoint := "https://id.twitch.tv/oauth2/token"
48
49	data := url.Values{}
50	data.Set("client_id", cfg.AppID)
51	data.Set("client_secret", cfg.AppSecret)
52	data.Set("grant_type", "client_credentials")
53
54	req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(data.Encode()))
55	if err != nil {
56		return err
57	}
58	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
59
60	resp, err := httpClient.Do(req)
61	if err != nil {
62		return err
63	}
64	defer resp.Body.Close()
65
66	body, err := io.ReadAll(resp.Body)
67	if err != nil {
68		return err
69	}
70	if resp.StatusCode != http.StatusOK {
71		return fmt.Errorf("token endpoint returned %d: %s", resp.StatusCode, string(body))
72	}
73
74	var tok OAuthToken
75	if err := json.Unmarshal(body, &tok); err != nil {
76		return err
77	}
78
79	tok.AcquiredAt = time.Now()
80	oauthToken = tok
81	logDebug("obtained oauth token, expires in %ds", oauthToken.ExpiresIn)
82	return nil
83}
84
85// NOTE: the endpoint has the ability to query for multiple streams at a time
86// this is currently not being done, but could be more correct
87func isLive(ctx context.Context, cfg *Config, channel string) (bool, StreamInfo, error) {
88	if err := refreshToken(ctx, cfg); err != nil {
89		return false, StreamInfo{}, err
90	}
91
92	oauthMu.Lock()
93	token := oauthToken.AccessToken
94	oauthMu.Unlock()
95
96	q := url.Values{"user_login": {channel}}
97	req, err := http.NewRequestWithContext(ctx, http.MethodGet,
98		"https://api.twitch.tv/helix/streams?"+q.Encode(), nil)
99	if err != nil {
100		return false, StreamInfo{}, err
101	}
102	req.Header.Set("Client-ID", cfg.AppID)
103	req.Header.Set("Authorization", "Bearer "+token)
104
105	resp, err := httpClient.Do(req)
106	if err != nil {
107		return false, StreamInfo{}, err
108	}
109	defer resp.Body.Close()
110
111	if resp.StatusCode != http.StatusOK {
112		b, _ := io.ReadAll(resp.Body)
113		return false, StreamInfo{}, fmt.Errorf("twitch API status %d: %s", resp.StatusCode, b)
114	}
115
116	var tr TwitchResp
117	if err := json.NewDecoder(resp.Body).Decode(&tr); err != nil {
118		return false, StreamInfo{}, err
119	}
120
121	if len(tr.Data) == 0 {
122		return false, StreamInfo{}, nil // stream is not live
123	}
124
125	startedAt, err := time.Parse(time.RFC3339, tr.Data[0].StartedAt)
126	if err != nil {
127		return false, StreamInfo{}, err
128	}
129
130	return true, StreamInfo{
131		Channel:   channel,
132		Title:     tr.Data[0].Title,
133		StreamID:  tr.Data[0].ID,
134		StartedAt: startedAt,
135	}, nil
136}
137func probeCDNs(ctx context.Context, cdns []string, path string, n int) []string {
138	client := &http.Client{Timeout: 5 * time.Second}
139	var out []string
140	for _, cdn := range cdns {
141		if len(out) >= n || ctx.Err() != nil {
142			break
143		}
144		u := "https://" + cdn + "/" + path
145		req, err := http.NewRequestWithContext(ctx, http.MethodHead, u, nil)
146		if err != nil {
147			continue
148		}
149		resp, err := client.Do(req)
150		if err != nil {
151			continue
152		}
153		resp.Body.Close()
154		if resp.StatusCode == http.StatusOK {
155			out = append(out, u)
156		}
157	}
158	return out
159}