From 75fbed4a4d841e07ce577b5b58719bf9f188c35d Mon Sep 17 00:00:00 2001 From: Noah Petherbridge Date: Fri, 24 Mar 2023 22:47:58 -0700 Subject: [PATCH] YouTube link embeds --- pkg/expand_media.go | 29 +++++++++++++++++++++++++++++ pkg/handlers.go | 3 +++ web/static/css/chat.css | 5 +++++ 3 files changed, 37 insertions(+) create mode 100644 pkg/expand_media.go diff --git a/pkg/expand_media.go b/pkg/expand_media.go new file mode 100644 index 0000000..345a1b0 --- /dev/null +++ b/pkg/expand_media.go @@ -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 = `` + +// 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 +} diff --git a/pkg/handlers.go b/pkg/handlers.go index b08306e..423a0ee 100644 --- a/pkg/handlers.go +++ b/pkg/handlers.go @@ -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, diff --git a/web/static/css/chat.css b/web/static/css/chat.css index 308f621..a62acd4 100644 --- a/web/static/css/chat.css +++ b/web/static/css/chat.css @@ -237,4 +237,9 @@ body { left: 4px; font-size: small; padding: 2px 4px; +} + +/* YouTube embeds */ +.youtube-embed { + max-width: 100%; } \ No newline at end of file