youtube.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/PuerkitoBio/goquery"
  15. "miniflux.app/v2/internal/config"
  16. "miniflux.app/v2/internal/model"
  17. "miniflux.app/v2/internal/proxyrotator"
  18. "miniflux.app/v2/internal/reader/fetcher"
  19. )
  20. var (
  21. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)$`)
  22. )
  23. func isYouTubeVideoURL(websiteURL string) bool {
  24. return len(youtubeRegex.FindStringSubmatch(websiteURL)) == 2
  25. }
  26. func getVideoIDFromYouTubeURL(websiteURL string) string {
  27. parsedWebsiteURL, err := url.Parse(websiteURL)
  28. if err != nil {
  29. return ""
  30. }
  31. return parsedWebsiteURL.Query().Get("v")
  32. }
  33. func shouldFetchYouTubeWatchTimeForSingleEntry(entry *model.Entry) bool {
  34. return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeApiKey() == "" && isYouTubeVideoURL(entry.URL)
  35. }
  36. func shouldFetchYouTubeWatchTimeInBulk() bool {
  37. return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeApiKey() != ""
  38. }
  39. func fetchYouTubeWatchTimeForSingleEntry(websiteURL string) (int, error) {
  40. slog.Debug("Fetching YouTube watch time for a single entry", slog.String("website_url", websiteURL))
  41. requestBuilder := fetcher.NewRequestBuilder()
  42. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  43. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  44. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
  45. defer responseHandler.Close()
  46. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  47. slog.Warn("Unable to fetch YouTube page", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  48. return 0, localizedError.Error()
  49. }
  50. doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
  51. if docErr != nil {
  52. return 0, docErr
  53. }
  54. htmlDuration, exists := doc.FindMatcher(goquery.Single(`meta[itemprop="duration"]`)).Attr("content")
  55. if !exists {
  56. return 0, errors.New("youtube: duration has not found")
  57. }
  58. parsedDuration, err := parseISO8601(htmlDuration)
  59. if err != nil {
  60. return 0, fmt.Errorf("youtube: unable to parse duration %s: %v", htmlDuration, err)
  61. }
  62. return int(parsedDuration.Minutes()), nil
  63. }
  64. func fetchYouTubeWatchTimeInBulk(entries []*model.Entry) {
  65. var videosEntriesMapping = make(map[string]*model.Entry, len(entries))
  66. var videoIDs []string
  67. for _, entry := range entries {
  68. if !isYouTubeVideoURL(entry.URL) {
  69. continue
  70. }
  71. youtubeVideoID := getVideoIDFromYouTubeURL(entry.URL)
  72. if youtubeVideoID == "" {
  73. continue
  74. }
  75. videosEntriesMapping[youtubeVideoID] = entry
  76. videoIDs = append(videoIDs, youtubeVideoID)
  77. }
  78. if len(videoIDs) == 0 {
  79. return
  80. }
  81. watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(videoIDs)
  82. if err != nil {
  83. slog.Warn("Unable to fetch YouTube watch time in bulk", slog.Any("error", err))
  84. return
  85. }
  86. for videoID, watchTime := range watchTimeMap {
  87. if entry, ok := videosEntriesMapping[videoID]; ok {
  88. entry.ReadingTime = int(watchTime.Minutes())
  89. }
  90. }
  91. }
  92. func fetchYouTubeWatchTimeFromApiInBulk(videoIDs []string) (map[string]time.Duration, error) {
  93. slog.Debug("Fetching YouTube watch time in bulk", slog.Any("video_ids", videoIDs))
  94. apiQuery := url.Values{}
  95. apiQuery.Set("id", strings.Join(videoIDs, ","))
  96. apiQuery.Set("key", config.Opts.YouTubeApiKey())
  97. apiQuery.Set("part", "contentDetails")
  98. apiURL := url.URL{
  99. Scheme: "https",
  100. Host: "www.googleapis.com",
  101. Path: "youtube/v3/videos",
  102. RawQuery: apiQuery.Encode(),
  103. }
  104. requestBuilder := fetcher.NewRequestBuilder()
  105. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  106. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  107. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(apiURL.String()))
  108. defer responseHandler.Close()
  109. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  110. slog.Warn("Unable to fetch contentDetails from YouTube API", slog.Any("error", localizedError.Error()))
  111. return nil, localizedError.Error()
  112. }
  113. videos := struct {
  114. Items []struct {
  115. ID string `json:"id"`
  116. ContentDetails struct {
  117. Duration string `json:"duration"`
  118. } `json:"contentDetails"`
  119. } `json:"items"`
  120. }{}
  121. if err := json.NewDecoder(responseHandler.Body(config.Opts.HTTPClientMaxBodySize())).Decode(&videos); err != nil {
  122. return nil, fmt.Errorf("youtube: unable to decode JSON: %v", err)
  123. }
  124. watchTimeMap := make(map[string]time.Duration, len(videos.Items))
  125. for _, video := range videos.Items {
  126. duration, err := parseISO8601(video.ContentDetails.Duration)
  127. if err != nil {
  128. slog.Warn("Unable to parse ISO8601 duration", slog.Any("error", err))
  129. continue
  130. }
  131. watchTimeMap[video.ID] = duration
  132. }
  133. return watchTimeMap, nil
  134. }