youtube.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package processor // import "miniflux.app/v2/internal/reader/processor"
  4. import (
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "miniflux.app/v2/internal/config"
  13. "miniflux.app/v2/internal/model"
  14. "miniflux.app/v2/internal/proxyrotator"
  15. "miniflux.app/v2/internal/reader/fetcher"
  16. )
  17. const youTubeVideosAPIURL = "https://www.googleapis.com/youtube/v3/videos"
  18. func isYouTubeVideoURL(websiteURL string) bool {
  19. return strings.Contains(websiteURL, "youtube.com/watch?v=")
  20. }
  21. func getVideoIDFromYouTubeURL(websiteURL string) string {
  22. parsedWebsiteURL, err := url.Parse(websiteURL)
  23. if err != nil {
  24. return ""
  25. }
  26. return parsedWebsiteURL.Query().Get("v")
  27. }
  28. func shouldFetchYouTubeWatchTimeForSingleEntry(entry *model.Entry) bool {
  29. return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeAPIKey() == "" && isYouTubeVideoURL(entry.URL)
  30. }
  31. func shouldFetchYouTubeWatchTimeInBulk() bool {
  32. return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeAPIKey() != ""
  33. }
  34. func fetchYouTubeWatchTimeForSingleEntry(websiteURL string) (int, error) {
  35. return fetchWatchTime(websiteURL, `meta[itemprop="duration"]`, true)
  36. }
  37. func fetchYouTubeWatchTimeInBulk(entries []*model.Entry) {
  38. videosEntriesMapping := make(map[string]*model.Entry, len(entries))
  39. videoIDs := make([]string, 0, len(entries))
  40. for _, entry := range entries {
  41. if !isYouTubeVideoURL(entry.URL) {
  42. continue
  43. }
  44. youtubeVideoID := getVideoIDFromYouTubeURL(entry.URL)
  45. if youtubeVideoID == "" {
  46. continue
  47. }
  48. videosEntriesMapping[youtubeVideoID] = entry
  49. videoIDs = append(videoIDs, youtubeVideoID)
  50. }
  51. if len(videoIDs) == 0 {
  52. return
  53. }
  54. watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(youTubeVideosAPIURL, videoIDs)
  55. if err != nil {
  56. slog.Warn("Unable to fetch YouTube watch time in bulk", slog.Any("error", err))
  57. return
  58. }
  59. for videoID, watchTime := range watchTimeMap {
  60. if entry, ok := videosEntriesMapping[videoID]; ok {
  61. entry.ReadingTime = int(watchTime.Minutes())
  62. }
  63. }
  64. }
  65. func fetchYouTubeWatchTimeFromApiInBulk(apiURL string, videoIDs []string) (map[string]time.Duration, error) {
  66. slog.Debug("Fetching YouTube watch time in bulk", slog.Any("video_ids", videoIDs))
  67. apiQuery := url.Values{}
  68. apiQuery.Set("id", strings.Join(videoIDs, ","))
  69. apiQuery.Set("part", "contentDetails")
  70. // The key goes in a header to keep it out of logged URLs, and redirects are not
  71. // followed because the HTTP client forwards custom headers to the redirect target.
  72. requestBuilder := fetcher.NewRequestBuilder().
  73. WithHeader("X-Goog-Api-Key", config.Opts.YouTubeAPIKey()).
  74. WithoutRedirects().
  75. WithTimeout(config.Opts.HTTPClientTimeout()).
  76. WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  77. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(apiURL + "?" + apiQuery.Encode()))
  78. defer responseHandler.Close()
  79. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  80. slog.Warn("Unable to fetch contentDetails from YouTube API", slog.Any("error", localizedError.Error()))
  81. return nil, localizedError.Error()
  82. }
  83. if responseHandler.IsRedirect() {
  84. return nil, errors.New("youtube: unexpected redirect from the API")
  85. }
  86. videos := struct {
  87. Items []struct {
  88. ID string `json:"id"`
  89. ContentDetails struct {
  90. Duration string `json:"duration"`
  91. } `json:"contentDetails"`
  92. } `json:"items"`
  93. }{}
  94. if err := json.NewDecoder(responseHandler.Body(config.Opts.HTTPClientMaxBodySize())).Decode(&videos); err != nil {
  95. return nil, fmt.Errorf("youtube: unable to decode JSON: %v", err)
  96. }
  97. watchTimeMap := make(map[string]time.Duration, len(videos.Items))
  98. for _, video := range videos.Items {
  99. duration, err := parseISO8601Duration(video.ContentDetails.Duration)
  100. if err != nil {
  101. slog.Warn("Unable to parse ISO8601 duration", slog.Any("error", err))
  102. continue
  103. }
  104. watchTimeMap[video.ID] = duration
  105. }
  106. return watchTimeMap, nil
  107. }