YouTube link embeds

This commit is contained in:
Noah 2023-03-24 22:47:58 -07:00
parent b3551cbe9a
commit 75fbed4a4d
3 changed files with 37 additions and 0 deletions

29
pkg/expand_media.go Normal file
View File

@ -0,0 +1,29 @@
package barertc
import (
"fmt"
"regexp"
)
// Media regexps
var (
ytLinkRegexp = regexp.MustCompile(`(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})`)
ytIdRegexp = regexp.MustCompile(`[0-9A-Za-z_-]{10}[048AEIMQUYcgkosw]`) // YT ID validator
)
// YT embed template
const youtubeEmbedTemplate = `<iframe class="youtube-embed" width="560" height="315" src="https://www.youtube.com/embed/%s" title="YouTube video player" frameborder="0" allow="autoplay; encrypted-media; picture-in-picture; web-share" allowfullscreen></iframe>`
// ExpandMedia detects media URLs such as YouTube videos and stylizes the message up with embeds.
func (s *Server) ExpandMedia(message string) string {
// YouTube links.
if m := ytLinkRegexp.FindStringSubmatch(message); len(m) > 0 {
var ytid = m[1]
// Sanity check the ID parsed OK (e.g. multiple youtube links can throw it off)
if ytIdRegexp.Match([]byte(ytid)) {
message += fmt.Sprintf(youtubeEmbedTemplate, ytid)
}
}
return message
}

View File

@ -120,6 +120,9 @@ func (s *Server) OnMessage(sub *Subscriber, msg Message) {
return
}
// Detect and expand media such as YouTube videos.
markdown = s.ExpandMedia(markdown)
// Message to be echoed to the channel.
var message = Message{
Action: ActionMessage,

View File

@ -238,3 +238,8 @@ body {
font-size: small;
padding: 2px 4px;
}
/* YouTube embeds */
.youtube-embed {
max-width: 100%;
}