web.go 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package main
  2. import (
  3. "github.com/zmb3/spotify"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "strings"
  8. "time"
  9. )
  10. var (
  11. cachedTemplates = template.Must(template.ParseFiles("web/index.html"))
  12. )
  13. func (s *WebService) IndexHandler(w http.ResponseWriter, r *http.Request) {
  14. if r.URL.Path != "/" {
  15. http.Error(w, "Not Found", http.StatusNotFound)
  16. return
  17. }
  18. data := struct {
  19. Username string
  20. Spotify string
  21. Songs []*Song
  22. }{
  23. "",
  24. "",
  25. make([]*Song, 0),
  26. }
  27. session, err := getSession(r)
  28. if session != nil {
  29. songs, err := s.db.FindAllEntries(session.username)
  30. if err != nil {
  31. log.Println("Error while reading entries from database", err)
  32. http.Error(w, err.Error(), http.StatusInternalServerError)
  33. return
  34. }
  35. data.Songs = songs
  36. data.Username = session.username
  37. data.Spotify = session.spotify
  38. }
  39. var templates = cachedTemplates
  40. if s.noCache {
  41. templates = template.Must(template.ParseFiles("web/index.html"))
  42. }
  43. err = templates.ExecuteTemplate(w, "index.html", data)
  44. if err != nil {
  45. log.Println("Error while rendering template", err)
  46. http.Error(w, err.Error(), http.StatusInternalServerError)
  47. }
  48. }
  49. func getTrackID(url string) string {
  50. const externalURLPrefix = "https://open.spotify.com/track/"
  51. const trackURIPrefix = "spotify:track:"
  52. if strings.HasPrefix(url, externalURLPrefix) {
  53. return strings.Split(url, externalURLPrefix)[1]
  54. } else if strings.HasPrefix(url, trackURIPrefix) {
  55. return strings.Split(url, trackURIPrefix)[1]
  56. }
  57. return url
  58. }
  59. func (s *WebService) UpdateHandler(w http.ResponseWriter, r *http.Request) {
  60. if r.URL.Path != "/update" {
  61. http.Error(w, "Forbidden", http.StatusForbidden)
  62. return
  63. }
  64. session, err := getSession(r)
  65. if session == nil {
  66. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  67. return
  68. }
  69. err = r.ParseForm()
  70. if err != nil {
  71. http.Error(w, err.Error(), http.StatusBadRequest)
  72. return
  73. }
  74. round := r.Form.Get("round")
  75. artist := r.Form.Get("artist")
  76. title := r.Form.Get("title")
  77. url := r.Form.Get("url")
  78. if artist == "" && title == "" && url != "" {
  79. if s.spotify.client == nil {
  80. http.Error(w, "No Spotify token available", http.StatusInternalServerError)
  81. return
  82. }
  83. token, err := s.spotify.client.Token()
  84. if err != nil {
  85. http.Error(w, err.Error(), http.StatusInternalServerError)
  86. return
  87. } else if token.Expiry.Before(time.Now()) {
  88. http.Error(w, "Spotify token expired", http.StatusInternalServerError)
  89. return
  90. }
  91. log.Println("Resolving Spotify URL")
  92. trackID := getTrackID(url)
  93. track, err := s.spotify.client.GetTrack(spotify.ID(trackID))
  94. if err != nil {
  95. http.Error(w, err.Error(), http.StatusInternalServerError)
  96. return
  97. }
  98. log.Printf("Found Track with name %v and artists %v\n", track.Name, track.Artists)
  99. for index, trackArtist := range track.Artists {
  100. if index == 0 {
  101. artist = trackArtist.Name
  102. } else if index == 1 {
  103. artist = artist + " feat. " + trackArtist.Name
  104. } else {
  105. artist = artist + ", " + trackArtist.Name
  106. }
  107. }
  108. title = track.Name
  109. url = track.ExternalURLs["spotify"]
  110. }
  111. updated, err := s.db.UpdateEntry(session.username, round, artist, title, url)
  112. if err != nil {
  113. http.Error(w, err.Error(), http.StatusInternalServerError)
  114. return
  115. }
  116. if !updated {
  117. http.Error(w, "No round in DB", http.StatusNotFound)
  118. return
  119. }
  120. log.Printf("Updated song for round %s, artist: %s, title: %s, URL: %s",
  121. round, artist, title, url)
  122. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  123. }
  124. func (s *WebService) LoginHandler(w http.ResponseWriter, r *http.Request) {
  125. err := r.ParseForm()
  126. if err != nil {
  127. http.Error(w, err.Error(), http.StatusBadRequest)
  128. return
  129. }
  130. username := r.Form.Get("username")
  131. password := r.Form.Get("password")
  132. remember := r.Form.Get("remember")
  133. longer := remember == "remember-me"
  134. cookie, err := tryLogin(s.db, username, password, longer)
  135. if err != nil {
  136. log.Println("Error while trying to login", err.Error())
  137. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  138. return
  139. }
  140. http.SetCookie(w, &cookie)
  141. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  142. }
  143. func (s *WebService) SpotifyHandler(w http.ResponseWriter, r *http.Request) {
  144. url := s.spotify.auth.AuthURL("foobar")
  145. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  146. }
  147. func (s *WebService) CallbackHandler(w http.ResponseWriter, r *http.Request) {
  148. state := "foobar"
  149. token, err := s.spotify.auth.Token(state, r)
  150. if err != nil {
  151. http.Error(w, "Couldn't get token", http.StatusForbidden)
  152. return
  153. }
  154. session, err := getSession(r)
  155. if err != nil {
  156. http.Error(w, "Couldn't get session", http.StatusInternalServerError)
  157. return
  158. }
  159. client := s.spotify.auth.NewClient(token)
  160. s.spotify.client = &client
  161. profile, err := s.spotify.client.CurrentUser()
  162. if err != nil {
  163. http.Error(w, "Couldn't load profile from Spotify", http.StatusInternalServerError)
  164. return
  165. }
  166. session.spotify = profile.ID
  167. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  168. }
  169. type WebService struct {
  170. db *DB
  171. spotify *AppSpotify
  172. noCache bool
  173. }
  174. func webStart(listenAddr string, db *DB, spotify *AppSpotify) {
  175. service := &WebService{db, spotify, true}
  176. mux := http.NewServeMux()
  177. fs := http.FileServer(http.Dir("web"))
  178. mux.Handle("/css/", fs)
  179. mux.Handle("/fonts/", fs)
  180. mux.Handle("/js/", fs)
  181. mux.Handle("/favicon.ico", fs)
  182. mux.HandleFunc("/", service.IndexHandler)
  183. mux.HandleFunc("/update", service.UpdateHandler)
  184. mux.HandleFunc("/login", service.LoginHandler)
  185. mux.HandleFunc("/spotify", service.SpotifyHandler)
  186. mux.HandleFunc("/callback", service.CallbackHandler)
  187. http.ListenAndServe(listenAddr, mux)
  188. }