aboutsummaryrefslogtreecommitdiff
path: root/tasks/anifetch.task.go
blob: 8d38da8d362f46615870bf6f620a1119f465da64 (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
package tasks

import (
	"encoding/json"
	"fmt"
	"io"
	"metachan/entities"
	"metachan/enums"
	"metachan/repositories"
	"metachan/types"
	"metachan/utils/logger"
	"metachan/utils/mappers"
	"net/http"
)

const (
	fribbURL  = "https://raw.githubusercontent.com/Fribb/anime-lists/master/anime-list-full.json"
	batchSize = 1000
)

func AniFetch() error {
	logger.Infof("AniFetch", "Starting Anime Fetch")

	response, err := http.Get(fribbURL)
	if err != nil {
		logger.Errorf("AniFetch", "Anime Fetch failed: %v", err)
		return err
	}

	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		logger.Errorf("AniFetch", "Failed to read response body: %v", err)
		return err
	}

	var mappings []types.MappingResponse
	if err := json.Unmarshal(body, &mappings); err != nil {
		logger.Errorf("AniFetch", "Failed to unmarshal JSON: %v", err)
		return err
	}

	total := len(mappings)

	for i := 0; i < total; i += batchSize {
		end := i + batchSize
		if end > total {
			end = total
		}

		batch := mappings[i:end]
		processBatch(batch)
		logger.Infof("AniFetch", "Processed %d/%d mappings", end, total)
	}

	logger.Successf("AniFetch", "Anime Fetch completed")

	return nil
}

func processBatch(mappings []types.MappingResponse) {
	for _, mapping := range mappings {
		var composite *string
		if mapping.MAL != 0 && mapping.Anilist != 0 {
			comp := fmt.Sprintf("%d-%d", mapping.MAL, mapping.Anilist)
			composite = &comp
		}

		entity := entities.Mapping{
			AniDB:               mapping.AniDB,
			Anilist:             mapping.Anilist,
			AnimeCountdown:      mapping.AnimeCountdown,
			AnimePlanet:         mappers.ForceString(mapping.AnimePlanet),
			AniSearch:           mapping.AniSearch,
			IMDB:                mapping.IMDB,
			Kitsu:               mapping.Kitsu,
			LiveChart:           mapping.LiveChart,
			MAL:                 mapping.MAL,
			NotifyMoe:           mapping.NotifyMoe,
			Simkl:               mapping.Simkl,
			TMDB:                mappers.ForceInt(mapping.TMDB),
			TVDB:                mapping.TVDB,
			Type:                enums.MappingAnimeType(mapping.Type),
			MALAnilistComposite: composite,
		}

		if err := repositories.CreateOrUpdateMapping(&entity); err != nil {
			logger.Warnf("AniFetch", "Unable to process mapping %v: %v", mapping, err)
		}
	}
}