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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
|
package tvdb
import (
"bytes"
"crypto/md5"
"encoding/json"
"fmt"
"metachan/config"
"metachan/database"
"metachan/entities"
"metachan/types"
"metachan/utils/logger"
"net/http"
"time"
)
var tvdbToken string
var tvdbTokenExpiry time.Time
// authenticateTVDB authenticates with TVDB API and returns a token
func authenticateTVDB() (string, error) {
// Check if we have a valid token
if tvdbToken != "" && time.Now().Before(tvdbTokenExpiry) {
return tvdbToken, nil
}
if config.Config.TVDB.APIKey == "" {
return "", fmt.Errorf("TVDB API key is not set")
}
logger.Log("Authenticating with TVDB API", logger.LogOptions{
Level: logger.Debug,
Prefix: "TVDB",
})
client := &http.Client{Timeout: 10 * time.Second}
// Create request body with apikey
authBody := map[string]string{"apikey": config.Config.TVDB.APIKey}
jsonBody, err := json.Marshal(authBody)
if err != nil {
return "", fmt.Errorf("failed to marshal auth body: %w", err)
}
req, err := http.NewRequest("POST", "https://api4.thetvdb.com/v4/login", bytes.NewBuffer(jsonBody))
if err != nil {
return "", fmt.Errorf("failed to create auth request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to authenticate: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("authentication failed with status: %d", resp.StatusCode)
}
var authResp TVDBAuthResponse
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return "", fmt.Errorf("failed to decode auth response: %w", err)
}
if authResp.Data.Token == "" {
return "", fmt.Errorf("no token received from TVDB")
}
// Store token and set expiry (TVDB tokens typically last 30 days, but we'll refresh after 24 hours to be safe)
tvdbToken = authResp.Data.Token
tvdbTokenExpiry = time.Now().Add(24 * time.Hour)
logger.Log("Successfully authenticated with TVDB", logger.LogOptions{
Level: logger.Success,
Prefix: "TVDB",
})
return tvdbToken, nil
}
// GetSeriesEpisodes fetches all episodes for a TVDB series
func GetSeriesEpisodes(tvdbID int) ([]TVDBEpisode, error) {
token, err := authenticateTVDB()
if err != nil {
return nil, fmt.Errorf("failed to authenticate with TVDB: %w", err)
}
logger.Log(fmt.Sprintf("Fetching episodes for TVDB series %d", tvdbID), logger.LogOptions{
Level: logger.Debug,
Prefix: "TVDB",
})
client := &http.Client{Timeout: 15 * time.Second}
// TVDB v4 API endpoint for episodes
url := fmt.Sprintf("https://api4.thetvdb.com/v4/series/%d/episodes/default", tvdbID)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch episodes: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch episodes with status: %d", resp.StatusCode)
}
var episodesResp TVDBEpisodesResponse
if err := json.NewDecoder(resp.Body).Decode(&episodesResp); err != nil {
return nil, fmt.Errorf("failed to decode episodes response: %w", err)
}
logger.Log(fmt.Sprintf("Successfully fetched %d episodes from TVDB for series %d", len(episodesResp.Data.Episodes), tvdbID), logger.LogOptions{
Level: logger.Success,
Prefix: "TVDB",
})
return episodesResp.Data.Episodes, nil
}
// ConvertTVDBEpisodesToAnimeEpisodes converts TVDB episodes to anime episode format
func ConvertTVDBEpisodesToAnimeEpisodes(tvdbEpisodes []TVDBEpisode) []types.AnimeSingleEpisode {
var animeEpisodes []types.AnimeSingleEpisode
const tvdbImageBaseURL = "https://artworks.thetvdb.com"
for _, ep := range tvdbEpisodes {
// Generate episode ID from name
titles := types.EpisodeTitles{
English: ep.Name,
Japanese: "",
Romaji: "",
}
thumbnailURL := ""
if ep.Image != "" {
thumbnailURL = ep.Image
}
description := ep.Overview
if description == "" {
description = "No description available"
}
isRecap := false
if ep.FinaleType != nil && *ep.FinaleType == "recap" {
isRecap = true
}
animeEpisodes = append(animeEpisodes, types.AnimeSingleEpisode{
ID: generateEpisodeID(titles),
Titles: titles,
Description: description,
Aired: ep.Aired,
ThumbnailURL: thumbnailURL,
Score: 0,
Filler: false,
Recap: isRecap,
ForumURL: "",
URL: "",
})
}
return animeEpisodes
}
// generateEpisodeID creates a unique episode ID from titles
func generateEpisodeID(titles types.EpisodeTitles) string {
var title string
if titles.English != "" {
title = titles.English
} else if titles.Romaji != "" {
title = titles.Romaji
} else {
title = titles.Japanese
}
// MD5 hash for ID generation to match Jikan episode IDs
hash := md5.Sum([]byte(title))
return fmt.Sprintf("%x", hash)
}
// FindSeasonMappings finds all anime mappings that belong to the same series based on TVDB ID
func FindSeasonMappings(tvdbID int) ([]entities.AnimeMapping, error) {
logger.Log(fmt.Sprintf("Finding season mappings for TVDB ID %d", tvdbID), logger.LogOptions{
Level: logger.Debug,
Prefix: "TVDB",
})
// Use our database function to find all mappings with the same TVDB ID
mappings, err := database.GetAnimeMappingsByTVDBID(tvdbID)
if err != nil {
return nil, fmt.Errorf("failed to get season mappings: %w", err)
}
if len(mappings) == 0 {
logger.Log(fmt.Sprintf("No season mappings found for TVDB ID %d", tvdbID), logger.LogOptions{
Level: logger.Debug,
Prefix: "TVDB",
})
} else {
logger.Log(fmt.Sprintf("Found %d season mappings for TVDB ID %d", len(mappings), tvdbID), logger.LogOptions{
Level: logger.Info,
Prefix: "TVDB",
})
}
return mappings, nil
}
|