-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Rasmus Karlsson <rasmus.karlsson@pajlada.com>
- Loading branch information
Showing
9 changed files
with
609 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
package youtube | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"net/http" | ||
"strings" | ||
"time" | ||
|
||
"github.com/Chatterino/api/internal/logger" | ||
"github.com/Chatterino/api/internal/staticresponse" | ||
"github.com/Chatterino/api/pkg/cache" | ||
"github.com/Chatterino/api/pkg/humanize" | ||
"github.com/Chatterino/api/pkg/resolver" | ||
youtubeAPI "google.golang.org/api/youtube/v3" | ||
) | ||
|
||
type youtubePlaylistTooltipData struct { | ||
Title string | ||
Description string | ||
Channel string | ||
VideoCount string | ||
PublishedAt string | ||
} | ||
|
||
type YouTubePlaylistLoader struct { | ||
youtubeClient *youtubeAPI.Service | ||
} | ||
|
||
func getThumbnailUrl(thumbnailDetails *youtubeAPI.ThumbnailDetails) string { | ||
if thumbnailDetails.Maxres != nil { | ||
return thumbnailDetails.Maxres.Url | ||
} | ||
if thumbnailDetails.Default != nil { | ||
return thumbnailDetails.Default.Url | ||
} | ||
return "" | ||
} | ||
|
||
func (r *YouTubePlaylistLoader) Load(ctx context.Context, playlistCacheKey string, req *http.Request) ([]byte, *int, *string, time.Duration, error) { | ||
log := logger.FromContext(ctx) | ||
log.Debugw("[YouTube] GET playlist", | ||
"cacheKey", playlistCacheKey, | ||
) | ||
|
||
playlistId, err := getPlaylistFromCacheKey(playlistCacheKey) | ||
if err != nil { | ||
return resolver.InternalServerErrorf("YouTube API playlist is invalid for key: %s", playlistCacheKey) | ||
} | ||
|
||
youtubePlaylistParts := []string{ | ||
"snippet", | ||
"contentDetails", | ||
} | ||
|
||
youtubeResponse, err := r.youtubeClient.Playlists.List(youtubePlaylistParts).Id(playlistId).Do() | ||
if err != nil { | ||
return resolver.InternalServerErrorf("YouTube API error: %s", err) | ||
} | ||
|
||
if len(youtubeResponse.Items) == 0 { | ||
return staticresponse.NotFoundf("No YouTube playlist with the ID %s found", playlistId). | ||
WithCacheDuration(24 * time.Hour). | ||
Return() | ||
} | ||
|
||
if len(youtubeResponse.Items) > 1 { | ||
return resolver.InternalServerErrorf("YouTube playlist response contained %d items", len(youtubeResponse.Items)) | ||
} | ||
|
||
youtubePlaylist := youtubeResponse.Items[0] | ||
|
||
data := youtubePlaylistTooltipData{ | ||
Title: youtubePlaylist.Snippet.Title, | ||
Description: youtubePlaylist.Snippet.Description, | ||
Channel: youtubePlaylist.Snippet.ChannelTitle, | ||
VideoCount: humanize.NumberInt64(youtubePlaylist.ContentDetails.ItemCount), | ||
PublishedAt: humanize.CreationDateRFC3339(youtubePlaylist.Snippet.PublishedAt), | ||
} | ||
|
||
var tooltip bytes.Buffer | ||
if err := youtubePlaylistTooltipTemplate.Execute(&tooltip, data); err != nil { | ||
return resolver.InternalServerErrorf("YouTube template error: %s", err.Error()) | ||
} | ||
|
||
statusCode := http.StatusOK | ||
contentType := "application/json" | ||
|
||
response := &resolver.Response{ | ||
Status: statusCode, | ||
Tooltip: tooltip.String(), | ||
Thumbnail: getThumbnailUrl(youtubePlaylist.Snippet.Thumbnails), | ||
} | ||
|
||
payload, err := json.Marshal(response) | ||
if err != nil { | ||
return resolver.InternalServerErrorf("YouTube marshaling error: %s", err.Error()) | ||
} | ||
|
||
return payload, &statusCode, &contentType, cache.NoSpecialDur, nil | ||
} | ||
|
||
func getPlaylistFromCacheKey(cacheKey string) (string, error) { | ||
splitKey := strings.Split(cacheKey, ":") | ||
|
||
if len(splitKey) < 2 { | ||
return "", errors.New("invalid playlist") | ||
} | ||
|
||
return splitKey[1], nil | ||
} | ||
|
||
func NewYouTubePlaylistLoader(youtubeClient *youtubeAPI.Service) *YouTubePlaylistLoader { | ||
loader := &YouTubePlaylistLoader{ | ||
youtubeClient: youtubeClient, | ||
} | ||
|
||
return loader | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package youtube | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"net/http" | ||
"net/url" | ||
"regexp" | ||
|
||
"github.com/Chatterino/api/internal/db" | ||
"github.com/Chatterino/api/internal/logger" | ||
"github.com/Chatterino/api/internal/staticresponse" | ||
"github.com/Chatterino/api/pkg/cache" | ||
"github.com/Chatterino/api/pkg/config" | ||
"github.com/Chatterino/api/pkg/utils" | ||
youtubeAPI "google.golang.org/api/youtube/v3" | ||
) | ||
|
||
var youtubePlaylistRegex = regexp.MustCompile(`^/playlist$`) | ||
|
||
type YouTubePlaylistResolver struct { | ||
playlistCache cache.Cache | ||
} | ||
|
||
func (r *YouTubePlaylistResolver) Check(ctx context.Context, url *url.URL) (context.Context, bool) { | ||
if !utils.IsSubdomainOf(url, "youtube.com") { | ||
return ctx, false | ||
} | ||
|
||
q := url.Query() | ||
if !q.Has("list") { | ||
return ctx, false | ||
} | ||
|
||
matches := youtubePlaylistRegex.MatchString(url.Path) | ||
return ctx, matches | ||
} | ||
|
||
func (r *YouTubePlaylistResolver) Run(ctx context.Context, url *url.URL, req *http.Request) (*cache.Response, error) { | ||
log := logger.FromContext(ctx) | ||
|
||
q := url.Query() | ||
|
||
playlistId := q.Get("list") | ||
if playlistId == "" { | ||
log.Warnw("[YouTube] Failed to get playlist ID from url", | ||
"url", url, | ||
) | ||
|
||
return &staticresponse.RNoLinkInfoFound, nil | ||
} | ||
|
||
return r.playlistCache.Get(ctx, fmt.Sprintf("playlist:%s", playlistId), req) | ||
} | ||
|
||
func (r *YouTubePlaylistResolver) Name() string { | ||
return "youtube:playlist" | ||
} | ||
|
||
func NewYouTubePlaylistResolver(ctx context.Context, cfg config.APIConfig, pool db.Pool, youtubeClient *youtubeAPI.Service) *YouTubePlaylistResolver { | ||
loader := NewYouTubePlaylistLoader(youtubeClient) | ||
|
||
r := &YouTubePlaylistResolver{ | ||
playlistCache: cache.NewPostgreSQLCache( | ||
ctx, cfg, pool, cache.NewPrefixKeyProvider("youtube:playlist"), loader, cfg.YoutubeChannelCacheDuration, | ||
), | ||
} | ||
|
||
return r | ||
} |
Oops, something went wrong.