Skip to content

Commit

Permalink
New dev flow + auth
Browse files Browse the repository at this point in the history
  • Loading branch information
yottapanda committed Nov 2, 2024
1 parent 820239f commit eafebe1
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 82 deletions.
4 changes: 1 addition & 3 deletions .air.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
[build]
args_bin = []
full_bin = "export $(grep -v '^#' .env | xargs); ./tmp/syncify" # also exports everything in .env
cmd = "go build -o ./tmp/syncify ."
delay = 100
exclude_dir = ["node_modules"]
exclude_dir = ["node_modules", "data"]
include_ext = ["go", "css", "env"]
pre_cmd = ["npm run build-dev"]
6 changes: 4 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ WORKDIR /app

COPY static static

COPY --from=build-go /build/out/syncify /bin/
COPY --from=build-go /build/out/syncify .

COPY --from=build-tailwind /build/static/stylesheet.css static/

EXPOSE 8000

VOLUME [ "/data" ]

CMD ["syncify"]
CMD ["./syncify"]
45 changes: 23 additions & 22 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,23 @@ package main
import (
"crypto/rand"
"encoding/base64"
"errors"
"github.com/sirupsen/logrus"
"github.com/thechubbypanda/syncify/config"
"github.com/zmb3/spotify/v2"
"github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2"
"net/http"
"strings"
"time"
)

var oauthConfig oauth2.Config
var authenticator *spotifyauth.Authenticator

func SetOauthConfig(cfg config.Config) {
oauthConfig = oauth2.Config{
ClientID: cfg.ClientID,
ClientSecret: cfg.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: "https://accounts.spotify.com/authorize",
DeviceAuthURL: "",
TokenURL: "https://accounts.spotify.com/api/token",
AuthStyle: 0,
},
RedirectURL: strings.Join([]string{cfg.Url, "callback"}, "/"),
Scopes: []string{"playlist-read-private", "user-library-read", "playlist-modify-private", "playlist-modify-public"},
}
func setAuthenticator(cfg config.Config) {
authenticator = spotifyauth.New(
spotifyauth.WithRedirectURL(cfg.Url+"/callback"),
spotifyauth.WithScopes(spotifyauth.ScopePlaylistReadPrivate, spotifyauth.ScopePlaylistModifyPrivate, spotifyauth.ScopeUserLibraryRead, spotifyauth.ScopePlaylistModifyPublic),
)
}

func randomState() (string, error) {
Expand All @@ -46,18 +41,13 @@ func Login(w http.ResponseWriter, r *http.Request) {

sm.Put(r.Context(), "state", state)

http.Redirect(w, r, oauthConfig.AuthCodeURL(state), http.StatusSeeOther)
http.Redirect(w, r, authenticator.AuthURL(state), http.StatusSeeOther)
}

func Callback(w http.ResponseWriter, r *http.Request) {
state := sm.PopString(r.Context(), "state")
if state == "" || r.URL.Query().Get("state") != state {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
logrus.Traceln("state did not match:", state)
return
}

token, err := oauthConfig.Exchange(r.Context(), r.URL.Query().Get("code"))
token, err := authenticator.Token(r.Context(), state, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
logrus.Errorln(err)
Expand All @@ -73,3 +63,14 @@ func Logout(w http.ResponseWriter, r *http.Request) {
sm.Pop(r.Context(), "token")
http.Redirect(w, r, "/", http.StatusFound)
}

func GetClient(r *http.Request) (*spotify.Client, error) {
token, ok := sm.Get(r.Context(), "token").(oauth2.Token)
if !ok {
return nil, errors.New("missing token")
}
if token.Expiry.Before(time.Now()) {
return nil, errors.New("token expired")
}
return spotify.New(authenticator.Client(r.Context(), &token)), nil
}
13 changes: 13 additions & 0 deletions compose.dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
services:
syncify:
image: syncify:dev
container_name: syncify
network_mode: host
build:
context: .
dockerfile: dev.Dockerfile
env_file:
- .env
volumes:
- .:/app
- ./data:/data
7 changes: 5 additions & 2 deletions compose.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
services:
syncify:
image: ghcr.io/thechubbypanda/syncify:main
build: .
restart: unless-stopped
user: 1000:1000 # Change to your user
env_file:
- .env
volumes:
- ./data:/data
- data:/data
ports:
- 8000:8000

volumes:
data:
9 changes: 3 additions & 6 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@ package config
import "github.com/sirupsen/logrus"

type Config struct {
DataDir string `env:"DATA_DIR" envDefault:"/data"` // TODO: Figure out why this defaults to ./data when .env DATA_DIR is missing
LogLevel logrus.Level `env:"LOG_LEVEL" envDefault:"info"`
ClientID string `env:"CLIENT_ID"`
ClientSecret string `env:"CLIENT_SECRET"`
Url string `env:"URL" envDefault:"http://localhost:8000"`
Plausible Plausible
LogLevel logrus.Level `env:"LOG_LEVEL" envDefault:"info"`
Url string `env:"URL" envDefault:"http://localhost:8000"`
Plausible Plausible
}

type Plausible struct {
Expand Down
15 changes: 15 additions & 0 deletions dev.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM docker.io/library/golang:alpine AS build-go

RUN go install github.com/air-verse/air@latest

RUN apk update && apk add npm

WORKDIR /app

COPY . .

EXPOSE 8000

VOLUME [ "/data" ]

CMD ["/go/bin/air"]
9 changes: 3 additions & 6 deletions example.env
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
# Folder where the sqlite database will be stored
DATA_DIR=/data

LOG_LEVEL=info

# Grab these from your own app at https://developer.spotify.com/dashboard
CLIENT_ID=
CLIENT_SECRET=
# Grab these OAuth2 values from your own app at https://developer.spotify.com/dashboard
SPOTIFY_ID=
SPOTIFY_SECRET=

# This should be the URL that users will use to reach the app
# It's used to generate the OAuth2 callback URL
Expand Down
30 changes: 13 additions & 17 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ package main
import (
"database/sql"
"encoding/gob"
"net/http"
"path/filepath"
"strings"
"time"

"github.com/alexedwards/scs/sqlite3store"
"github.com/alexedwards/scs/v2"
"github.com/chi-middleware/logrus-logger"
Expand All @@ -20,9 +15,10 @@ import (
"github.com/thechubbypanda/syncify/config"
"github.com/thechubbypanda/syncify/model"
"github.com/thechubbypanda/syncify/views"
"github.com/zmb3/spotify/v2"
"github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2"
"net/http"
"path/filepath"
"strings"
)

var cfg config.Config
Expand All @@ -38,11 +34,11 @@ func main() {

logrus.SetLevel(cfg.LogLevel)

gob.Register(oauth2.Token{})
setAuthenticator(cfg)

SetOauthConfig(cfg)
gob.Register(oauth2.Token{})

dbFilename := filepath.Join(cfg.DataDir, "syncify.db")
dbFilename := filepath.Join("/data", "syncify.db")

db, err := sql.Open("sqlite3", "file:"+dbFilename)
if err != nil {
Expand Down Expand Up @@ -108,25 +104,24 @@ func main() {
r.Get("/*", http.StripPrefix("/", http.FileServer(http.Dir("static/"))).ServeHTTP)
})

logrus.Infoln("starting web server on", "0.0.0.0:8000")
httpErr := http.ListenAndServe("0.0.0.0:8000", r)
logrus.Infoln("starting web server on", ":8000")
httpErr := http.ListenAndServe(":8000", r)
if httpErr != nil {
logrus.Errorln(httpErr)
}
}

func Root(w http.ResponseWriter, r *http.Request) {
token, ok := sm.Get(r.Context(), "token").(oauth2.Token)
if !ok || token.Expiry.Before(time.Now()) {
s, err := GetClient(r)
if err != nil {
logrus.Debugln(err)
err := views.Root(model.Model{Plausible: &cfg.Plausible}).Render(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
logrus.Errorln(err)
}
return
}
s := spotify.New(spotifyauth.New().Client(r.Context(), &token))

user, err := s.CurrentUser(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Expand All @@ -140,6 +135,7 @@ func Root(w http.ResponseWriter, r *http.Request) {
}).Render(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logrus.Errorln(err)
return
}
}
28 changes: 10 additions & 18 deletions sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import (
"github.com/thechubbypanda/syncify/model"
"github.com/thechubbypanda/syncify/views"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2"
"net/http"
"time"
)

func getLikedTrackIds(r *http.Request, s *spotify.Client) ([]spotify.ID, error) {
Expand Down Expand Up @@ -122,7 +119,7 @@ func truncateWrapper(r *http.Request, s *spotify.Client, user *spotify.PrivateUs

type LikedTrackIdsResult struct {
Tracks []spotify.ID
Err error
Err error
}

func getLikedTrackIdsWrapper(r *http.Request, s *spotify.Client, c chan LikedTrackIdsResult) {
Expand All @@ -133,9 +130,7 @@ func getLikedTrackIdsWrapper(r *http.Request, s *spotify.Client, c chan LikedTra
}
}

func sync(r *http.Request, token *oauth2.Token) model.SyncResponse {
s := spotify.New(spotifyauth.New().Client(r.Context(), token))

func sync(r *http.Request, s *spotify.Client) model.SyncResponse {
user, err := s.CurrentUser(r.Context())
if err != nil {
logrus.Errorln("failed to fetch user: ", err)
Expand All @@ -158,13 +153,13 @@ func sync(r *http.Request, token *oauth2.Token) model.SyncResponse {
likedIdsChannel := make(chan LikedTrackIdsResult)
go getLikedTrackIdsWrapper(r, s, likedIdsChannel)

likedResult := <- likedIdsChannel
likedResult := <-likedIdsChannel
if likedResult.Err != nil {
logrus.Errorln(user.ID, ":", err)
return model.SyncResponse{Err: err}
}
trackIds := likedResult.Tracks

logrus.Debugln(user.ID, ":", "found", len(trackIds), "liked songs")

if <-truncateChannel != nil {
Expand Down Expand Up @@ -194,19 +189,16 @@ func sync(r *http.Request, token *oauth2.Token) model.SyncResponse {
}

func Sync(w http.ResponseWriter, r *http.Request) {
token, ok := sm.Get(r.Context(), "token").(oauth2.Token)
if !ok || token.Expiry.Before(time.Now()) {
s, err := GetClient(r)
if err != nil {
logrus.Debugln(err)
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
logrus.Traceln("no token or expired")
return
}

syncResponse := sync(r, &token)
err := views.Outcome(model.Model{
Plausible: nil,
User: nil,
SyncOutcome: &syncResponse,
}).Render(w)
syncResponse := sync(r, s)

err = views.Outcome(&syncResponse).Render(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
Expand Down
12 changes: 6 additions & 6 deletions views/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func Root(model model.Model) g.Node {
svg.Path(svg.D("M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"), svg.Fill("currentColor")),
svg.Path(svg.D("M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"), svg.Fill("currentFill")),
),
Outcome(model),
Outcome(model.SyncOutcome),
P(
Class("absolute bottom-0 p-4 text-center"),
A(Class("text-green-500"), Href("https://github.com/thechubbypanda/syncify"), g.Text("Syncify")),
Expand Down Expand Up @@ -74,14 +74,14 @@ func Buttons(model model.Model) g.Node {
)
}

func Outcome(model model.Model) g.Node {
func Outcome(syncOutcome *model.SyncResponse) g.Node {
var o g.Node
if model.SyncOutcome == nil {
if syncOutcome == nil {
o = Div()
} else if model.SyncOutcome.Err != nil {
o = g.Text("Error: " + model.SyncOutcome.Err.Error())
} else if syncOutcome.Err != nil {
o = g.Text("Error: " + syncOutcome.Err.Error())
} else {
o = Span(g.Text("Successfully synchronized "+strconv.Itoa(model.SyncOutcome.Count)+" tracks to your "), A(Class("text-green-500"), Href(model.SyncOutcome.PlaylistUrl), g.Text("Syncify playlist")))
o = Span(g.Text("Successfully synchronized "+strconv.Itoa(syncOutcome.Count)+" tracks to your "), A(Class("text-green-500"), Href(syncOutcome.PlaylistUrl), g.Text("Syncify playlist")))
}
return Div(ID("outcome"), Class("text-gray-500 text-center"), o)
}

0 comments on commit eafebe1

Please sign in to comment.