aboutsummaryrefslogtreecommitdiff
path: root/modules/grils/grils.go
blob: 135398d64476e6247574bde33474e1280c57a5a8 (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
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
package grils

import (
	"fmt"
	"log"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"

	"fagott.pw/charakterin"
	"fagott.pw/grilist/cache"
	"fagott.pw/grilist/frontend"
	"fagott.pw/grilist/grilist"

	"github.com/julienschmidt/httprouter"
)

type CachedGril struct {
	Created time.Time
	Gril    *Gril
}

var (
	pgArrayReg = regexp.MustCompile(`(((?P<value>(([^",\\{}\s(NULL)])+|"([^"\\]|\\"|\\\\)*")))(,)?)`)
	pgValueIdx int
)

func findIdx() {
	for i, subexp := range pgArrayReg.SubexpNames() {
		if subexp == "value" {
			pgValueIdx = i
			break
		}
	}
}

type GrilsModule struct {
	g *grilist.Grilist
	c *cache.Cache
}

func (m *GrilsModule) Name() string {
	return "Grils"
}

func (m *GrilsModule) Init(g *grilist.Grilist) {
	findIdx()
	m.g = g
	m.g.Router.GET("/gril/:id", m.viewGril)
	m.g.Router.GET("/gril/:id/*rest", m.viewGril)

	m.c = cache.New()
}

func (m *GrilsModule) getGrils(whereClause string, params ...interface{}) ([]*Gril, error) {
	var grils []*Gril

	rows, err := m.g.DB.Query(fmt.Sprintf(`SELECT id, kanji_name, romaji_name, other_names, updated_at, age, birthday, tags FROM grilist.grils_flattened WHERE %s`, whereClause), params...)
	if err != nil {
		return nil, err
	}

	defer rows.Close()
	for rows.Next() {
		gril := &Gril{}
		var tags []byte
		var otherNames []byte
		err = rows.Scan(&gril.ID, &gril.KanjiName, &gril.RomajiName, &otherNames, &gril.UpdatedAt, &gril.Age, &gril.Birthday, &tags)
		if err != nil {
			log.Println(gril.ID)
			log.Println("error scanning in getGrils:", err)
			continue
		}

		gril.Tags = pgArray(tags)
		gril.OtherNames = pgArray(otherNames)

		grils = append(grils, gril)
	}

	return grils, nil
}

func (m *GrilsModule) GetListsOfGril(gril *Gril) error {
	rows, err := m.g.DB.Query(`SELECT list_id FROM grilist.lists_grils WHERE gril_id = $1`, gril.ID)
	if err != nil {
		return err
	}

	defer rows.Close()
	for rows.Next() {
		var listID int
		if err := rows.Scan(&listID); err != nil {
			log.Println(err)
			continue
		}

		gril.Lists = append(gril.Lists, listID)
	}

	return nil
}

func (m *GrilsModule) ProvideDashboardData(user *charakterin.User) []grilist.DashboardCategory {
	var categories []grilist.DashboardCategory
	t1 := time.Now()

	rows, err := m.g.DB.Query(
		`SELECT id, romaji_name, kanji_name FROM grilist.get_recently_updated_grils();`)
	if err != nil {
		log.Println(err)
		return categories
	}
	defer rows.Close()

	cat := grilist.DashboardCategory{
		Title: "Neue Grils",
	}

	for rows.Next() {
		var g Gril
		if err := rows.Scan(&g.ID, &g.RomajiName, &g.KanjiName); err != nil {
			log.Println(err)
			continue
		}

		cat.Cards = append(cat.Cards, frontend.Card{
			Title:       g.RomajiName,
			Description: g.KanjiName,
			Size:        "medium",
			Actions: []frontend.Action{
				frontend.Action{
					Name: "anguckieren",
					Link: "/gril/" + g.Slug(),
				},
			},
		})
	}
	categories = append(categories, cat)
	log.Printf("get_newest_grils_overall: %dms", time.Since(t1).Nanoseconds()/1000000)
	return categories
}

func (m *GrilsModule) FromID(id int) (*Gril, error) {
	if g, ok := m.c.Get(id); ok {
		return g.(*Gril), nil
	}

	gril := &Gril{
		ID: id,
	}
	t1 := time.Now()
	err := m.g.DB.QueryRow(`SELECT updated_at, age, birthday FROM grilist.grils WHERE id = $1`, id).Scan(&gril.UpdatedAt, &gril.Age, &gril.Birthday)
	log.Printf("get_gril_from_id_raw: %dms", time.Since(t1).Nanoseconds()/1000000)

	if err != nil {
		return nil, err
	}

	// Namen rausholen
	rows, err := m.g.DB.Query(`SELECT name, name_type FROM grilist.gril_names WHERE gril_id = $1`, id)
	if err != nil {
		return nil, err
	}
	log.Printf("get_gril_from_id_names: %dms", time.Since(t1).Nanoseconds()/1000000)
	defer rows.Close()

	for rows.Next() {
		var name string
		var name_type int
		if err := rows.Scan(&name, &name_type); err != nil {
			return nil, err
		}

		switch name_type {
		case 0:
			gril.KanjiName = name
			break
		case 1:
			gril.RomajiName = name
		default:
			gril.OtherNames = append(gril.OtherNames, name)
		}
	}
	/*rows, err := m.g.DB.Query(`SELECT name FROM grilist.gril_names WHERE gril_id = $1 AND name_type > 1`, id)
		if err != nil {
			return nil, err
		}
	    defer rows.Close()

	    for rows.Next() {
	        var name string
	        if err := rows.Scan(&name); err != nil {
	            return nil, err
	        }
	        gril.OtherNames = append(gril.OtherNames, name)
	    }
	    rows.Close()

	    // Tags holen
	    rows, err := m.g.DB.Query(`SELECT name FROM grilist.tags WHERE id IN (SELECT tag_id FROM grilist.grils_tags WHERE gril_id = $1)`, id)
		if err != nil {
			return nil, err
		}
	    defer rows.Close()

	    for rows.Next() {
	        var name string
	        if err := rows.Scan(&name); err != nil {
	            return nil, err
	        }
	        gril.Tags = append(gril.Tags, name)
	    }*/

	m.c.Insert(id, gril)
	log.Printf("get_gril_from_id: %dms", time.Since(t1).Nanoseconds()/1000000)
	return gril, nil
}

func (m *GrilsModule) FromIDs(ids []int) ([]*Gril, error) {
	if len(ids) == 0 {
		return make([]*Gril, 0), nil
	}

	idList := "("
	first := true
	for _, v := range ids {
		if first {
			first = false
		} else {
			idList += ","
		}
		idList += strconv.Itoa(v)
	}
	idList += ")"
	grils, err := m.getGrils("id IN " + idList)
	return grils, err
}

func (m *GrilsModule) viewGril(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, _ := m.g.Charakterin.GetUserFromRequest(r)
	sid := p.ByName("id")

	id, err := strconv.Atoi(sid)
	if err != nil {
		http.Redirect(w, r, "/", 302)
		return
	}

	gril, err := m.FromID(id)
	if err != nil {
		http.Redirect(w, r, "/", 302)
		return
	}

	if err := m.GetListsOfGril(gril); err != nil {
		log.Println(err)
	}

	data := m.g.Renderer.DefaultData()
	data["user"] = user
	data["gril"] = gril

	// ähnliche grils holen
	rows, err := m.g.DB.Query(`SELECT gril_id FROM (
	SELECT DISTINCT gril_id FROM gril_appearance WHERE appearance_id IN (SELECT appearance_id FROM gril_appearance WHERE gril_id = $1)
	) as t
    ORDER BY RANDOM()
    LIMIT 4;`, id)
	if err != nil {
		log.Println("could not get similar grils:", err)
		http.Error(w, "500", http.StatusInternalServerError)
		return
	}

	defer rows.Close()
	var similar []*Gril
	for rows.Next() {
		var id int
		if err := rows.Scan(&id); err != nil {
			log.Println("error scanning for similar gril:", err)
			continue
		}

		g, err := m.FromID(id)
		if err != nil {
			log.Println("invalid similar gril:", err)
			continue
		}
		similar = append(similar, g)
	}
	data["SimilarGrils"] = similar

	m.g.Renderer.RenderPage("gril", w, data)
}

func pgArray(array []byte) []string {
	var results []string
	matches := pgArrayReg.FindAllStringSubmatch(string(array), -1)
	for _, match := range matches {
		s := match[pgValueIdx]
		s = strings.Trim(s, "\"")
		results = append(results, s)
	}
	return results
}

func New() *GrilsModule {
	return &GrilsModule{}
}