Commit 4358e9d516

4358e9d516c5aff26e4667ab85de93404b05b409

parent: 4e6d12436d

Unregistered key

chokerman <44473782+justchokingaround@users.noreply.github.com> · 2025-02-15 12:36 UTC
committer: <noreply@github.com>

 feat(episode): implement concurrent URL fetching with rate limiting  (#39)

* docs: add macOS installation instructions

* fix: handle currently airing anime episodes correctly

- Add IsAiring field to track airing status of anime
- Improve GetAnimeDataByID to fetch and handle airing status
- Fix completion logic for currently airing shows

* chore: Sprintf -> Errorf

* feat(episode): implement concurrent URL fetching with rate limiting

- Add parallel processing of source URLs with goroutines
- Implement rate limiting (50ms) to prevent API overload
- Add timeout handling (10s) for request completion
- Maintain result order using ordered collection
- Add error handling and partial result recovery
- Improve logging for better debugging

Layout: unified · split

internal/anilist.go +1 −1
@@ -59,7 +59,7 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
59 populateMap := func(entries []Entry) { 59 populateMap := func(entries []Entry) {
60 for _, entry := range entries { 60 for _, entry := range entries {
61 // Only include entries with a non-empty English title 61 // Only include entries with a non-empty English title
62 Log(fmt.Sprintf("AnimeNameLanguage: ", userCurdConfig.AnimeNameLanguage), logFile) 62 Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage), logFile)
63 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" { 63 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
64 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ 64 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
65 Title: entry.Media.Title.English, 65 Title: entry.Media.Title.English,
internal/aniskip.go +5 −5
@@ -10,8 +10,8 @@ import (
10 10
11// skipTimesResponse struct to hold the response from the AniSkip API 11// skipTimesResponse struct to hold the response from the AniSkip API
12type skipTimesResponse struct { 12type skipTimesResponse struct {
13 Found bool `json:"found"` 13 Found bool `json:"found"`
14 Results []skipResult `json:"results"` 14 Results []skipResult `json:"results"`
15} 15}
16 16
17// skipResult struct to hold individual skip result data 17// skipResult struct to hold individual skip result data
@@ -32,7 +32,7 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
32 32
33 resp, err := http.Get(url) 33 resp, err := http.Get(url)
34 if err != nil { 34 if err != nil {
35 Log(fmt.Sprintf("error fetching data from AniSkip API: %w", err), logFile) 35 Log(fmt.Errorf("error fetching data from AniSkip API: %w", err), logFile)
36 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err) 36 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err)
37 } 37 }
38 defer resp.Body.Close() 38 defer resp.Body.Close()
@@ -44,7 +44,7 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
44 44
45 body, err := io.ReadAll(resp.Body) 45 body, err := io.ReadAll(resp.Body)
46 if err != nil { 46 if err != nil {
47 Log(fmt.Sprintf("failed to read response body: %w", err), logFile) 47 Log(fmt.Errorf("failed to read response body %w", err), logFile)
48 return "", fmt.Errorf("failed to read response body %w", err) 48 return "", fmt.Errorf("failed to read response body %w", err)
49 } 49 }
50 50
@@ -100,4 +100,4 @@ func GetAndParseAniSkipData(animeMalId int, episode int, timePrecision int, anim
100 return err 100 return err
101 } 101 }
102 return ParseAniSkipResponse(responseText, anime, timePrecision) 102 return ParseAniSkipResponse(responseText, anime, timePrecision)
103}\ No newline at end of file 103}
internal/episode_url.go +127 −21
@@ -8,10 +8,10 @@ import (
8 "net/url" 8 "net/url"
9 "regexp" 9 "regexp"
10 "strings" 10 "strings"
11 "time"
11 "unicode" 12 "unicode"
12) 13)
13 14
14
15type allanimeResponse struct { 15type allanimeResponse struct {
16 Data struct { 16 Data struct {
17 Episode struct { 17 Episode struct {
@@ -94,7 +94,7 @@ func extractLinks(provider_id string) map[string]interface{} {
94 return videoData 94 return videoData
95} 95}
96 96
97// Get anime episode url respective to given config 97// Get anime episode url respective to given config
98// If the link is found, it returns a list of links. Otherwise, it returns an error. 98// If the link is found, it returns a list of links. Otherwise, it returns an error.
99// 99//
100// Parameters: 100// Parameters:
@@ -145,35 +145,141 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
145 return nil, err 145 return nil, err
146 } 146 }
147 147
148 responseStr := string(body)
149
150 // Unmarshal the JSON data into the struct
151 var response allanimeResponse 148 var response allanimeResponse
152 err = json.Unmarshal([]byte(responseStr), &response) 149 err = json.Unmarshal(body, &response)
153 if err != nil { 150 if err != nil {
154 Log(fmt.Sprint("Error parsing JSON: ", err), logFile) 151 Log(fmt.Sprint("Error parsing JSON: ", err), logFile)
152 return nil, err
155 } 153 }
156 154
157 var allinks []string // This will be returned 155 type result struct {
156 index int
157 links []string
158 err error
159 }
158 160
159 // Iterate through the SourceUrls and print each URL 161 // Pre-count valid URLs and create slice to preserve order
162 validURLs := make([]string, 0)
160 for _, url := range response.Data.Episode.SourceUrls { 163 for _, url := range response.Data.Episode.SourceUrls {
161 if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) { // Source Url 3rd letter is a number (it stars as --32f23k31jk) 164 if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
162 decodedProviderID := decodeProviderID(url.SourceUrl[2:]) // Decode the source url to get the provider id 165 validURLs = append(validURLs, url.SourceUrl)
163 extractedLinks := extractLinks(decodedProviderID) // Extract the links using provider id 166 }
164 if linksInterface, ok := extractedLinks["links"].([]interface{}); ok { 167 }
165 for _, linkInterface := range linksInterface { 168
166 if linkMap, ok := linkInterface.(map[string]interface{}); ok { 169 if len(validURLs) == 0 {
167 if link, ok := linkMap["link"].(string); ok { 170 return nil, fmt.Errorf("no valid source URLs found in response")
168 allinks = append(allinks, link) // Add all extracted links into allinks 171 }
169 } 172
170 } 173 // Create channels for results and a slice to store ordered results
174 results := make(chan result, len(validURLs))
175 orderedResults := make([][]string, len(validURLs))
176
177 // Create rate limiter
178 rateLimiter := time.NewTicker(50 * time.Millisecond)
179 defer rateLimiter.Stop()
180
181 // Launch goroutines
182 for i, sourceUrl := range validURLs {
183 go func(idx int, url string) {
184 <-rateLimiter.C // Rate limit the requests
185
186 decodedProviderID := decodeProviderID(url[2:])
187 Log(fmt.Sprintf("Processing URL %d/%d with provider ID: %s", idx+1, len(validURLs), decodedProviderID), logFile)
188
189 extractedLinks := extractLinks(decodedProviderID)
190
191 if extractedLinks == nil {
192 results <- result{
193 index: idx,
194 err: fmt.Errorf("failed to extract links for provider %s", decodedProviderID),
195 }
196 return
197 }
198
199 linksInterface, ok := extractedLinks["links"].([]interface{})
200 if !ok {
201 results <- result{
202 index: idx,
203 err: fmt.Errorf("links field is not []interface{} for provider %s", decodedProviderID),
204 }
205 return
206 }
207
208 var links []string
209 for _, linkInterface := range linksInterface {
210 linkMap, ok := linkInterface.(map[string]interface{})
211 if !ok {
212 Log(fmt.Sprintf("Warning: invalid link format for provider %s", decodedProviderID), logFile)
213 continue
171 } 214 }
215
216 link, ok := linkMap["link"].(string)
217 if !ok {
218 Log(fmt.Sprintf("Warning: link field is not string for provider %s", decodedProviderID), logFile)
219 continue
220 }
221
222 links = append(links, link)
223 }
224
225 results <- result{
226 index: idx,
227 links: links,
228 }
229 }(i, sourceUrl)
230 }
231
232 // Collect results with timeout
233 timeout := time.After(10 * time.Second)
234 var collectedErrors []error
235 successCount := 0
236
237 // Collect results maintaining order
238 for successCount < len(validURLs) {
239 select {
240 case res := <-results:
241 if res.err != nil {
242 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err), logFile)
243 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
172 } else { 244 } else {
173 Log("Links field is not of the expected type []interface{}", logFile) 245 orderedResults[res.index] = res.links
246 successCount++
247 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, len(validURLs)), logFile)
248 }
249 case <-timeout:
250 if successCount > 0 {
251 Log(fmt.Sprintf("Timeout reached with %d/%d successful results", successCount, len(validURLs)), logFile)
252 // Flatten available results
253 return flattenResults(orderedResults), nil
174 } 254 }
255 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
175 } 256 }
176 } 257 }
177 258
178 return allinks, nil 259 // If we have any errors but also some successes, log errors but continue
179}\ No newline at end of file 260 if len(collectedErrors) > 0 {
261 Log(fmt.Sprintf("Completed with %d errors: %v", len(collectedErrors), collectedErrors), logFile)
262 }
263
264 // Flatten and return results
265 allLinks := flattenResults(orderedResults)
266 if len(allLinks) == 0 {
267 return nil, fmt.Errorf("no valid links found from %d URLs: %v", len(validURLs), collectedErrors)
268 }
269
270 return allLinks, nil
271}
272
273// converts the ordered slice of link slices into a single slice
274func flattenResults(results [][]string) []string {
275 var totalLen int
276 for _, r := range results {
277 totalLen += len(r)
278 }
279
280 allLinks := make([]string, 0, totalLen)
281 for _, links := range results {
282 allLinks = append(allLinks, links...)
283 }
284 return allLinks
285}
internal/localTracking.go +6 −6
@@ -234,7 +234,7 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
234 CurdOut(fmt.Sprintf("Error writing record: %v", err)) 234 CurdOut(fmt.Sprintf("Error writing record: %v", err))
235 } 235 }
236 } 236 }
237 237
238 return nil 238 return nil
239} 239}
240 240
@@ -259,7 +259,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
259 userInput, err := GetUserInputFromRofi("Enter the anime name") 259 userInput, err := GetUserInputFromRofi("Enter the anime name")
260 if err != nil { 260 if err != nil {
261 Log("Error getting user input: "+err.Error(), logFile) 261 Log("Error getting user input: "+err.Error(), logFile)
262 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error())) 262 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
263 } 263 }
264 query = userInput 264 query = userInput
265 } else { 265 } else {
@@ -298,7 +298,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
298 userInput, err := GetUserInputFromRofi("Enter the episode number") 298 userInput, err := GetUserInputFromRofi("Enter the episode number")
299 if err != nil { 299 if err != nil {
300 Log("Error getting episode number: "+err.Error(), logFile) 300 Log("Error getting episode number: "+err.Error(), logFile)
301 ExitCurd(fmt.Errorf("Error getting episode number: "+err.Error())) 301 ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
302 } 302 }
303 episodeNumber, err = strconv.Atoi(userInput) 303 episodeNumber, err = strconv.Atoi(userInput)
304 if err != nil { 304 if err != nil {
@@ -311,7 +311,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
311 } 311 }
312 312
313 anime.Ep.Number = episodeNumber 313 anime.Ep.Number = episodeNumber
314 314
315 for { 315 for {
316 // Get episode link 316 // Get episode link
317 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 317 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
@@ -335,8 +335,8 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
335 335
336 anime.Ep.Player.SocketPath = mpvSocketPath 336 anime.Ep.Player.SocketPath = mpvSocketPath
337 anime.Ep.Started = false 337 anime.Ep.Started = false
338 338
339 Log(fmt.Sprintf("Started mpvsocketpath ", anime.Ep.Player.SocketPath), logFile) 339 Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath), logFile)
340 340
341 // Get video duration 341 // Get video duration
342 go func() { 342 go func() {