-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanime.go
More file actions
698 lines (610 loc) · 17 KB
/
anime.go
File metadata and controls
698 lines (610 loc) · 17 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
package main
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"sort"
"strings"
"time"
"github.com/nstratos/go-myanimelist/mal"
"github.com/rl404/verniy"
)
var errStatusUnknown = errors.New("status unknown")
type Status string
const (
StatusWatching Status = "watching"
StatusCompleted Status = "completed"
StatusOnHold Status = "on_hold"
StatusDropped Status = "dropped"
StatusPlanToWatch Status = "plan_to_watch"
StatusUnknown Status = "unknown"
)
func (s Status) GetMalStatus() (mal.AnimeStatus, error) {
switch s {
case StatusWatching:
return mal.AnimeStatusWatching, nil
case StatusCompleted:
return mal.AnimeStatusCompleted, nil
case StatusOnHold:
return mal.AnimeStatusOnHold, nil
case StatusDropped:
return mal.AnimeStatusDropped, nil
case StatusPlanToWatch:
return mal.AnimeStatusPlanToWatch, nil
case StatusUnknown:
return "", errStatusUnknown
default:
return "", errStatusUnknown
}
}
func (s Status) GetAnilistStatus() string {
switch s {
case StatusWatching:
return "CURRENT"
case StatusCompleted:
return "COMPLETED"
case StatusOnHold:
return "PAUSED"
case StatusDropped:
return "DROPPED"
case StatusPlanToWatch:
return "PLANNING"
case StatusUnknown:
return ""
default:
return ""
}
}
type Anime struct {
NumEpisodes int
IDAnilist int
IDMal int
Progress int
Score int
SeasonYear int
Status Status
TitleEN string
TitleJP string
TitleRomaji string
StartedAt *time.Time
FinishedAt *time.Time
IsFavourite bool
isReverse bool // true when used in reverse sync (MAL → AniList)
}
func (a Anime) GetTargetID() TargetID {
if a.isReverse {
return TargetID(a.IDAnilist)
}
return TargetID(a.IDMal)
}
// GetAniListID returns the AniList ID.
func (a Anime) GetAniListID() TargetID {
return TargetID(a.IDAnilist)
}
// GetMALID returns the MAL ID.
func (a Anime) GetMALID() TargetID {
return TargetID(a.IDMal)
}
func (a Anime) GetSourceID() int {
if a.isReverse {
return a.IDMal
}
return a.IDAnilist
}
func (a Anime) GetStatusString() string {
return string(a.Status)
}
func (a Anime) GetStringDiffWithTarget(t Target) string {
b, ok := t.(Anime)
if !ok {
return "Diff{undefined}"
}
return buildDiffString(
"Status", a.Status, b.Status,
"Score", a.Score, b.Score,
"Progress", a.Progress, b.Progress,
"NumEpisodes", a.NumEpisodes, b.NumEpisodes,
"StartedAt", a.StartedAt, b.StartedAt,
"FinishedAt", a.FinishedAt, b.FinishedAt,
"TitleEN", a.TitleEN, b.TitleEN,
"TitleJP", a.TitleJP, b.TitleJP,
"TitleRomaji", a.TitleRomaji, b.TitleRomaji,
)
}
func (a Anime) SameProgressWithTarget(t Target) bool {
b, ok := t.(Anime)
if !ok {
return false
}
if a.Status != b.Status {
return false
}
if a.Score != b.Score {
return false
}
if !sameDates(a.StartedAt, b.StartedAt) {
return false
}
// Compare FinishedAt only when status is COMPLETED.
// Non-completed entries may have stale FinishedAt on AniList
// that MAL ignores — comparing them would cause infinite
// update loops since MAL never accepts the date.
if a.Status == StatusCompleted && !sameDates(a.FinishedAt, b.FinishedAt) {
return false
}
progress := a.Progress == b.Progress
if a.NumEpisodes == b.NumEpisodes {
return progress
}
if a.NumEpisodes == 0 || b.NumEpisodes == 0 {
return progress
}
if progress && (a.NumEpisodes-b.NumEpisodes != 0) {
return true
}
aa := (a.NumEpisodes - a.Progress)
bb := (b.NumEpisodes - b.Progress)
return aa == bb
}
func (a Anime) SameTypeWithTarget(ctx context.Context, t Target) bool {
// Type assertion to ensure we're comparing with another Anime
b, ok := t.(Anime)
if !ok {
return false
}
// Check if MAL IDs match (critical for reverse sync)
if a.IDMal > 0 && b.IDMal > 0 && a.IDMal == b.IDMal {
return true
}
// Check if AniList IDs match
if a.IDAnilist > 0 && b.IDAnilist > 0 && a.IDAnilist == b.IDAnilist {
return true
}
// Use the comprehensive title matching logic
return a.SameTitleWithTarget(ctx, t)
}
func (a Anime) SameTitleWithTarget(ctx context.Context, t Target) bool {
b, ok := t.(Anime)
if !ok {
return false
}
// Check if titles match
if !titleMatchingLevels(ctx,
a.TitleEN, a.TitleJP, a.TitleRomaji,
b.TitleEN, b.TitleJP, b.TitleRomaji,
) {
return false
}
// Additional validation: check episode count if both are known
// This prevents matching movies (1 ep) with TV series (13+ eps)
if a.NumEpisodes > 0 && b.NumEpisodes > 0 {
minEps := a.NumEpisodes
maxEps := b.NumEpisodes
if minEps > maxEps {
minEps, maxEps = maxEps, minEps
}
// Calculate percentage difference
percentDiff := float64(maxEps-minEps) / float64(maxEps) * 100
// Reject if difference is more than 20%
if percentDiff > 20.0 {
return false
}
}
return true
}
// IsPotentiallyIncorrectMatch checks if a match might be incorrect
// Returns true if the match should be rejected.
func (a Anime) IsPotentiallyIncorrectMatch(t Target) bool {
b, ok := t.(Anime)
if !ok {
return false
}
// If source has a valid MAL ID that matches, trust it
srcID := a.IDMal
tgtID := b.IDMal
if srcID > 0 && srcID == tgtID {
return false // Valid MAL ID match
}
// If source has no MAL ID but target does, and titles don't match exactly
// This prevents matching random specials/ovies with different titles
if srcID == 0 && tgtID > 0 && !a.IdenticalTitleMatch(b) {
return true // Likely incorrect match - different titles
}
// Check episode count mismatch
// If source has 0/unknown episodes but target has many (> 4)
if (a.NumEpisodes == 0 || a.NumEpisodes == 1) && b.NumEpisodes > 4 {
// Check if titles are actually different (not just one being a substring)
if !a.IdenticalTitleMatch(b) {
return true // Likely incorrect match
}
}
return false
}
// IdenticalTitleMatch checks if titles are truly identical (not just similar).
func (a Anime) IdenticalTitleMatch(b Anime) bool {
// Exact match on any title field
if a.TitleEN != "" && a.TitleEN == b.TitleEN {
return true
}
if a.TitleJP != "" && a.TitleJP == b.TitleJP {
return true
}
if a.TitleRomaji != "" && a.TitleRomaji == b.TitleRomaji {
return true
}
return false
}
func (a Anime) GetUpdateOptions() []mal.UpdateMyAnimeListStatusOption {
st, err := a.Status.GetMalStatus()
if err != nil {
log.Printf("Error getting MAL status: %v", err)
return nil
}
opts := []mal.UpdateMyAnimeListStatusOption{
st,
mal.Score(a.Score),
mal.NumEpisodesWatched(a.Progress),
}
if a.StartedAt != nil {
opts = append(opts, mal.StartDate(*a.StartedAt))
}
if a.Status == StatusCompleted && a.FinishedAt != nil {
opts = append(opts, mal.FinishDate(*a.FinishedAt))
}
return opts
}
func (a Anime) GetTitle() string {
if a.TitleEN != "" {
return a.TitleEN
}
if a.TitleJP != "" {
return a.TitleJP
}
return a.TitleRomaji
}
func (a Anime) String() string {
var sb strings.Builder
sb.WriteString("Anime{")
fmt.Fprintf(&sb, "IDAnilist: %d, ", a.IDAnilist)
fmt.Fprintf(&sb, "IDMal: %d, ", a.IDMal)
fmt.Fprintf(&sb, "TitleEN: %s, ", a.TitleEN)
fmt.Fprintf(&sb, "TitleJP: %s, ", a.TitleJP)
fmt.Fprintf(&sb, "MediaListStatus: %s, ", a.Status)
fmt.Fprintf(&sb, "Score: %d, ", a.Score)
fmt.Fprintf(&sb, "Progress: %d, ", a.Progress)
fmt.Fprintf(&sb, "EpisodeNumber: %d, ", a.NumEpisodes)
fmt.Fprintf(&sb, "SeasonYear: %d, ", a.SeasonYear)
fmt.Fprintf(&sb, "StartedAt: %s, ", a.StartedAt)
fmt.Fprintf(&sb, "FinishedAt: %s", a.FinishedAt)
sb.WriteString("}")
return sb.String()
}
// newAnimesFromMediaListGroups converts AniList media list groups to domain Anime list.
// reverse=false: entries are forward-sync sources; reverse=true: reverse-sync targets.
func newAnimesFromMediaListGroups(
ctx context.Context, groups []verniy.MediaListGroup, scoreFormat verniy.ScoreFormat, reverse bool,
) []Anime {
res := make([]Anime, 0, len(groups))
for _, group := range groups {
for _, mediaList := range group.Entries {
a, err := newAnimeFromMediaListEntry(ctx, mediaList, scoreFormat, reverse)
if err != nil {
log.Printf("Error creating anime from media list entry: %v", err)
continue
}
res = append(res, a)
}
}
return res
}
func newAnimeFromMediaListEntry(
ctx context.Context, mediaList verniy.MediaList, scoreFormat verniy.ScoreFormat, reverse bool,
) (Anime, error) {
if mediaList.Media == nil {
return Anime{}, errors.New("media is nil")
}
if mediaList.Status == nil {
return Anime{}, errors.New("status is nil")
}
if mediaList.Media.Title == nil {
return Anime{}, errors.New("title is nil")
}
var score int
if mediaList.Score != nil {
// Normalize AniList score to MAL format (0-10)
score = normalizeScoreForMAL(ctx, *mediaList.Score, scoreFormat)
}
var progress int
if mediaList.Progress != nil {
progress = *mediaList.Progress
}
var titleEN string
if mediaList.Media.Title.English != nil {
titleEN = *mediaList.Media.Title.English
}
var titleJP string
if mediaList.Media.Title.Native != nil {
titleJP = *mediaList.Media.Title.Native
}
var episodeNumber int
if mediaList.Media.Episodes != nil {
episodeNumber = *mediaList.Media.Episodes
}
var year int
if mediaList.Media.SeasonYear != nil {
year = *mediaList.Media.SeasonYear
}
var idMal int
if mediaList.Media.IDMAL != nil {
idMal = *mediaList.Media.IDMAL
}
var romajiTitle string
if mediaList.Media.Title.Romaji != nil {
romajiTitle = *mediaList.Media.Title.Romaji
}
startedAt := convertFuzzyDateToTimeOrNow(mediaList.StartedAt)
finishedAt := convertFuzzyDateToTimeOrNow(mediaList.CompletedAt)
var isFavourite bool
if mediaList.Media.IsFavourite != nil {
isFavourite = *mediaList.Media.IsFavourite
}
return Anime{
NumEpisodes: episodeNumber,
IDAnilist: mediaList.Media.ID,
IDMal: idMal,
Progress: progress,
Score: score,
SeasonYear: year,
Status: mapVerniyStatusToStatus(*mediaList.Status),
TitleEN: titleEN,
TitleJP: titleJP,
TitleRomaji: romajiTitle,
StartedAt: startedAt,
FinishedAt: finishedAt,
IsFavourite: isFavourite,
isReverse: reverse,
}, nil
}
// newAnimesFromMalAnimes converts MAL anime list to domain Anime list.
// reverse=false: entries are forward-sync targets (MAL IDs as target IDs).
// reverse=true: entries are reverse-sync sources (AniList IDs as target IDs).
func newAnimesFromMalAnimes(malAnimes []mal.Anime, reverse bool) []Anime {
res := make([]Anime, 0, len(malAnimes))
for _, malAnime := range malAnimes {
a, err := newAnimeFromMalAnime(malAnime, reverse)
if err != nil {
log.Printf("failed to convert mal anime to anime: %v", err)
continue
}
res = append(res, a)
}
return res
}
// newAnimesFromMalUserAnimes converts MAL user anime list to domain Anime list.
// reverse=false: entries are forward-sync targets (MAL IDs as target IDs).
// reverse=true: entries are reverse-sync sources (AniList IDs as target IDs).
func newAnimesFromMalUserAnimes(malAnimes []mal.UserAnime, reverse bool) []Anime {
res := make([]Anime, 0, len(malAnimes))
for _, malAnime := range malAnimes {
a, err := newAnimeFromMalAnime(malAnime.Anime, reverse)
if err != nil {
log.Printf("failed to convert mal anime to anime: %v", err)
continue
}
res = append(res, a)
}
sort.Slice(res, func(i, j int) bool {
return res[i].GetStatusString() < res[j].GetStatusString()
})
return res
}
func newAnimeFromMalAnime(malAnime mal.Anime, reverse bool) (Anime, error) {
if malAnime.ID == 0 {
return Anime{}, errors.New("ID is nil")
}
startedAt := parseDateOrNow(malAnime.MyListStatus.StartDate)
finishedAt := parseDateOrNow(malAnime.MyListStatus.FinishDate)
titleEN := malAnime.Title
if malAnime.AlternativeTitles.En != "" {
titleEN = malAnime.AlternativeTitles.En
}
titleJP := malAnime.Title
if malAnime.AlternativeTitles.Ja != "" {
titleJP = malAnime.AlternativeTitles.Ja
}
// In reverse sync, IDAnilist=0 triggers name-based search in the strategy chain.
// In forward sync, IDAnilist=-1 indicates "unknown" (MAL entries as targets don't need it).
anilistID := -1
if reverse {
anilistID = 0
}
return Anime{
NumEpisodes: malAnime.NumEpisodes,
IDAnilist: anilistID,
IDMal: malAnime.ID,
Progress: malAnime.MyListStatus.NumEpisodesWatched,
Score: malAnime.MyListStatus.Score, // MAL score is already 0-10 int
SeasonYear: malAnime.StartSeason.Year,
Status: mapMalAnimeStatusToStatus(malAnime.MyListStatus.Status),
TitleEN: titleEN,
TitleJP: titleJP,
StartedAt: startedAt,
FinishedAt: finishedAt,
IsFavourite: false, // MAL API v2 does not provide favorites
isReverse: reverse,
}, nil
}
func mapVerniyStatusToStatus(s verniy.MediaListStatus) Status {
switch s {
case verniy.MediaListStatusCurrent:
return StatusWatching
case verniy.MediaListStatusCompleted:
return StatusCompleted
case verniy.MediaListStatusPaused:
return StatusOnHold
case verniy.MediaListStatusDropped:
return StatusDropped
case verniy.MediaListStatusPlanning:
return StatusPlanToWatch
case verniy.MediaListStatusRepeating:
return StatusWatching // TODO: handle repeating correctly
default:
return StatusUnknown
}
}
func mapMalAnimeStatusToStatus(s mal.AnimeStatus) Status {
switch s {
case mal.AnimeStatusWatching:
return StatusWatching
case mal.AnimeStatusCompleted:
return StatusCompleted
case mal.AnimeStatusOnHold:
return StatusOnHold
case mal.AnimeStatusDropped:
return StatusDropped
case mal.AnimeStatusPlanToWatch:
return StatusPlanToWatch
default:
return StatusUnknown
}
}
func convertFuzzyDateToTimeOrNow(fd *verniy.FuzzyDate) *time.Time {
if fd == nil || fd.Year == nil || fd.Month == nil || fd.Day == nil {
return nil
}
d := time.Date(
*fd.Year,
time.Month(*fd.Month),
*fd.Day,
0, 0, 0, 0,
time.UTC,
)
return &d
}
func parseDateOrNow(dateStr string) *time.Time {
if dateStr == "" {
return nil
}
parsedTime, err := time.Parse(time.DateOnly, dateStr)
if err != nil {
return nil
}
parsedTime = parsedTime.UTC().Truncate(24 * time.Hour)
return &parsedTime
}
func newTargetsFromAnimes(animes []Anime) []Target {
res := make([]Target, 0, len(animes))
for _, anime := range animes {
res = append(res, anime)
}
return res
}
func newSourcesFromAnimes(animes []Anime) []Source {
res := make([]Source, 0, len(animes))
for _, anime := range animes {
res = append(res, anime)
}
return res
}
// newAnimesFromVerniyMedias converts AniList API search results to domain Anime list.
// reverse=true: entries will be used as reverse-sync targets (AniList IDs as target IDs).
func newAnimesFromVerniyMedias(medias []verniy.Media, reverse bool) []Anime {
res := make([]Anime, 0, len(medias))
for _, media := range medias {
a, err := newAnimeFromVerniyMedia(media, reverse)
if err != nil {
log.Printf("failed to convert verniy media to anime: %v", err)
continue
}
res = append(res, a)
}
return res
}
func newAnimeFromVerniyMedia(media verniy.Media, reverse bool) (Anime, error) {
if media.ID == 0 {
return Anime{}, errors.New("ID is 0")
}
var titleEN string
if media.Title != nil && media.Title.English != nil {
titleEN = *media.Title.English
}
var titleJP string
if media.Title != nil && media.Title.Native != nil {
titleJP = *media.Title.Native
}
var romajiTitle string
if media.Title != nil && media.Title.Romaji != nil {
romajiTitle = *media.Title.Romaji
}
var episodeNumber int
if media.Episodes != nil {
episodeNumber = *media.Episodes
}
var year int
if media.SeasonYear != nil {
year = *media.SeasonYear
}
var idMal int
if media.IDMAL != nil {
idMal = *media.IDMAL
}
return Anime{
NumEpisodes: episodeNumber,
IDAnilist: media.ID,
IDMal: idMal,
Progress: 0, // Will be set from MAL source
Score: 0, // Will be set from MAL source
SeasonYear: year,
Status: StatusUnknown, // Will be set from MAL source
TitleEN: titleEN,
TitleJP: titleJP,
TitleRomaji: romajiTitle,
StartedAt: nil, // Will be set from MAL source
FinishedAt: nil, // Will be set from MAL source
IsFavourite: false, // Verniy media from search doesn't contain user favorite status
isReverse: reverse,
}, nil
}
// sameDates compares two date pointers at day-level granularity.
// Used to detect if dates need syncing between source and target.
//
// Behavior:
//
// Source (a) | Target (b) | Result | Action
// -----------|------------|--------|-----------------------------
// nil | nil | true | no dates, nothing to do
// nil | set | true | don't clear existing target date
// set | nil | false | sync date to target
// same | same | true | already in sync
// differ | differ | false | update target date
func sameDates(a, b *time.Time) bool {
if a == nil {
return true
}
if b == nil {
return false
}
return a.Year() == b.Year() && a.Month() == b.Month() && a.Day() == b.Day()
}
func buildDiffString(pairs ...any) string {
if len(pairs)%3 != 0 {
return "Diff{invalid params}"
}
sb := strings.Builder{}
sb.WriteString("Diff{")
for i := 0; i < len(pairs); i += 3 {
field, ok := pairs[i].(string)
if !ok {
continue
}
a := pairs[i+1]
b := pairs[i+2]
if !reflect.DeepEqual(a, b) {
fmt.Fprintf(&sb, "%s: %v -> %v, ", field, a, b)
}
}
sb.WriteString("}")
return sb.String()
}