2024-09-22 18:22:41 -07:00
|
|
|
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2025-02-25 08:11:06 +08:00
|
|
|
package processor // import "miniflux.app/v2/internal/reader/processor"
|
2024-09-22 18:22:41 -07:00
|
|
|
|
|
|
|
import (
|
2024-11-19 00:57:59 +00:00
|
|
|
"encoding/json"
|
2024-09-22 18:22:41 -07:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
2024-11-19 00:57:59 +00:00
|
|
|
"net/url"
|
2024-09-22 18:22:41 -07:00
|
|
|
"regexp"
|
|
|
|
"strconv"
|
2025-01-24 14:27:17 -08:00
|
|
|
"strings"
|
2024-09-22 18:22:41 -07:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/PuerkitoBio/goquery"
|
|
|
|
|
|
|
|
"miniflux.app/v2/internal/config"
|
|
|
|
"miniflux.app/v2/internal/model"
|
|
|
|
"miniflux.app/v2/internal/reader/fetcher"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
youtubeRegex = regexp.MustCompile(`youtube\.com/watch\?v=(.*)$`)
|
|
|
|
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)?)?$`)
|
|
|
|
)
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
func isYouTubeVideoURL(websiteURL string) bool {
|
|
|
|
return len(youtubeRegex.FindStringSubmatch(websiteURL)) == 2
|
2024-09-22 18:22:41 -07:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
func getVideoIDFromYouTubeURL(websiteURL string) string {
|
|
|
|
parsedWebsiteURL, err := url.Parse(websiteURL)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
2025-01-24 14:27:17 -08:00
|
|
|
|
|
|
|
return parsedWebsiteURL.Query().Get("v")
|
|
|
|
}
|
|
|
|
|
|
|
|
func shouldFetchYouTubeWatchTimeForSingleEntry(entry *model.Entry) bool {
|
|
|
|
return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeApiKey() == "" && isYouTubeVideoURL(entry.URL)
|
|
|
|
}
|
|
|
|
|
|
|
|
func shouldFetchYouTubeWatchTimeInBulk() bool {
|
|
|
|
return config.Opts.FetchYouTubeWatchTime() && config.Opts.YouTubeApiKey() != ""
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
func fetchYouTubeWatchTimeForSingleEntry(websiteURL string) (int, error) {
|
|
|
|
slog.Debug("Fetching YouTube watch time for a single entry", slog.String("website_url", websiteURL))
|
|
|
|
|
2024-09-22 18:22:41 -07:00
|
|
|
requestBuilder := fetcher.NewRequestBuilder()
|
|
|
|
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
|
|
|
|
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
|
|
|
|
|
|
|
|
responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(websiteURL))
|
|
|
|
defer responseHandler.Close()
|
|
|
|
|
|
|
|
if localizedError := responseHandler.LocalizedError(); localizedError != nil {
|
|
|
|
slog.Warn("Unable to fetch YouTube page", slog.String("website_url", websiteURL), slog.Any("error", localizedError.Error()))
|
|
|
|
return 0, localizedError.Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
doc, docErr := goquery.NewDocumentFromReader(responseHandler.Body(config.Opts.HTTPClientMaxBodySize()))
|
|
|
|
if docErr != nil {
|
|
|
|
return 0, docErr
|
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
htmlDuration, exists := doc.FindMatcher(goquery.Single(`meta[itemprop="duration"]`)).Attr("content")
|
2024-09-22 18:22:41 -07:00
|
|
|
if !exists {
|
2025-01-24 14:27:17 -08:00
|
|
|
return 0, errors.New("youtube: duration has not found")
|
2024-09-22 18:22:41 -07:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
parsedDuration, err := parseISO8601(htmlDuration)
|
2024-09-22 18:22:41 -07:00
|
|
|
if err != nil {
|
2025-01-24 14:27:17 -08:00
|
|
|
return 0, fmt.Errorf("youtube: unable to parse duration %s: %v", htmlDuration, err)
|
2024-09-22 18:22:41 -07:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
return int(parsedDuration.Minutes()), nil
|
2024-09-22 18:22:41 -07:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
func fetchYouTubeWatchTimeInBulk(entries []*model.Entry) {
|
|
|
|
var videosEntriesMapping = make(map[string]*model.Entry)
|
|
|
|
var videoIDs []string
|
2024-11-19 00:57:59 +00:00
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
for _, entry := range entries {
|
|
|
|
if !isYouTubeVideoURL(entry.URL) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
youtubeVideoID := getVideoIDFromYouTubeURL(entry.URL)
|
|
|
|
if youtubeVideoID == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
videosEntriesMapping[getVideoIDFromYouTubeURL(entry.URL)] = entry
|
|
|
|
videoIDs = append(videoIDs, youtubeVideoID)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(videoIDs) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
watchTimeMap, err := fetchYouTubeWatchTimeFromApiInBulk(videoIDs)
|
2024-11-19 00:57:59 +00:00
|
|
|
if err != nil {
|
2025-01-24 14:27:17 -08:00
|
|
|
slog.Warn("Unable to fetch YouTube watch time in bulk", slog.Any("error", err))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for videoID, watchTime := range watchTimeMap {
|
|
|
|
if entry, ok := videosEntriesMapping[videoID]; ok {
|
|
|
|
entry.ReadingTime = int(watchTime.Minutes())
|
|
|
|
}
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
2025-01-24 14:27:17 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func fetchYouTubeWatchTimeFromApiInBulk(videoIDs []string) (map[string]time.Duration, error) {
|
|
|
|
slog.Debug("Fetching YouTube watch time in bulk", slog.Any("video_ids", videoIDs))
|
2024-11-19 00:57:59 +00:00
|
|
|
|
|
|
|
apiQuery := url.Values{}
|
2025-01-24 14:27:17 -08:00
|
|
|
apiQuery.Set("id", strings.Join(videoIDs, ","))
|
2024-11-19 00:57:59 +00:00
|
|
|
apiQuery.Set("key", config.Opts.YouTubeApiKey())
|
|
|
|
apiQuery.Set("part", "contentDetails")
|
|
|
|
|
|
|
|
apiURL := url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: "www.googleapis.com",
|
|
|
|
Path: "youtube/v3/videos",
|
|
|
|
RawQuery: apiQuery.Encode(),
|
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
requestBuilder := fetcher.NewRequestBuilder()
|
|
|
|
requestBuilder.WithTimeout(config.Opts.HTTPClientTimeout())
|
|
|
|
requestBuilder.WithProxy(config.Opts.HTTPClientProxy())
|
|
|
|
|
2024-11-19 00:57:59 +00:00
|
|
|
responseHandler := fetcher.NewResponseHandler(requestBuilder.ExecuteRequest(apiURL.String()))
|
|
|
|
defer responseHandler.Close()
|
|
|
|
|
|
|
|
if localizedError := responseHandler.LocalizedError(); localizedError != nil {
|
2025-01-24 14:27:17 -08:00
|
|
|
slog.Warn("Unable to fetch contentDetails from YouTube API", slog.Any("error", localizedError.Error()))
|
|
|
|
return nil, localizedError.Error()
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
var videos youtubeVideoListResponse
|
2024-11-19 00:57:59 +00:00
|
|
|
if err := json.NewDecoder(responseHandler.Body(config.Opts.HTTPClientMaxBodySize())).Decode(&videos); err != nil {
|
2025-01-24 14:27:17 -08:00
|
|
|
return nil, fmt.Errorf("youtube: unable to decode JSON: %v", err)
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
|
|
|
|
2025-01-24 14:27:17 -08:00
|
|
|
watchTimeMap := make(map[string]time.Duration)
|
|
|
|
for _, video := range videos.Items {
|
|
|
|
duration, err := parseISO8601(video.ContentDetails.Duration)
|
|
|
|
if err != nil {
|
|
|
|
slog.Warn("Unable to parse ISO8601 duration", slog.Any("error", err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
watchTimeMap[video.ID] = duration
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
2025-01-24 14:27:17 -08:00
|
|
|
return watchTimeMap, nil
|
2024-11-19 00:57:59 +00:00
|
|
|
}
|
|
|
|
|
2024-09-22 18:22:41 -07:00
|
|
|
func parseISO8601(from string) (time.Duration, error) {
|
|
|
|
var match []string
|
|
|
|
var d time.Duration
|
|
|
|
|
|
|
|
if iso8601Regex.MatchString(from) {
|
|
|
|
match = iso8601Regex.FindStringSubmatch(from)
|
|
|
|
} else {
|
2025-01-24 14:27:17 -08:00
|
|
|
return 0, errors.New("youtube: could not parse duration string")
|
2024-09-22 18:22:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
for i, name := range iso8601Regex.SubexpNames() {
|
|
|
|
part := match[i]
|
|
|
|
if i == 0 || name == "" || part == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
val, err := strconv.ParseInt(part, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch name {
|
|
|
|
case "hour":
|
2025-01-20 16:17:06 +01:00
|
|
|
d += time.Duration(val) * time.Hour
|
2024-09-22 18:22:41 -07:00
|
|
|
case "minute":
|
2025-01-20 16:17:06 +01:00
|
|
|
d += time.Duration(val) * time.Minute
|
2024-09-22 18:22:41 -07:00
|
|
|
case "second":
|
2025-01-20 16:17:06 +01:00
|
|
|
d += time.Duration(val) * time.Second
|
2024-09-22 18:22:41 -07:00
|
|
|
default:
|
2025-01-24 14:27:17 -08:00
|
|
|
return 0, fmt.Errorf("youtube: unknown field %s", name)
|
2024-09-22 18:22:41 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return d, nil
|
|
|
|
}
|
2025-01-24 14:27:17 -08:00
|
|
|
|
|
|
|
type youtubeVideoListResponse struct {
|
|
|
|
Items []struct {
|
|
|
|
ID string `json:"id"`
|
|
|
|
ContentDetails struct {
|
|
|
|
Duration string `json:"duration"`
|
|
|
|
} `json:"contentDetails"`
|
|
|
|
} `json:"items"`
|
|
|
|
}
|