aboutsummaryrefslogtreecommitdiffstats
path: root/web.go
blob: 25f7b8f93c17c5af81feb141b7ad54c158292049 (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
package main

import (
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	_ "github.com/lib/pq"
)

type User struct {
	Id          int
	Type        string
	OpId        string `json:"sub"`
	Name        string `json:"given_name"`
	Email       string `json:"email"`
	LfmName     string
	LfmPassword string
}

type UserSession struct {
	Id       string
	UserId   int
	UserName string
}

func (app *App) login(w http.ResponseWriter, r *http.Request) {
	state := hex.EncodeToString(genKey(32))
	if err := app.SetCookie(w, "state", state, 120); err != nil {
		log.Panic(err)
	}
	url := app.Config.OAuth.AuthCodeURL(state)
	app.Template.ExecuteTemplate(w, "login.tmpl", url)
}

func (app *App) root(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	se := new(UserSession)
	err := app.GetCookie(r, "session", se)
	if err != nil {
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	scrobbles := app.RecentScrobbles(se.UserId)
	np := app.NowPlaying(se.UserId)
	np.Image = "static/np2.gif"
	if time.Since(np.Time) > time.Duration(np.Duration)*time.Second {
		np = nil
	}

	app.Template.ExecuteTemplate(w, "index.tmpl", struct {
		Session    *UserSession
		Scrobbles  []*Scrobble
		NowPlaying *Scrobble
	}{se, scrobbles, np})
}

func (app *App) callback(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if rec := recover(); rec != nil {
			http.Redirect(w, r, "/login", http.StatusFound)
			log.Println(rec)
		}
	}()

	var state string
	app.GetCookie(r, "state", &state)
	if state == "" || state != r.FormValue("state") {
		panic(fmt.Errorf("state"))
	}
	code := r.FormValue("code")
	tok, _ := app.Config.OAuth.Exchange(r.Context(), code)
	client := app.Config.OAuth.Client(r.Context(), tok)
	resp, _ := client.Get("https://www.googleapis.com/plus/v1/people/me/openIdConnect")
	p, _ := ioutil.ReadAll(resp.Body)
	user := &User{Type: "google"}
	json.Unmarshal(p, user)

	s := &UserSession{Id: hex.EncodeToString(genKey(32))}
	var newUser bool
	if err := app.GetUser(user); err != nil {
		newUser = true
		if err := app.InsertUser(user); err != nil {
			panic(err)
		}
	}
	s.UserId = user.Id
	s.UserName = user.Name
	app.InsertUserSession(s)
	app.SetCookie(w, "session", s, 86400*30)
	if newUser {
		http.Redirect(w, r, "/settings", http.StatusTemporaryRedirect)
	} else {
		http.Redirect(w, r, "/", http.StatusFound)
	}
}

func (app *App) settings(w http.ResponseWriter, r *http.Request) {
	se := new(UserSession)
	err := app.GetCookie(r, "session", se)
	if err != nil {
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	if r.Method == "POST" && r.FormValue("save") != "" {
		u := &User{
			Id:      se.UserId,
			Name:    r.FormValue("name"),
			Email:   r.FormValue("email"),
			LfmName: r.FormValue("lfm_name"),
		}
		if password := r.FormValue("lfm_password"); password != "" {
			u.LfmPassword = md5hex(password)
		}
		if err := app.SaveUser(u); err != nil {
			log.Println(err)
		}
		se.UserName = u.Name
		app.SetCookie(w, "session", se, 86400*30)
	}

	if r.Method == "POST" && r.FormValue("import") != "" {
		u := &User{
			Id: se.UserId,
		}
		app.GetUser(u)
		go app.ImportRecentTracks(u)
	}

	if r.Method == "POST" && r.FormValue("love_import") != "" {
		u := &User{
			Id: se.UserId,
		}
		app.GetUser(u)
		go app.ImportLovedTracks(u)
	}

	user := &User{Id: se.UserId}
	if err := app.GetUser(user); err != nil {
		log.Println(err)
	}
	i, err := app.ImportStats(user.LfmName)
	li, err := app.LoveImportStats(user.LfmName)
	err = app.Template.ExecuteTemplate(w, "settings.tmpl", struct {
		Session *UserSession
		*User
		LoveImport *LoveImport
		Import     *Import
	}{Session: se, User: user, LoveImport: li, Import: i})
	if err != nil {
		log.Println(err)
	}
}