aboutsummaryrefslogtreecommitdiff
path: root/modules/lists/lists.go
blob: d1913be8efd1d3d83d54ae92c93eaf397808a004 (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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
package lists

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"sort"
	"strconv"

	"fagott.pw/charakterin"
	"fagott.pw/grilist/cache"
	"fagott.pw/grilist/frontend"
	"fagott.pw/grilist/grilist"
	"fagott.pw/grilist/modules/grils"
	"github.com/julienschmidt/httprouter"
	"github.com/lib/pq"
)

// Module und so.
type Module struct {
	g     *grilist.Grilist
	c     *cache.Cache
	grils *grils.GrilsModule
}

// List ist eine Liste an DINGEN.
type List struct {
	ID          int
	Name        string
	Description string
	Owner       *charakterin.User
	ForkOf      sql.NullInt64
	UpdatedAt   pq.NullTime
	Grils       []*ListGril
}

// ListGril ist ein geranktes Gril
type ListGril struct {
	Gril  *grils.Gril
	Order int
}

// ListGrils ist die Sort-Interface Implementation für Grils einer Liste.
type ListGrils []*ListGril

func (l ListGrils) Len() int           { return len(l) }
func (l ListGrils) Swap(i, j int)      { l[i], l[j] = l[j], l[i] }
func (l ListGrils) Less(i, j int) bool { return l[i].Order < l[j].Order }

// Name gibt den Namen des Moduls zurück
func (m *Module) Name() string {
	return "Lists"
}

// Init initialisiert das Modul
func (m *Module) Init(g *grilist.Grilist) {
	m.g = g

	gm, ok := g.Modules["Grils"]
	if !ok {
		log.Fatal("lists: grils module not found")
	}

	grilsModule, ok := gm.(*grils.GrilsModule)
	if !ok {
		log.Fatal("lists: error with grils module")
	}
	m.grils = grilsModule
	m.g.Router.GET("/list/:id", m.viewList)
	m.g.Router.POST("/list/:id/order", m.updateGrilOrder)
	m.g.Router.POST("/list/:id", m.addGrilToList)
	m.g.Router.DELETE("/list/:id/order", m.removeGrilFromList)
	m.g.Router.GET("/list/:id/settings", m.viewListSettings)
	m.g.Router.POST("/list/:id/settings", m.updateListSettings)
	m.g.Router.GET("/new/list", m.displayCreateList)
	m.g.Router.POST("/new/list", m.createList)
	m.g.Router.GET("/list/:id/delete", m.deleteList)

	m.g.Router.GET("/api/lists/user", m.APIgetUserLists)

	m.c = cache.New()
}

func (m *Module) getListGrils(list *List) error {
	rows, err := m.g.DB.Query(`SELECT gril_id, "order" FROM grilist.lists_grils WHERE list_id = $1 ORDER BY "order" ASC`, list.ID)
	if err != nil {
		return err
	}

	defer rows.Close()
	list.Grils = list.Grils[:0]
	for rows.Next() {
		var grilID int
		lg := &ListGril{}

		if err := rows.Scan(&grilID, &lg.Order); err != nil {
			log.Println("error scanning row in getListGrils:", err)
			continue
		}

		gril, err := m.grils.FromID(grilID)
		if err != nil {
			log.Println("error getting listGril:", err)
			continue
		}
		lg.Gril = gril

		list.Grils = append(list.Grils, lg)
	}
	sort.Sort(ListGrils(list.Grils))
	return nil
}

func (m *Module) getLists(whereClause string, params ...interface{}) ([]*List, error) {
	var lists []*List

	rows, err := m.g.DB.Query(fmt.Sprintf(`SELECT id, name, description, fork_of, updated_at, user_id FROM grilist.lists WHERE %s`, whereClause), params...)
	if err != nil {
		return nil, err
	}

	defer rows.Close()
	for rows.Next() {
		list := &List{}
		var ownerID int
		if err := rows.Scan(&list.ID, &list.Name, &list.Description, &list.ForkOf, &list.UpdatedAt, &ownerID); err != nil {
			log.Println("error scanning row in getLists:", err)
			continue
		}

		// Owner kriegn
		owner, err := m.g.Charakterin.GetUserByID(ownerID)
		if err != nil {
			log.Println("error retreiving owner of list", err)
			continue
		}
		list.Owner = owner

		m.c.Insert(list.ID, list)
		lists = append(lists, list)
	}

	return lists, nil
}

// GetUserLists gibt die Listen eines Benutzers zurück.
func (m *Module) GetUserLists(u *charakterin.User, withGrils bool) []*List {
	lists, err := m.getLists(`user_id = $1`, u.ID)
	if err != nil {
		log.Println(err)
	}

	if withGrils {
		for _, list := range lists {
			if err := m.getListGrils(list); err != nil {
				log.Println(err)
			}
		}
	}
	return lists
}

// FromID sucht nach der Liste mit der gegebenen ID und gibt sie, falls sie existiert, zurück.
func (m *Module) FromID(id int, withGrils bool) (*List, error) {
	if lst, ok := m.c.Get(id); ok {
		l := lst.(*List)
		// einen neuen User holen, wir wollen ja sicher gehen und so.
		if owner, err := m.g.Charakterin.GetUserByID(l.Owner.ID); err == nil {
			l.Owner = owner
		}

		// Potenzieller Optimierungsbedarf: neue query, wenn die Liste leer ist. updateGrilOrder nutzt derzeit aber genau dieses verhalten.
		if withGrils && len(l.Grils) == 0 {
			if err := m.getListGrils(l); err != nil {
				return nil, err
			}
		}
		return l, nil
	}

	lists, err := m.getLists(`id = $1`, id)
	if err != nil {
		return nil, err
	}

	if withGrils {
		for _, list := range lists {
			if err := m.getListGrils(list); err != nil {
				return nil, err
			}
		}
	}

	if len(lists) == 0 {
		return nil, errors.New("no list found")
	}
	return lists[0], nil
}

func ListsToCards(lists []*List) []frontend.Card {
	var cards []frontend.Card

	for _, list := range lists {
		cards = append(cards, frontend.Card{
			Title:       list.Name,
			Description: list.Description,
			Size:        "medium",
			Actions: []frontend.Action{
				frontend.Action{
					Name: "anguckieren",
					Link: fmt.Sprintf("/list/%d", list.ID),
				},
				frontend.Action{
					Name:     fmt.Sprintf(`<span class="chip">von <a class="purple-text text-lighten-2" style="margin-right: 0px" href="/user/%d/%s">%s</a></span>`, list.Owner.ID, list.Owner.GetName(), list.Owner.GetName()),
					Link:     "#",
					Disabled: true,
				},
			},
		})
	}
	return cards
}

// ProvideDashboardData gibt Daten für das Dashboard bezogen auf den Benutzer zurück
func (m *Module) ProvideDashboardData(user *charakterin.User) []grilist.DashboardCategory {
	var categories []grilist.DashboardCategory

	// Neue Listen
	lists, err := m.getLists(`1=1 ORDER BY id DESC LIMIT 5`)
	if err != nil {
		log.Println(err)
		return categories
	}

	categories = append(categories, grilist.DashboardCategory{
		Title: "Neueste Listen",
		Cards: ListsToCards(lists),
	})

	if user == nil {
		return categories
	}

	// Listen des Benutzers
	lists = m.GetUserLists(user, false)

	categories = append(categories, grilist.DashboardCategory{
		Title: "Meine Listen",
		Cards: ListsToCards(lists),
	})

	return categories
}

func (m *Module) viewList(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 {
		log.Println("redir")
		http.Redirect(w, r, "/", 302)
		return
	}

	list, err := m.FromID(id, true)
	if err != nil {
		log.Println("redir")
		http.Redirect(w, r, "/", 302)
		return
	}

	data := m.g.Renderer.DefaultData()
	data["user"] = user
	data["list"] = list
	if user != nil && user.ID == list.Owner.ID {
		data["isOwner"] = true
	} else {
		data["isOwner"] = false
	}

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

func (m *Module) deleteList(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		log.Println("invalid deleteList user")
		http.Redirect(w, r, fmt.Sprintf("/list/%s", p.ByName("id")), 403)
		return
	}

	id, err := strconv.Atoi(p.ByName("id"))
	if err != nil {
		log.Println("invalid deleteList ID")
		http.Redirect(w, r, "/", 400)
		return
	}

	list, err := m.FromID(id, false)
	if err != nil {
		log.Println("invalid deleteList ID (could not get list)")
		http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 500)
		return
	}

	// checken, ob der user auch list owner ist
	if user.ID != list.Owner.ID {
		log.Println("invalid deleteList request: user not list owner")
		http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 403)
		return
	}

	// aus der Datenbank loeschen
	_, err = m.g.DB.Query(`DELETE FROM grilist.lists WHERE id = $1`, id)
	if err != nil {
		log.Println("could not delete list:", err)
		data := m.g.Renderer.DefaultData()
		data["user"] = user
		data["list"] = list
		data["error"] = "Liste konnte nicht geloescht werden."

		m.g.Renderer.RenderPage("list_settings", w, data)
		return
	}
	// aus dem Cache loeschen
	m.c.Remove(list.ID)

	log.Printf("list %d has been deleted by the owner %d(%s)", list.ID, list.Owner.ID, list.Owner.GetName())
	http.Redirect(w, r, "/", 302)
}

func (m *Module) viewListSettings(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		log.Println("invalid viewListSettings user")
		http.Redirect(w, r, fmt.Sprintf("/list/%s", p.ByName("id")), 403)
		return
	}

	id, err := strconv.Atoi(p.ByName("id"))
	if err != nil {
		log.Println("invalid viewListSettings ID")
		http.Redirect(w, r, "/", 400)
		return
	}

	list, err := m.FromID(id, false)
	if err != nil {
		log.Println("invalid viewListSettings ID (could not get list)")
		http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 500)
		return
	}

	// checken, ob der user auch list owner ist
	if user.ID != list.Owner.ID {
		log.Println("invalid viewListSettings request: user not list owner")
		http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 403)
		return
	}

	data := m.g.Renderer.DefaultData()
	data["user"] = user
	data["list"] = list
	m.g.Renderer.RenderPage("list_settings", w, data)
}

func (m *Module) updateListSettings(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		log.Println("invalid updateListSettings user")
		http.Redirect(w, r, fmt.Sprintf("/list/%s", p.ByName("id")), 403)
		return
	}

	id, err := strconv.Atoi(p.ByName("id"))
	if err != nil {
		log.Println("invalid updateListSettings ID")
		http.Redirect(w, r, "/", 400)
		return
	}

	list, err := m.FromID(id, false)
	if err != nil {
		log.Println("invalid updateListSettings ID (could not get list)")
		http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 500)
		return
	}

	// checken, ob der user auch list owner ist
	if user.ID != list.Owner.ID {
		log.Println("invalid updateListSettings request: user not list owner")
		http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 403)
		return
	}

	renderWithError := func(message string, nameError, descriptionError bool) {
		data := m.g.Renderer.DefaultData()
		data["user"] = user
		data["list"] = list
		data["error"] = message
		data["error_name"] = nameError
		data["error_description"] = descriptionError

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

	values, err := readBody(r)
	if err != nil {
		log.Println("invalid POST data in updateListSettings")
		renderWithError("invalid post data", false, false)
		return
	}

	name := values.Get("name")
	if len(name) < 3 {
		renderWithError("Name zu kurz", true, false)
		return
	} else if len(name) > 32 {
		renderWithError("Name zu lang", true, false)
		return
	}

	description := values.Get("description")
	if len(description) < 3 {
		renderWithError("Beschreibung zu kurz", false, true)
		return
	} else if len(description) > 100 {
		renderWithError("Beschreibung zu lang", false, true)
		return
	}

	if list.Name != name && list.Description != description {
		_, err = m.g.DB.Query(`UPDATE grilist.lists SET name = $2, description = $3 WHERE id = $1`, id, name, description)
		if err != nil {
			log.Println("could not update list:", err)
			renderWithError("interner fehler", false, false)
			return
		}
	} else if list.Name != name || list.Description != description {
		field := "name"
		value := name
		if list.Description != description {
			field = "description"
			value = description
		}

		_, err = m.g.DB.Query(fmt.Sprintf(`UPDATE grilist.lists SET %s = $2 WHERE id = $1`, field), id, value)
		if err != nil {
			log.Println("could not update list:", err)
			renderWithError("interner fehler", false, false)
			return
		}
	}

	list.Name = name
	list.Description = description

	m.viewListSettings(w, r, p)
}

func (m *Module) addGrilToList(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	slistID := p.ByName("id")

	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		http.Error(w, "403", http.StatusForbidden)
		return
	}

	listID, err := strconv.Atoi(slistID)
	if err != nil {
		log.Println("invalid list id")
		return
	}

	values, err := readBody(r)
	if err != nil {
		log.Println("invalid POST data")
		return
	}

	grilID, err := strconv.Atoi(values.Get("id"))
	if err != nil {
		log.Println("invalid gril id")
		return
	}

	list, err := m.FromID(listID, true)
	if err != nil {
		http.Error(w, "invalid list", 404)
		return
	}

	if list.Owner.ID != user.ID {
		http.Error(w, "403", http.StatusForbidden)
		return
	}

	rank := 0
	if len(list.Grils) > 0 {
		rank = list.Grils[len(list.Grils)-1].Order + 1
	}

	// rein in die DB damit
	_, err = m.g.DB.Query(`INSERT INTO grilist.lists_grils(list_id, gril_id, "order") VALUES($1, $2, $3)`, listID, grilID, rank)
	if err != nil {
		log.Println("error inserting gril into list:", err)
		http.Error(w, "could not insert gril", 500)
		return
	}

	gril, err := m.grils.FromID(grilID)
	if err != nil {
		log.Println("inserted gril into list but couldnt get gril afterwards:", err)
		http.Error(w, "error after insert", 500)
		return
	}

	lg := &ListGril{gril, rank}
	data := m.g.Renderer.DefaultData()
	data["Index"] = len(list.Grils)
	value := make(map[string]interface{})
	value["IsListOwner"] = true
	value["Gril"] = lg
	data["Value"] = value
	list.Grils = append(list.Grils, lg)
	m.g.Renderer.RenderPage("list_gril", w, data)
	return
}

func (m *Module) displayCreateList(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		http.Redirect(w, r, "/", 302)
		return
	}

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

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

func (m *Module) createList(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		log.Println(err)
		http.Error(w, "500", http.StatusInternalServerError)
		return
	}

	values, err := readBody(r)
	if err != nil {
		log.Println(err)
		http.Error(w, "500", http.StatusInternalServerError)
		return
	}

	var id int
	err = m.g.DB.QueryRow(`INSERT INTO grilist.lists(user_id, name, description) VALUES($1, $2, $3) RETURNING id`, user.ID, values.Get("name"), values.Get("description")).Scan(&id)
	if err != nil {
		log.Println(err)
		http.Error(w, "500", http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, fmt.Sprintf("/list/%d", id), 302)
}

func (m *Module) updateGrilOrder(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	slistID := p.ByName("id")

	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		http.Error(w, "403", http.StatusForbidden)
		return
	}

	listID, err := strconv.Atoi(slistID)
	if err != nil {
		http.Error(w, "invalid list ID (type mismatch)", 400)
		return
	}

	values, err := readBody(r)
	if err != nil {
		http.Error(w, "invalid POST data", 400)
		return
	}

	grilID, err := strconv.Atoi(values.Get("gril"))
	if err != nil {
		http.Error(w, "invalid gril ID", 404)
		return
	}

	pos, err := strconv.Atoi(values.Get("pos"))
	if err != nil {
		http.Error(w, "invalid position", 400)
		return
	}

	// rein in die DB damit
	_, err = m.g.DB.Exec(`SELECT grilist.set_gril_order($1, $2, $3, $4)`, user.ID, listID, grilID, pos)
	if err != nil {
		log.Println("error reordering gril:", err)
		http.Error(w, "could not update gril order", 500)
		return
	}

	// wenn die liste im cache ist, die Grils clearen, damit beim naechsten aufruf die Gril-Liste neu geholt wird.
	if l, ok := m.c.Get(listID); ok {
		ls := l.(*List)
		ls.Grils = ls.Grils[:0]
	}

	w.WriteHeader(200)
	w.Write([]byte("ok"))
	return
}

func (m *Module) removeGrilFromList(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	slistID := p.ByName("id")

	listID, err := strconv.Atoi(slistID)
	if err != nil {
		http.Error(w, "invalid list ID (type mismatch)", 400)
		return
	}

	values, err := readBody(r)
	if err != nil {
		http.Error(w, "invalid POST data", 400)
		return
	}

	grilID, err := strconv.Atoi(values.Get("gril"))
	if err != nil {
		http.Error(w, "invalid gril ID", 404)
		return
	}

	res, err := m.g.DB.Exec(`DELETE FROM grilist.lists_grils WHERE list_id=$1 AND gril_id=$2`, listID, grilID)
	if err != nil {
		log.Println("error removing gril:", err)
		http.Error(w, "could not remove gril", 500)
		return
	}

	if r, err := res.RowsAffected(); err != nil || r == 0 {
		log.Println("invalid rows affected in removing gril")
		http.Error(w, "gril not in list / other error", 500)
		return
	}

	if l, ok := m.c.Get(listID); ok {
		ls := l.(*List)
		ls.Grils = ls.Grils[:0]
	}

	w.WriteHeader(200)
	w.Write([]byte("ok"))
	return
}

func (m *Module) APIgetUserLists(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	user, err := m.g.Charakterin.GetUserFromRequest(r)
	if err != nil {
		http.Error(w, "403", http.StatusForbidden)
		return
	}

	lists := m.GetUserLists(user, false)
	var pubLists []List

	for _, list := range lists {
		// owner wegen SICHERHEIT rausfiltern (nodumppassword2k16)
		// list.Owner = nil
		var tempList List
		tempList.Description = list.Description
		tempList.ForkOf = list.ForkOf
		tempList.ID = list.ID
		tempList.Name = list.Name
		tempList.UpdatedAt = list.UpdatedAt
		pubLists = append(pubLists, tempList)
	}

	data, err := json.Marshal(&pubLists)
	if err != nil {
		log.Println(err)
		http.Error(w, "500", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(200)
	w.Write(data)
}

// New erstellt eine neue Instanz des Modules
func New() *Module {
	return &Module{}
}

func readBody(r *http.Request) (url.Values, error) {
	defer r.Body.Close()
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}

	values, err := url.ParseQuery(string(data))
	if err != nil {
		return nil, err
	}

	return values, nil
}