reddit: prevent infinite loop on error

This commit is contained in:
stefanodvx 2025-04-22 12:06:13 +02:00
parent 7e69320d2c
commit 34827fe852
2 changed files with 19 additions and 8 deletions

View file

@ -88,7 +88,7 @@ func MediaListFromAPI(ctx *models.DownloadContext) ([]*models.Media, error) {
contentID := ctx.MatchedContentID contentID := ctx.MatchedContentID
contentURL := ctx.MatchedContentURL contentURL := ctx.MatchedContentURL
manifest, err := GetRedditData(client, host, slug) manifest, err := GetRedditData(client, host, slug, false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -100,6 +100,7 @@ func MediaListFromAPI(ctx *models.DownloadContext) ([]*models.Media, error) {
data := manifest[0].Data.Children[0].Data data := manifest[0].Data.Children[0].Data
title := data.Title title := data.Title
isNsfw := data.Over18 isNsfw := data.Over18
var mediaList []*models.Media var mediaList []*models.Media
if !data.IsVideo { if !data.IsVideo {
@ -228,6 +229,7 @@ func GetRedditData(
client models.HTTPClient, client models.HTTPClient,
host string, host string,
slug string, slug string,
raise bool,
) (RedditResponse, error) { ) (RedditResponse, error) {
url := fmt.Sprintf("https://%s/%s/.json", host, slug) url := fmt.Sprintf("https://%s/%s/.json", host, slug)
@ -252,13 +254,16 @@ func GetRedditData(
defer res.Body.Close() defer res.Body.Close()
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
if raise {
return nil, fmt.Errorf("failed to get reddit data: %s", res.Status)
}
// try with alternative domain // try with alternative domain
altHost := "old.reddit.com" altHost := "old.reddit.com"
if host == "old.reddit.com" { if host == "old.reddit.com" {
altHost = "www.reddit.com" altHost = "www.reddit.com"
} }
return GetRedditData(client, altHost, slug) return GetRedditData(client, altHost, slug, true)
} }
var response RedditResponse var response RedditResponse

View file

@ -1,13 +1,19 @@
package reddit package reddit
type RedditResponse []struct { type Child struct {
Data struct { Data *PostData `json:"data"`
Children []struct {
Data PostData `json:"data"`
} `json:"children"`
} `json:"data"`
} }
type Data struct {
Children []*Child `json:"children"`
}
type ResponseItem struct {
Data *Data `json:"data"`
}
type RedditResponse []*ResponseItem
type PostData struct { type PostData struct {
ID string `json:"id"` ID string `json:"id"`
Title string `json:"title"` Title string `json:"title"`