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 {
5959 populateMap := func(entries []Entry) {
6060 for _, entry := range entries {
6161 // 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)
6363 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
6464 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
6565 Title: entry.Media.Title.English,
internal/aniskip.go +5 −5
@@ -10,8 +10,8 @@ import (
1010
1111// skipTimesResponse struct to hold the response from the AniSkip API
1212type skipTimesResponse struct {
13 Found bool `json:"found"`
14 Results []skipResult `json:"results"`
13 Found bool `json:"found"`
14 Results []skipResult `json:"results"`
1515}
1616
1717// skipResult struct to hold individual skip result data
@@ -32,7 +32,7 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
3232
3333 resp, err := http.Get(url)
3434 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)
3636 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err)
3737 }
3838 defer resp.Body.Close()
@@ -44,7 +44,7 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
4444
4545 body, err := io.ReadAll(resp.Body)
4646 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)
4848 return "", fmt.Errorf("failed to read response body %w", err)
4949 }
5050
@@ -100,4 +100,4 @@ func GetAndParseAniSkipData(animeMalId int, episode int, timePrecision int, anim
100100 return err
101101 }
102102 return ParseAniSkipResponse(responseText, anime, timePrecision)
103}
\ No newline at end of file
103}
internal/episode_url.go +127 −21
@@ -8,10 +8,10 @@ import (
88 "net/url"
99 "regexp"
1010 "strings"
11 "time"
1112 "unicode"
1213)
1314
14
1515type allanimeResponse struct {
1616 Data struct {
1717 Episode struct {
@@ -94,7 +94,7 @@ func extractLinks(provider_id string) map[string]interface{} {
9494 return videoData
9595}
9696
97// Get anime episode url respective to given config
97// Get anime episode url respective to given config
9898// If the link is found, it returns a list of links. Otherwise, it returns an error.
9999//
100100// Parameters:
@@ -145,35 +145,141 @@ func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
145145 return nil, err
146146 }
147147
148 responseStr := string(body)
149
150 // Unmarshal the JSON data into the struct
151148 var response allanimeResponse
152 err = json.Unmarshal([]byte(responseStr), &response)
149 err = json.Unmarshal(body, &response)
153150 if err != nil {
154151 Log(fmt.Sprint("Error parsing JSON: ", err), logFile)
152 return nil, err
155153 }
156154
157 var allinks []string // This will be returned
155 type result struct {
156 index int
157 links []string
158 err error
159 }
158160
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)
160163 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)
162 decodedProviderID := decodeProviderID(url.SourceUrl[2:]) // Decode the source url to get the provider id
163 extractedLinks := extractLinks(decodedProviderID) // Extract the links using provider id
164 if linksInterface, ok := extractedLinks["links"].([]interface{}); ok {
165 for _, linkInterface := range linksInterface {
166 if linkMap, ok := linkInterface.(map[string]interface{}); ok {
167 if link, ok := linkMap["link"].(string); ok {
168 allinks = append(allinks, link) // Add all extracted links into allinks
169 }
170 }
164 if len(url.SourceUrl) > 2 && unicode.IsDigit(rune(url.SourceUrl[2])) {
165 validURLs = append(validURLs, url.SourceUrl)
166 }
167 }
168
169 if len(validURLs) == 0 {
170 return nil, fmt.Errorf("no valid source URLs found in response")
171 }
172
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
171214 }
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))
172244 } 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
174254 }
255 return nil, fmt.Errorf("timeout waiting for results after %d successful responses", successCount)
175256 }
176257 }
177258
178 return allinks, nil
179}
\ No newline at end of file
259 // If we have any errors but also some successes, log errors but continue
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
234234 CurdOut(fmt.Sprintf("Error writing record: %v", err))
235235 }
236236 }
237
237
238238 return nil
239239}
240240
@@ -259,7 +259,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
259259 userInput, err := GetUserInputFromRofi("Enter the anime name")
260260 if err != nil {
261261 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()))
263263 }
264264 query = userInput
265265 } else {
@@ -298,7 +298,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
298298 userInput, err := GetUserInputFromRofi("Enter the episode number")
299299 if err != nil {
300300 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()))
302302 }
303303 episodeNumber, err = strconv.Atoi(userInput)
304304 if err != nil {
@@ -311,7 +311,7 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
311311 }
312312
313313 anime.Ep.Number = episodeNumber
314
314
315315 for {
316316 // Get episode link
317317 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
@@ -335,8 +335,8 @@ func WatchUntracked(userCurdConfig *CurdConfig, logFile string) {
335335
336336 anime.Ep.Player.SocketPath = mpvSocketPath
337337 anime.Ep.Started = false
338
339 Log(fmt.Sprintf("Started mpvsocketpath ", anime.Ep.Player.SocketPath), logFile)
338
339 Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath), logFile)
340340
341341 // Get video duration
342342 go func() {