~handlerug/handlebot

ref: e2138e35984f582b50a481b58c332afae2841b1f handlebot/urlpreview/youtube.go -rw-r--r-- 1.4 KiB
e2138e35Umar Getagazov urlpreview: Parse Content-Disposition 5 months ago
                                                                                
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
package urlpreview

import (
	"context"
	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/dustin/go-humanize"

	"git.sr.ht/~handlerug/handlebot/youtube"
)

func (p *Previewer) youtube(ctx context.Context, u *url.URL) (string, error) {
	var vid string
	switch {
	case strings.HasSuffix(u.Host, "youtube.com") && u.Path == "/watch":
		vid = u.Query().Get("v")
	case strings.HasSuffix(u.Host, "youtu.be"):
		vid = u.Path[1:]
	}
	if vid == "" {
		return "", nil
	}

	yt := youtube.ForContext(ctx)
	if yt == nil {
		return "", nil
	}

	video, err := yt.GetVideo(ctx, vid)
	if err != nil {
		return "", nil
	}

	var postfix string
	if len(video.ContentDetails.RegionRestriction.Blocked) > 0 {
		postfix = " [Region restricted]"
	}

	var pubDate string
	if video.Snippet.PublishedAt.Add(time.Hour * 24 * 30).Before(time.Now()) {
		pubDate = video.Snippet.PublishedAt.Format("2006-01-02")
	} else {
		pubDate = humanize.Time(video.Snippet.PublishedAt)
	}

	var dimension string
	if video.ContentDetails.Dimension != "2d" {
		dimension = " (" + strings.ToUpper(dimension) + ")"
	}

	duration := strings.ToLower(strings.TrimPrefix(video.ContentDetails.Duration, "PT"))

	return fmt.Sprintf("%s [%s] %s (%s) %s views %s%s%s",
		video.Snippet.Title, duration, pubDate, video.Snippet.ChannelTitle,
		humanize.Comma(int64(video.Statistics.ViewCount)),
		strings.ToUpper(video.ContentDetails.Definition),
		dimension, postfix), nil
}