youtube.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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/reader/fetcher"
  18. )
  19. var (
  20. youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)$`)
  21. 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)?)?$`)
  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.WithProxy(config.Opts.HTTPClientProxy())
  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)
  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[getVideoIDFromYouTubeURL(entry.URL)] = 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.WithProxy(config.Opts.HTTPClientProxy())
  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. var videos youtubeVideoListResponse
  114. if err := json.NewDecoder(responseHandler.Body(config.Opts.HTTPClientMaxBodySize())).Decode(&videos); err != nil {
  115. return nil, fmt.Errorf("youtube: unable to decode JSON: %v", err)
  116. }
  117. watchTimeMap := make(map[string]time.Duration)
  118. for _, video := range videos.Items {
  119. duration, err := parseISO8601(video.ContentDetails.Duration)
  120. if err != nil {
  121. slog.Warn("Unable to parse ISO8601 duration", slog.Any("error", err))
  122. continue
  123. }
  124. watchTimeMap[video.ID] = duration
  125. }
  126. return watchTimeMap, nil
  127. }
  128. func parseISO8601(from string) (time.Duration, error) {
  129. var match []string
  130. var d time.Duration
  131. if iso8601Regex.MatchString(from) {
  132. match = iso8601Regex.FindStringSubmatch(from)
  133. } else {
  134. return 0, errors.New("youtube: could not parse duration string")
  135. }
  136. for i, name := range iso8601Regex.SubexpNames() {
  137. part := match[i]
  138. if i == 0 || name == "" || part == "" {
  139. continue
  140. }
  141. val, err := strconv.ParseInt(part, 10, 64)
  142. if err != nil {
  143. return 0, err
  144. }
  145. switch name {
  146. case "hour":
  147. d += time.Duration(val) * time.Hour
  148. case "minute":
  149. d += time.Duration(val) * time.Minute
  150. case "second":
  151. d += time.Duration(val) * time.Second
  152. default:
  153. return 0, fmt.Errorf("youtube: unknown field %s", name)
  154. }
  155. }
  156. return d, nil
  157. }
  158. type youtubeVideoListResponse struct {
  159. Items []struct {
  160. ID string `json:"id"`
  161. ContentDetails struct {
  162. Duration string `json:"duration"`
  163. } `json:"contentDetails"`
  164. } `json:"items"`
  165. }