aboutsummaryrefslogtreecommitdiff
path: root/utils/api/tvdb/tvdb.go
blob: ee8f0a97e15ee7316aa1daff9ebaf8d1b34aeb92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package tvdb

import (
	"bytes"
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"metachan/config"
	"metachan/entities"
	"metachan/types"
	"metachan/utils/logger"
	"net/http"
	"time"
)

const (
	tvdbAPIBaseURL    = "https://api4.thetvdb.com/v4"
	tvdbLoginEndpoint = "/login"
	tvdbImageBaseURL  = "https://artworks.thetvdb.com"
	timeout           = 10 * time.Second
	episodesTimeout   = 15 * time.Second
	tokenExpiry       = 24 * time.Hour
	contentType       = "application/json"
	acceptHeader      = "application/json"
	noDescription     = "No description available"
	recapType         = "recap"
)

var (
	clientInstance = &client{
		httpClient: &http.Client{
			Timeout: timeout,
		},
	}
)

func authenticate() (string, error) {
	if clientInstance.token != "" && time.Now().Before(clientInstance.tokenExpiry) {
		return clientInstance.token, nil
	}

	if config.API.TVDBKey == "" {
		logger.Errorf("TVDB", "TVDB API key is not set")
		return "", errors.New("TVDB API key is not set")
	}

	logger.Debugf("TVDB", "Authenticating with TVDB API")

	authBody := map[string]string{"apikey": config.API.TVDBKey}
	jsonBody, err := json.Marshal(authBody)
	if err != nil {
		logger.Errorf("TVDB", "Failed to marshal auth body: %v", err)
		return "", errors.New("failed to marshal auth body")
	}

	req, err := http.NewRequest("POST", tvdbAPIBaseURL+tvdbLoginEndpoint, bytes.NewBuffer(jsonBody))
	if err != nil {
		logger.Errorf("TVDB", "Failed to create auth request: %v", err)
		return "", errors.New("failed to create auth request")
	}

	req.Header.Add("Content-Type", contentType)

	resp, err := clientInstance.httpClient.Do(req)
	if err != nil {
		logger.Errorf("TVDB", "Failed to authenticate: %v", err)
		return "", errors.New("failed to authenticate")
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		logger.Errorf("TVDB", "Authentication failed with status: %d", resp.StatusCode)
		return "", errors.New("authentication failed")
	}

	var authResp types.TVDBAuthResponse
	if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
		logger.Errorf("TVDB", "Failed to decode auth response: %v", err)
		return "", errors.New("failed to decode auth response")
	}

	if authResp.Data.Token == "" {
		logger.Errorf("TVDB", "No token received from TVDB")
		return "", errors.New("no token received from TVDB")
	}

	clientInstance.token = authResp.Data.Token
	clientInstance.tokenExpiry = time.Now().Add(tokenExpiry)

	logger.Successf("TVDB", "Successfully authenticated with TVDB")

	return clientInstance.token, nil
}

func GetSeriesEpisodes(tvdbID int) ([]types.TVDBEpisode, error) {
	token, err := authenticate()
	if err != nil {
		logger.Errorf("TVDB", "Failed to authenticate with TVDB for series %d: %v", tvdbID, err)
		return nil, errors.New("failed to authenticate with TVDB")
	}

	logger.Debugf("TVDB", "Fetching episodes for TVDB series %d", tvdbID)

	tempClient := &http.Client{Timeout: episodesTimeout}

	url := fmt.Sprintf("%s/series/%d/episodes/default", tvdbAPIBaseURL, tvdbID)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		logger.Errorf("TVDB", "Failed to create request for series %d: %v", tvdbID, err)
		return nil, errors.New("failed to create request")
	}

	req.Header.Add("Authorization", "Bearer "+token)
	req.Header.Add("Accept", acceptHeader)

	resp, err := tempClient.Do(req)
	if err != nil {
		logger.Errorf("TVDB", "Failed to fetch episodes for series %d: %v", tvdbID, err)
		return nil, errors.New("failed to fetch episodes")
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		logger.Errorf("TVDB", "Failed to fetch episodes with status: %d", resp.StatusCode)
		return nil, errors.New("failed to fetch episodes")
	}

	var episodesResp types.TVDBEpisodesResponse
	if err := json.NewDecoder(resp.Body).Decode(&episodesResp); err != nil {
		logger.Errorf("TVDB", "Failed to decode episodes response for series %d: %v", tvdbID, err)
		return nil, errors.New("failed to decode episodes response")
	}

	logger.Successf("TVDB", "Successfully fetched %d episodes from TVDB for series %d", len(episodesResp.Data.Episodes), tvdbID)

	return episodesResp.Data.Episodes, nil
}

func EnrichEpisodesFromTVDB(anime *entities.Anime, tvdbEpisodes []types.TVDBEpisode) {
	if anime == nil || len(anime.Episodes) == 0 {
		return
	}

	malID := anime.MALID

	for i, ep := range tvdbEpisodes {
		if i >= len(anime.Episodes) {
			break
		}

		episode := &anime.Episodes[i]

		if ep.Name != "" {
			episode.Title = entities.EpisodeTitle{
				English:  ep.Name,
				Japanese: episode.Title.Japanese,
				Romaji:   episode.Title.Romaji,
			}
		}

		if ep.Image != "" {
			episode.ThumbnailURL = ep.Image
		}

		if ep.Overview != "" {
			episode.Description = ep.Overview
		} else {
			episode.Description = noDescription
		}

		if ep.Aired != "" {
			episode.Aired = ep.Aired
		}

		if ep.FinaleType != nil && *ep.FinaleType == recapType {
			episode.Recap = true
		}

		episode.EpisodeNumber = ep.Number
		episode.EpisodeLength = float64(ep.Runtime)

		titleForID := ep.Name
		if titleForID == "" {
			if episode.Title.English != "" {
				titleForID = episode.Title.English
			} else if episode.Title.Romaji != "" {
				titleForID = episode.Title.Romaji
			}
		}
		episode.EpisodeID = generateEpisodeID(malID, ep.Number, titleForID)
	}
}

func generateEpisodeID(malID int, episodeNumber int, title string) string {
	uniqueString := fmt.Sprintf("%d-%d-%s", malID, episodeNumber, title)
	hash := md5.Sum([]byte(uniqueString))
	return fmt.Sprintf("%x", hash)
}