aboutsummaryrefslogtreecommitdiff
path: root/dataimport/finder.go
blob: 5b704a486bd4c805cfcad3ca4bae18dfcb994d03 (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
package dataimport

import (
	"strings"

	"fagott.pw/grilist/models"
	"fagott.pw/grilist/util"
)

func FindGrilInDatabase(id int, dataSource models.DataSource) *int {
	var grilID *int
	_ = database.QueryRow("SELECT gril_id FROM grilist.grils_id_mappings WHERE source = $1 AND source_id = $2;", dataSource, id).Scan(&grilID)
	return grilID
}

func compareAnimeNames(a, b string) bool {
	normalize := func(str string) string {
		return util.NormalizeString(strings.TrimSpace(strings.Replace(strings.ToLower(str), " ", "", -1)))
	}
	return normalize(a) == normalize(b)
}

func FindSimilarGrils(iGril *ImporterGril, dataSource models.DataSource) ([]*models.Gril, error) {
	rows, err := database.Query("SELECT id, name, appearance_id, appearance_names, source_id FROM grilist.get_grils_for_merge($1, $2);", iGril.RomajiName, dataSource)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	grils := []*models.Gril{}
	var gril *models.Gril

	for rows.Next() {
		var id int
		var name string
		var aID *int
		var aNamesData *[]byte
		var sID *int
		if err := rows.Scan(&id, &name, &aID, &aNamesData, &sID); err != nil {
			return nil, err
		}
		if gril == nil || gril.ID != id {
			gril = &models.Gril{
				ID:         id,
				RomajiName: name,
			}
			grils = append(grils, gril)
		}
		if aID != nil && aNamesData != nil {
			series := models.Series{
				ID: *aID,
			}
			aNames := util.PGArray(*aNamesData)
			series.RomajiName = aNames[0]
			series.OtherNames = aNames
			if sID != nil {
				series.ForeignIDs[dataSource] = *sID
			}
			gril.Series = append(gril.Series, series)
		}
	}
	mGrils := []*models.Gril{}
	for _, gril := range grils {
		matches := false
		for _, series := range gril.Series {
			gril.Series = append(gril.Series, series)
			for _, anime := range iGril.Series {
				if id, ok := series.ForeignIDs[dataSource]; ok && id == anime.ID {
					matches = true
					continue
				}
				for _, name := range series.OtherNames {
					matches = matches || compareAnimeNames(name, anime.RomajiName)
					matches = matches || compareAnimeNames(name, anime.KanjiName)
					matches = matches || compareAnimeNames(name, anime.FuriganaName)
					for _, syn := range anime.OtherNames {
						matches = matches || compareAnimeNames(name, syn)
					}
				}
			}
		}
		if matches {
			mGrils = append(mGrils, gril)
		}
	}
	return mGrils, nil
}