package youtube import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" "time" "supermarket/internal/models" ) const apiBase = "https://www.googleapis.com/youtube/v3" type Client struct { apiKey string maxResults int http *http.Client } func New(apiKey string, maxResults int) *Client { return &Client{ apiKey: apiKey, maxResults: maxResults, http: &http.Client{Timeout: 15 * time.Second}, } } // SearchVideos searches YouTube for videos matching the query published after `since`. func (c *Client) SearchVideos(ctx context.Context, query string, since time.Time, appName string) ([]models.ContentItem, error) { params := url.Values{ "part": {"snippet"}, "q": {query}, "type": {"video"}, "order": {"date"}, "publishedAfter": {since.UTC().Format(time.RFC3339)}, "maxResults": {strconv.Itoa(clamp(c.maxResults, 1, 50))}, "key": {c.apiKey}, } return c.doSearch(ctx, params, appName) } // GetChannelVideos fetches recent videos from a specific YouTube channel. func (c *Client) GetChannelVideos(ctx context.Context, channelID string, since time.Time, appName string) ([]models.ContentItem, error) { params := url.Values{ "part": {"snippet"}, "channelId": {channelID}, "type": {"video"}, "order": {"date"}, "publishedAfter": {since.UTC().Format(time.RFC3339)}, "maxResults": {strconv.Itoa(clamp(c.maxResults, 1, 50))}, "key": {c.apiKey}, } return c.doSearch(ctx, params, appName) } func (c *Client) doSearch(ctx context.Context, params url.Values, appName string) ([]models.ContentItem, error) { endpoint := apiBase + "/search?" + params.Encode() req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } res, err := c.http.Do(req) if err != nil { return nil, err } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("youtube HTTP %d: %s", res.StatusCode, raw) } var resp searchResponse if err := json.Unmarshal(raw, &resp); err != nil { return nil, err } var items []models.ContentItem for _, r := range resp.Items { ts, _ := time.Parse(time.RFC3339, r.Snippet.PublishedAt) videoURL := "https://www.youtube.com/watch?v=" + r.ID.VideoID items = append(items, models.ContentItem{ ID: r.ID.VideoID, Source: models.SourceYouTube, Author: r.Snippet.ChannelTitle, AuthorHandle: r.Snippet.ChannelTitle, Title: r.Snippet.Title, Body: r.Snippet.Description, URL: videoURL, PublishedAt: ts, AppName: appName, }) } return items, nil } type searchResponse struct { Items []struct { ID struct { VideoID string `json:"videoId"` } `json:"id"` Snippet struct { Title string `json:"title"` Description string `json:"description"` ChannelTitle string `json:"channelTitle"` PublishedAt string `json:"publishedAt"` } `json:"snippet"` } `json:"items"` } func clamp(v, min, max int) int { if v < min { return min } if v > max { return max } return v }