youtube.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. iso8601Regex = regexp.MustCompile(`^P((?P<year>\d+)Y)?((?P<month>\d+)M)?((?P<week>\d+)W)?((?P<day>\d+)D)?(T((?P<hour>\d+)H)?((?P<minute>\d+)M)?((?P<second>\d+)S)?)?$`)
  23. )
  24. func isYouTubeVideoURL(websiteURL string) bool {
  25. return len(youtubeRegex.FindStringSubmatch(websiteURL)) == 2
  26. }
  27. func getVideoIDFromYouTubeURL(websiteURL string) string {
  28. parsedWebsiteURL, err := url.Parse(websiteURL)
  29. if err != nil {
  30. return ""
  31. }
  32. return parsedWebsiteURL.Query().Get("v")
  33. }
  34. func shouldFetchYouTubeWatchTimeForSingleEntry(entry *model.Entry) bool {
  35. return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeApiKey() == "" && isYouTubeVideoURL(entry.URL)
  36. }
  37. func shouldFetchYouTubeWatchTimeInBulk() bool {
  38. return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeApiKey() != ""
  39. }
  40. func fetchYouTubeWatchTimeForSingleEntry(websiteURL string) (int, error) {
  41. slog.Debug("Fetching YouTube watch time for a single entry", slog.String("website_url", websiteURL))
  42. requestBuilder := fetcher.NewRequestBuilder()
  43. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  44. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  45. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
  46. defer responseHandler.Close()
  47. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  48. slog.Warn("Unable to fetch YouTube page", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
  49. return 0, localizedError.Error()
  50. }
  51. doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
  52. if docErr != nil {
  53. return 0, docErr
  54. }
  55. htmlDuration, exists := doc.FindMatcher(goquery.Single(`meta[itemprop="duration"]`)).Attr("content")
  56. if !exists {
  57. return 0, errors.New("youtube: duration has not found")
  58. }
  59. parsedDuration, err := parseISO8601(htmlDuration)
  60. if err != nil {
  61. return 0, fmt.Errorf("youtube: unable to parse duration %s: %v", htmlDuration, err)
  62. }
  63. return int(parsedDuration.Minutes()), nil
  64. }
  65. func fetchYouTubeWatchTimeInBulk(entries []*model.Entry) {
  66. var videosEntriesMapping = make(map[string]*model.Entry)
  67. var videoIDs []string
  68. for _, entry := range entries {
  69. if !isYouTubeVideoURL(entry.URL) {
  70. continue
  71. }
  72. youtubeVideoID := getVideoIDFromYouTubeURL(entry.URL)
  73. if youtubeVideoID == "" {
  74. continue
  75. }
  76. videosEntriesMapping[getVideoIDFromYouTubeURL(entry.URL)] = entry
  77. videoIDs = append(videoIDs, youtubeVideoID)
  78. }
  79. if len(videoIDs) == 0 {
  80. return
  81. }
  82. watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(videoIDs)
  83. if err != nil {
  84. slog.Warn("Unable to fetch YouTube watch time in bulk", slog.Any("error", err))
  85. return
  86. }
  87. for videoID, watchTime := range watchTimeMap {
  88. if entry, ok := videosEntriesMapping[videoID]; ok {
  89. entry.ReadingTime = int(watchTime.Minutes())
  90. }
  91. }
  92. }
  93. func fetchYouTubeWatchTimeFromApiInBulk(videoIDs []string) (map[string]time.Duration, error) {
  94. slog.Debug("Fetching YouTube watch time in bulk", slog.Any("video_ids", videoIDs))
  95. apiQuery := url.Values{}
  96. apiQuery.Set("id", strings.Join(videoIDs, ","))
  97. apiQuery.Set("key", config.Opts.YouTubeApiKey())
  98. apiQuery.Set("part", "contentDetails")
  99. apiURL := url.URL{
  100. Scheme: "https",
  101. Host: "www.googleapis.com",
  102. Path: "youtube/v3/videos",
  103. RawQuery: apiQuery.Encode(),
  104. }
  105. requestBuilder := fetcher.NewRequestBuilder()
  106. requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
  107. requestBuilder.WithProxyRotator(proxyrotator.ProxyRotatorInstance)
  108. responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(apiURL.String()))
  109. defer responseHandler.Close()
  110. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  111. slog.Warn("Unable to fetch contentDetails from YouTube API", slog.Any("error", localizedError.Error()))
  112. return nil, localizedError.Error()
  113. }
  114. var videos youtubeVideoListResponse
  115. if err := json.NewDecoder(responseHandler.Body(config.Opts.HTTPClientMaxBodySize())).Decode(&videos); err != nil {
  116. return nil, fmt.Errorf("youtube: unable to decode JSON: %v", err)
  117. }
  118. watchTimeMap := make(map[string]time.Duration)
  119. for _, video := range videos.Items {
  120. duration, err := parseISO8601(video.ContentDetails.Duration)
  121. if err != nil {
  122. slog.Warn("Unable to parse ISO8601 duration", slog.Any("error", err))
  123. continue
  124. }
  125. watchTimeMap[video.ID] = duration
  126. }
  127. return watchTimeMap, nil
  128. }
  129. func parseISO8601(from string) (time.Duration, error) {
  130. var match []string
  131. var d time.Duration
  132. if iso8601Regex.MatchString(from) {
  133. match = iso8601Regex.FindStringSubmatch(from)
  134. } else {
  135. return 0, errors.New("youtube: could not parse duration string")
  136. }
  137. for i, name := range iso8601Regex.SubexpNames() {
  138. part := match[i]
  139. if i == 0 || name == "" || part == "" {
  140. continue
  141. }
  142. val, err := strconv.ParseInt(part, 10, 64)
  143. if err != nil {
  144. return 0, err
  145. }
  146. switch name {
  147. case "hour":
  148. d += time.Duration(val) * time.Hour
  149. case "minute":
  150. d += time.Duration(val) * time.Minute
  151. case "second":
  152. d += time.Duration(val) * time.Second
  153. default:
  154. return 0, fmt.Errorf("youtube: unknown field %s", name)
  155. }
  156. }
  157. return d, nil
  158. }
  159. type youtubeVideoListResponse struct {
  160. Items []struct {
  161. ID string `json:"id"`
  162. ContentDetails struct {
  163. Duration string `json:"duration"`
  164. } `json:"contentDetails"`
  165. } `json:"items"`
  166. }