mirror of
https://github.com/riwiwa/muzi.git
synced 2026-02-28 11:56:57 -08:00
Added userID in history table for per profile history, reworked primary key. Profile recent history table
This commit is contained in:
95
db/db.go
Normal file
95
db/db.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TableExists(name string, conn *pgx.Conn) bool {
|
||||||
|
var exists bool
|
||||||
|
err := conn.QueryRow(
|
||||||
|
context.Background(),
|
||||||
|
`SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND
|
||||||
|
tablename = $1);`,
|
||||||
|
name,
|
||||||
|
).
|
||||||
|
Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "SELECT EXISTS failed: %v\n", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return exists
|
||||||
|
}
|
||||||
|
|
||||||
|
func DbExists() bool {
|
||||||
|
conn, err := pgx.Connect(
|
||||||
|
context.Background(),
|
||||||
|
"postgres://postgres:postgres@localhost:5432/muzi",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer conn.Close(context.Background())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateDB() error {
|
||||||
|
conn, err := pgx.Connect(
|
||||||
|
context.Background(),
|
||||||
|
"postgres://postgres:postgres@localhost:5432",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Cannot connect to PostgreSQL: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer conn.Close(context.Background())
|
||||||
|
_, err = conn.Exec(context.Background(), "CREATE DATABASE muzi")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Cannot create muzi database: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateHistoryTable(conn *pgx.Conn) error {
|
||||||
|
_, err := conn.Exec(context.Background(),
|
||||||
|
`CREATE TABLE IF NOT EXISTS history (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
timestamp TIMESTAMPTZ NOT NULL,
|
||||||
|
song_name TEXT NOT NULL,
|
||||||
|
artist TEXT NOT NULL,
|
||||||
|
album_name TEXT,
|
||||||
|
ms_played INTEGER,
|
||||||
|
platform TEXT DEFAULT 'spotify',
|
||||||
|
UNIQUE (user_id, song_name, artist, timestamp)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_history_user_timestamp ON history(user_id, timestamp DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_history_user_artist ON history(user_id, artist);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_history_user_song ON history(user_id, song_name);`)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error creating history table: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateUsersTable(conn *pgx.Conn) error {
|
||||||
|
_, err := conn.Exec(context.Background(),
|
||||||
|
`CREATE TABLE IF NOT EXISTS users (
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
password TEXT NOT NULL,
|
||||||
|
bio TEXT DEFAULT 'This profile has no bio.',
|
||||||
|
pfp TEXT DEFAULT '/files/assets/default.png',
|
||||||
|
allow_duplicate_edits BOOLEAN DEFAULT FALSE,
|
||||||
|
pk SERIAL PRIMARY KEY
|
||||||
|
);`)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error creating users table: %v\n", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
38
main.go
38
main.go
@@ -1,18 +1,22 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
|
"muzi/db"
|
||||||
"muzi/migrate"
|
"muzi/migrate"
|
||||||
"muzi/web"
|
"muzi/web"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func dbCheck() error {
|
func dbCheck() error {
|
||||||
if !migrate.DbExists() {
|
if !db.DbExists() {
|
||||||
err := migrate.CreateDB()
|
err := db.CreateDB()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Error creating muzi DB: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Error creating muzi DB: %v\n", err)
|
||||||
return err
|
return err
|
||||||
@@ -68,14 +72,40 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fmt.Println("Setting up database tables...")
|
||||||
|
conn, err := pgx.Connect(
|
||||||
|
context.Background(),
|
||||||
|
"postgres://postgres:postgres@localhost:5432/muzi",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Cannot connect to muzi database: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close(context.Background())
|
||||||
|
|
||||||
|
err = db.CreateHistoryTable(conn)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error creating history table: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = db.CreateUsersTable(conn)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error creating users table: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
username := ""
|
username := ""
|
||||||
apiKey := ""
|
apiKey := ""
|
||||||
fmt.Printf("Importing LastFM data for %s\n", username)
|
fmt.Printf("Importing LastFM data for %s\n", username)
|
||||||
err = migrate.ImportLastFM(username, apiKey)
|
// TODO:
|
||||||
|
// remove hardcoded userID by creating webUI import pages and getting
|
||||||
|
// userID from login session
|
||||||
|
err = migrate.ImportLastFM(username, apiKey, 1)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = migrate.ImportSpotify()
|
err = migrate.ImportSpotify(1)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type LastFMTrack struct {
|
type LastFMTrack struct {
|
||||||
|
UserId int
|
||||||
Timestamp time.Time
|
Timestamp time.Time
|
||||||
SongName string
|
SongName string
|
||||||
Artist string
|
Artist string
|
||||||
@@ -50,37 +51,17 @@ type Response struct {
|
|||||||
} `json:"recenttracks"`
|
} `json:"recenttracks"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ImportLastFM(username string, apiKey string) error {
|
func ImportLastFM(username string, apiKey string, userId int) error {
|
||||||
if !DbExists() {
|
|
||||||
err := CreateDB()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error creating muzi database: %v\n", err)
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
conn, err := pgx.Connect(
|
conn, err := pgx.Connect(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
"postgres://postgres:postgres@localhost:5432/muzi",
|
"postgres://postgres:postgres@localhost:5432/muzi",
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Cannot connect to muzi database: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Cannot connect to muzi database: %v\n", err)
|
||||||
panic(err)
|
return err
|
||||||
}
|
}
|
||||||
defer conn.Close(context.Background())
|
defer conn.Close(context.Background())
|
||||||
|
|
||||||
if !TableExists("history", conn) {
|
|
||||||
_, err = conn.Exec(
|
|
||||||
context.Background(),
|
|
||||||
`CREATE TABLE history ( ms_played INTEGER, timestamp TIMESTAMPTZ,
|
|
||||||
song_name TEXT, artist TEXT, album_name TEXT, PRIMARY KEY (timestamp,
|
|
||||||
ms_played, artist, song_name));`,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot create history table: %v\n", err)
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
totalImported := 0
|
totalImported := 0
|
||||||
|
|
||||||
resp, err := http.Get(
|
resp, err := http.Get(
|
||||||
@@ -106,13 +87,11 @@ func ImportLastFM(username string, apiKey string) error {
|
|||||||
pageChan := make(chan pageResult, 20)
|
pageChan := make(chan pageResult, 20)
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
// use 10 workers
|
|
||||||
wg.Add(10)
|
wg.Add(10)
|
||||||
|
|
||||||
for worker := range 10 {
|
for worker := range 10 {
|
||||||
go func(workerID int) {
|
go func(workerID int) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
// distrubute 10 pages to each worker
|
|
||||||
for page := workerID + 1; page <= totalPages; page += 10 {
|
for page := workerID + 1; page <= totalPages; page += 10 {
|
||||||
resp, err := http.Get(
|
resp, err := http.Get(
|
||||||
"https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" +
|
"https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" +
|
||||||
@@ -140,6 +119,7 @@ func ImportLastFM(username string, apiKey string) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
pageTracks = append(pageTracks, LastFMTrack{
|
pageTracks = append(pageTracks, LastFMTrack{
|
||||||
|
UserId: userId,
|
||||||
Timestamp: time.Unix(unixTime, 0),
|
Timestamp: time.Unix(unixTime, 0),
|
||||||
SongName: data.Recenttracks.Track[j].Name,
|
SongName: data.Recenttracks.Track[j].Name,
|
||||||
Artist: data.Recenttracks.Track[j].Artist.Text,
|
Artist: data.Recenttracks.Track[j].Artist.Text,
|
||||||
@@ -197,22 +177,35 @@ func insertBatch(conn *pgx.Conn, tracks []LastFMTrack, totalImported *int, batch
|
|||||||
|
|
||||||
for i, track := range tracks {
|
for i, track := range tracks {
|
||||||
batchValues = append(batchValues, fmt.Sprintf(
|
batchValues = append(batchValues, fmt.Sprintf(
|
||||||
"($%d, $%d, $%d, $%d, $%d)",
|
"($%d, $%d, $%d, $%d, $%d, $%d, $%d)",
|
||||||
len(
|
len(batchArgs)+1,
|
||||||
batchArgs,
|
|
||||||
)+1,
|
|
||||||
len(batchArgs)+2,
|
len(batchArgs)+2,
|
||||||
len(batchArgs)+3,
|
len(batchArgs)+3,
|
||||||
len(batchArgs)+4,
|
len(batchArgs)+4,
|
||||||
len(batchArgs)+5,
|
len(batchArgs)+5,
|
||||||
|
len(batchArgs)+6,
|
||||||
|
len(batchArgs)+7,
|
||||||
))
|
))
|
||||||
batchArgs = append(batchArgs, track.Timestamp, track.SongName, track.Artist, track.Album, 0)
|
// lastfm doesn't store playtime for each track, so set to 0
|
||||||
|
batchArgs = append(
|
||||||
|
batchArgs,
|
||||||
|
track.UserId,
|
||||||
|
track.Timestamp,
|
||||||
|
track.SongName,
|
||||||
|
track.Artist,
|
||||||
|
track.Album,
|
||||||
|
0,
|
||||||
|
"lastfm",
|
||||||
|
)
|
||||||
|
|
||||||
if len(batchValues) >= batchSize || i == len(tracks)-1 {
|
if len(batchValues) >= batchSize || i == len(tracks)-1 {
|
||||||
result, err := tx.Exec(
|
result, err := tx.Exec(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
`INSERT INTO history (timestamp, song_name, artist, album_name, ms_played) VALUES `+
|
`INSERT INTO history (user_id, timestamp, song_name, artist, album_name, ms_played, platform) VALUES `+
|
||||||
strings.Join(batchValues, ", ")+` ON CONFLICT DO NOTHING;`,
|
strings.Join(
|
||||||
|
batchValues,
|
||||||
|
", ",
|
||||||
|
)+` ON CONFLICT ON CONSTRAINT history_user_id_song_name_artist_timestamp_key DO NOTHING;`,
|
||||||
batchArgs...,
|
batchArgs...,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
package migrate
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TableExists(name string, conn *pgx.Conn) bool {
|
|
||||||
var exists bool
|
|
||||||
err := conn.QueryRow(
|
|
||||||
context.Background(),
|
|
||||||
`SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND
|
|
||||||
tablename = $1);`,
|
|
||||||
name,
|
|
||||||
).
|
|
||||||
Scan(&exists)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "SELECT EXISTS failed: %v\n", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return exists
|
|
||||||
}
|
|
||||||
|
|
||||||
func DbExists() bool {
|
|
||||||
conn, err := pgx.Connect(
|
|
||||||
context.Background(),
|
|
||||||
"postgres://postgres:postgres@localhost:5432/muzi",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
defer conn.Close(context.Background())
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateDB() error {
|
|
||||||
conn, err := pgx.Connect(
|
|
||||||
context.Background(),
|
|
||||||
"postgres://postgres:postgres@localhost:5432",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot connect to PostgreSQL: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer conn.Close(context.Background())
|
|
||||||
_, err = conn.Exec(context.Background(), "CREATE DATABASE muzi")
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot create muzi database: %v\n", err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
@@ -39,59 +40,85 @@ type SpotifyTrack struct {
|
|||||||
Incognito bool `json:"-"`
|
Incognito bool `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func trackKey(t SpotifyTrack) string {
|
type existingTrack struct {
|
||||||
return fmt.Sprintf("%s|%d|%s|%s", t.Timestamp, t.Played, t.Artist, t.Name)
|
Timestamp time.Time
|
||||||
|
SongName string
|
||||||
|
Artist string
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExistingTracks(conn *pgx.Conn, tracks []SpotifyTrack) (map[string]bool, error) {
|
func getExistingTracks(conn *pgx.Conn, userId int, tracks []SpotifyTrack) (map[string]bool, error) {
|
||||||
if len(tracks) == 0 {
|
if len(tracks) == 0 {
|
||||||
return map[string]bool{}, nil
|
return map[string]bool{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var conditions []string
|
// find min/max timestamps in this batch to create time window
|
||||||
var args []any
|
var minTs, maxTs time.Time
|
||||||
|
for _, t := range tracks {
|
||||||
for i, t := range tracks {
|
ts, err := time.Parse(time.RFC3339Nano, t.Timestamp)
|
||||||
base := i * 4
|
if err != nil {
|
||||||
conditions = append(conditions,
|
continue
|
||||||
fmt.Sprintf("(timestamp=$%d AND ms_played=$%d AND artist=$%d AND song_name=$%d)",
|
}
|
||||||
base+1, base+2, base+3, base+4))
|
if minTs.IsZero() || ts.Before(minTs) {
|
||||||
args = append(args, t.Timestamp, t.Played, t.Artist, t.Name)
|
minTs = ts
|
||||||
|
}
|
||||||
|
if ts.After(maxTs) {
|
||||||
|
maxTs = ts
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
query := fmt.Sprintf(
|
if minTs.IsZero() {
|
||||||
"SELECT timestamp, ms_played, artist, song_name FROM history WHERE %s",
|
return map[string]bool{}, nil
|
||||||
strings.Join(conditions, " OR "))
|
}
|
||||||
|
|
||||||
rows, err := conn.Query(context.Background(), query, args...)
|
// query only tracks within [min-20s, max+20s] window using timestamp index
|
||||||
|
rows, err := conn.Query(context.Background(),
|
||||||
|
`SELECT song_name, artist, timestamp
|
||||||
|
FROM history
|
||||||
|
WHERE user_id = $1
|
||||||
|
AND timestamp BETWEEN $2 AND $3`,
|
||||||
|
userId,
|
||||||
|
minTs.Add(-20*time.Second),
|
||||||
|
maxTs.Add(20*time.Second))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
existing := make(map[string]bool)
|
existing := make(map[string]bool)
|
||||||
|
var existingTracks []existingTrack
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var ts string
|
var t existingTrack
|
||||||
var played int
|
if err := rows.Scan(&t.SongName, &t.Artist, &t.Timestamp); err != nil {
|
||||||
var artist, song string
|
|
||||||
if err := rows.Scan(&ts, &played, &artist, &song); err != nil {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
key := fmt.Sprintf("%s|%d|%s|%s", ts, played, artist, song)
|
existingTracks = append(existingTracks, t)
|
||||||
existing[key] = true
|
}
|
||||||
|
|
||||||
|
// check each incoming track against existing ones within 20 second window
|
||||||
|
for _, newTrack := range tracks {
|
||||||
|
newTs, err := time.Parse(time.RFC3339Nano, newTrack.Timestamp)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, existTrack := range existingTracks {
|
||||||
|
if newTrack.Name == existTrack.SongName && newTrack.Artist == existTrack.Artist {
|
||||||
|
diff := newTs.Sub(existTrack.Timestamp)
|
||||||
|
if diff < 0 {
|
||||||
|
diff = -diff
|
||||||
|
}
|
||||||
|
if diff < 20*time.Second {
|
||||||
|
key := fmt.Sprintf("%s|%s|%s", newTrack.Artist, newTrack.Name, newTrack.Timestamp)
|
||||||
|
existing[key] = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return existing, nil
|
return existing, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func JsonToDB(jsonFile string) error {
|
func JsonToDB(jsonFile string, userId int) error {
|
||||||
if !DbExists() {
|
|
||||||
err := CreateDB()
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error creating muzi database: %v\n", err)
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
conn, err := pgx.Connect(
|
conn, err := pgx.Connect(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
"postgres://postgres:postgres@localhost:5432/muzi",
|
"postgres://postgres:postgres@localhost:5432/muzi",
|
||||||
@@ -101,18 +128,7 @@ func JsonToDB(jsonFile string) error {
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
defer conn.Close(context.Background())
|
defer conn.Close(context.Background())
|
||||||
if !TableExists("history", conn) {
|
|
||||||
_, err = conn.Exec(
|
|
||||||
context.Background(),
|
|
||||||
`CREATE TABLE history ( ms_played INTEGER, timestamp TIMESTAMPTZ,
|
|
||||||
song_name TEXT, artist TEXT, album_name TEXT, PRIMARY KEY (timestamp,
|
|
||||||
ms_played, artist, song_name));`,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot create history table: %v\n", err)
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
jsonData, err := os.ReadFile(jsonFile)
|
jsonData, err := os.ReadFile(jsonFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Cannot read %s: %v\n", jsonFile, err)
|
fmt.Fprintf(os.Stderr, "Cannot read %s: %v\n", jsonFile, err)
|
||||||
@@ -136,7 +152,7 @@ func JsonToDB(jsonFile string) error {
|
|||||||
|
|
||||||
var validTracks []SpotifyTrack
|
var validTracks []SpotifyTrack
|
||||||
for i := batchStart; i < batchEnd; i++ {
|
for i := batchStart; i < batchEnd; i++ {
|
||||||
if tracks[i].Played >= 20000 {
|
if tracks[i].Played >= 20000 && tracks[i].Name != "" && tracks[i].Artist != "" {
|
||||||
validTracks = append(validTracks, tracks[i])
|
validTracks = append(validTracks, tracks[i])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,7 +161,7 @@ func JsonToDB(jsonFile string) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
existing, err := getExistingTracks(conn, validTracks)
|
existing, err := getExistingTracks(conn, userId, validTracks)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Error checking existing tracks: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Error checking existing tracks: %v\n", err)
|
||||||
continue
|
continue
|
||||||
@@ -155,20 +171,31 @@ func JsonToDB(jsonFile string) error {
|
|||||||
var batchArgs []any
|
var batchArgs []any
|
||||||
|
|
||||||
for _, t := range validTracks {
|
for _, t := range validTracks {
|
||||||
key := trackKey(t)
|
key := fmt.Sprintf("%s|%s|%s", t.Artist, t.Name, t.Timestamp)
|
||||||
if existing[key] {
|
if existing[key] {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
batchValues = append(batchValues, fmt.Sprintf(
|
batchValues = append(batchValues, fmt.Sprintf(
|
||||||
"($%d, $%d, $%d, $%d, $%d)",
|
"($%d, $%d, $%d, $%d, $%d, $%d, $%d)",
|
||||||
len(batchArgs)+1,
|
len(batchArgs)+1,
|
||||||
len(batchArgs)+2,
|
len(batchArgs)+2,
|
||||||
len(batchArgs)+3,
|
len(batchArgs)+3,
|
||||||
len(batchArgs)+4,
|
len(batchArgs)+4,
|
||||||
len(batchArgs)+5,
|
len(batchArgs)+5,
|
||||||
|
len(batchArgs)+6,
|
||||||
|
len(batchArgs)+7,
|
||||||
))
|
))
|
||||||
batchArgs = append(batchArgs, t.Timestamp, t.Name, t.Artist, t.Album, t.Played)
|
batchArgs = append(
|
||||||
|
batchArgs,
|
||||||
|
userId,
|
||||||
|
t.Timestamp,
|
||||||
|
t.Name,
|
||||||
|
t.Artist,
|
||||||
|
t.Album,
|
||||||
|
t.Played,
|
||||||
|
"spotify",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(batchValues) == 0 {
|
if len(batchValues) == 0 {
|
||||||
@@ -177,9 +204,12 @@ func JsonToDB(jsonFile string) error {
|
|||||||
|
|
||||||
_, err = conn.Exec(
|
_, err = conn.Exec(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
`INSERT INTO history (timestamp, song_name, artist, album_name, ms_played) VALUES `+
|
`INSERT INTO history (user_id, timestamp, song_name, artist, album_name, ms_played, platform) VALUES `+
|
||||||
strings.Join(batchValues, ", ")+
|
strings.Join(
|
||||||
` ON CONFLICT DO NOTHING;`,
|
batchValues,
|
||||||
|
", ",
|
||||||
|
)+
|
||||||
|
` ON CONFLICT ON CONSTRAINT history_user_id_song_name_artist_timestamp_key DO NOTHING;`,
|
||||||
batchArgs...,
|
batchArgs...,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -193,7 +223,7 @@ func JsonToDB(jsonFile string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func AddDirToDB(path string) error {
|
func AddDirToDB(path string, userId int) error {
|
||||||
dirs, err := os.ReadDir(path)
|
dirs, err := os.ReadDir(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Error while reading path: %s: %v\n", path, err)
|
fmt.Fprintf(os.Stderr, "Error while reading path: %s: %v\n", path, err)
|
||||||
@@ -215,12 +245,11 @@ func AddDirToDB(path string) error {
|
|||||||
if !strings.Contains(jsonFileName, ".json") {
|
if !strings.Contains(jsonFileName, ".json") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// prevents parsing spotify video data that causes duplicates
|
|
||||||
if strings.Contains(jsonFileName, "Video") {
|
if strings.Contains(jsonFileName, "Video") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
jsonFilePath := filepath.Join(subPath, jsonFileName)
|
jsonFilePath := filepath.Join(subPath, jsonFileName)
|
||||||
err = JsonToDB(jsonFilePath)
|
err = JsonToDB(jsonFilePath, userId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr,
|
fmt.Fprintf(os.Stderr,
|
||||||
"Error adding json data (%s) to muzi database: %v", jsonFilePath, err)
|
"Error adding json data (%s) to muzi database: %v", jsonFilePath, err)
|
||||||
@@ -231,7 +260,7 @@ func AddDirToDB(path string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ImportSpotify() error {
|
func ImportSpotify(userId int) error {
|
||||||
path := filepath.Join(".", "imports", "spotify", "zip")
|
path := filepath.Join(".", "imports", "spotify", "zip")
|
||||||
targetBase := filepath.Join(".", "imports", "spotify", "extracted")
|
targetBase := filepath.Join(".", "imports", "spotify", "extracted")
|
||||||
entries, err := os.ReadDir(path)
|
entries, err := os.ReadDir(path)
|
||||||
@@ -258,7 +287,7 @@ func ImportSpotify() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
err = AddDirToDB(targetBase)
|
err = AddDirToDB(targetBase, userId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr,
|
fmt.Fprintf(os.Stderr,
|
||||||
"Error adding directory of data (%s) to muzi database: %v\n",
|
"Error adding directory of data (%s) to muzi database: %v\n",
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ body {
|
|||||||
color: #AFA;
|
color: #AFA;
|
||||||
align-content: center;
|
align-content: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
max-width: 100vw;
|
max-width: 70vw;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
|
width: 70vw;
|
||||||
|
font-family: sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
.page_buttons {
|
.page_buttons {
|
||||||
@@ -23,6 +26,47 @@ body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.user-stats-top {
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username-bio {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
margin-left: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-top {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-content: center;
|
||||||
|
h1 {
|
||||||
|
color: #FFFFFF;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
color: #777777;
|
||||||
|
font-size: 15px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
color: #AAAAAA;
|
||||||
|
font-size: 25px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
img {
|
||||||
|
object-fit: cover;
|
||||||
|
width: 250px;
|
||||||
|
height: 250px;
|
||||||
|
border-radius: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-error {
|
||||||
|
color: #AA0000;
|
||||||
|
}
|
||||||
|
|
||||||
.history {
|
.history {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<link rel="stylesheet" href="/files/style.css" type="text/css">
|
|
||||||
<title>
|
|
||||||
muzi | History
|
|
||||||
</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
Scrobbles: {{.Content}}<br><br>
|
|
||||||
<div class=history>
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<th>Artist</th>
|
|
||||||
<th>Title</th>
|
|
||||||
<th>Timestamp</th>
|
|
||||||
</tr>
|
|
||||||
{{$artists := .Artists}}
|
|
||||||
{{$times := .Times}}
|
|
||||||
{{range $index, $title := .Titles}}
|
|
||||||
<tr>
|
|
||||||
<td>{{index $artists $index}}</td>
|
|
||||||
<td>{{$title}}</td>
|
|
||||||
<td>{{index $times $index}}</td>
|
|
||||||
</tr>
|
|
||||||
{{end}}
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
{{$page := .Page}}
|
|
||||||
<div class=page_buttons>
|
|
||||||
<a href="/history?page={{Sub $page 1}}">Prev Page</a>
|
|
||||||
<a href="/history?page={{Add $page 1}}">Next Page</a>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -14,9 +14,32 @@
|
|||||||
<h2>{{.Bio}}</h2>
|
<h2>{{.Bio}}</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="user-stats-top">
|
<div class="user-stats-top">
|
||||||
<h3>101238 Listens</h3>
|
<h3>{{.ScrobbleCount}} Listens</h3>
|
||||||
<h3>1298 Artists</h3>
|
<h3>{{.ArtistCount}} Artists</h3>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="history">
|
||||||
|
<h3>Listening History</h3>
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Artist</th>
|
||||||
|
<th>Title</th>
|
||||||
|
<th>Timestamp</th>
|
||||||
|
</tr>
|
||||||
|
{{$artists := .Artists}}
|
||||||
|
{{$times := .Times}}
|
||||||
|
{{range $index, $title := .Titles}}
|
||||||
|
<tr>
|
||||||
|
<td>{{index $artists $index}}</td>
|
||||||
|
<td>{{$title}}</td>
|
||||||
|
<td>{{index $times $index}}</td>
|
||||||
|
</tr>
|
||||||
|
{{end}}
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="page_buttons">
|
||||||
|
<a href="/profile/{{.Username}}?page={{Sub .Page 1}}">Prev Page</a>
|
||||||
|
<a href="/profile/{{.Username}}?page={{Add .Page 1}}">Next Page</a>
|
||||||
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
221
web/web.go
221
web/web.go
@@ -8,7 +8,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"muzi/migrate"
|
"muzi/db"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
@@ -18,12 +18,17 @@ import (
|
|||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type PageData struct {
|
type ProfileData struct {
|
||||||
Content int
|
Username string
|
||||||
Artists []string
|
Bio string
|
||||||
Titles []string
|
Pfp string
|
||||||
Times []string
|
AllowDuplicateEdits bool
|
||||||
Page int
|
ScrobbleCount int
|
||||||
|
ArtistCount int
|
||||||
|
Artists []string
|
||||||
|
Titles []string
|
||||||
|
Times []string
|
||||||
|
Page int
|
||||||
}
|
}
|
||||||
|
|
||||||
func Sub(a int, b int) int {
|
func Sub(a int, b int) int {
|
||||||
@@ -34,16 +39,24 @@ func Add(a int, b int) int {
|
|||||||
return a + b
|
return a + b
|
||||||
}
|
}
|
||||||
|
|
||||||
func getTimes(conn *pgx.Conn, lim int, off int) []string {
|
func getUserIdByUsername(conn *pgx.Conn, username string) (int, error) {
|
||||||
|
var userId int
|
||||||
|
err := conn.QueryRow(context.Background(), "SELECT pk FROM users WHERE username = $1;", username).
|
||||||
|
Scan(&userId)
|
||||||
|
return userId, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTimes(conn *pgx.Conn, userId int, lim int, off int) []string {
|
||||||
var times []string
|
var times []string
|
||||||
rows, err := conn.Query(
|
rows, err := conn.Query(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
"SELECT timestamp FROM history ORDER BY timestamp DESC LIMIT $1 OFFSET $2;",
|
"SELECT timestamp FROM history WHERE user_id = $1 ORDER BY timestamp DESC LIMIT $2 OFFSET $3;",
|
||||||
|
userId,
|
||||||
lim,
|
lim,
|
||||||
off,
|
off,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "SELECT COUNT failed: %v\n", err)
|
fmt.Fprintf(os.Stderr, "SELECT timestamp failed: %v\n", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
@@ -58,16 +71,17 @@ func getTimes(conn *pgx.Conn, lim int, off int) []string {
|
|||||||
return times
|
return times
|
||||||
}
|
}
|
||||||
|
|
||||||
func getTitles(conn *pgx.Conn, lim int, off int) []string {
|
func getTitles(conn *pgx.Conn, userId int, lim int, off int) []string {
|
||||||
var titles []string
|
var titles []string
|
||||||
rows, err := conn.Query(
|
rows, err := conn.Query(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
"SELECT song_name FROM history ORDER BY timestamp DESC LIMIT $1 OFFSET $2;",
|
"SELECT song_name FROM history WHERE user_id = $1 ORDER BY timestamp DESC LIMIT $2 OFFSET $3;",
|
||||||
|
userId,
|
||||||
lim,
|
lim,
|
||||||
off,
|
off,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "SELECT COUNT failed: %v\n", err)
|
fmt.Fprintf(os.Stderr, "SELECT song_name failed: %v\n", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
@@ -82,16 +96,17 @@ func getTitles(conn *pgx.Conn, lim int, off int) []string {
|
|||||||
return titles
|
return titles
|
||||||
}
|
}
|
||||||
|
|
||||||
func getArtists(conn *pgx.Conn, lim int, off int) []string {
|
func getArtists(conn *pgx.Conn, userId int, lim int, off int) []string {
|
||||||
var artists []string
|
var artists []string
|
||||||
rows, err := conn.Query(
|
rows, err := conn.Query(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
"SELECT artist FROM history ORDER BY timestamp DESC LIMIT $1 OFFSET $2;",
|
"SELECT artist FROM history WHERE user_id = $1 ORDER BY timestamp DESC LIMIT $2 OFFSET $3;",
|
||||||
|
userId,
|
||||||
lim,
|
lim,
|
||||||
off,
|
off,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "SELECT COUNT failed: %v\n", err)
|
fmt.Fprintf(os.Stderr, "SELECT artist failed: %v\n", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
@@ -106,9 +121,10 @@ func getArtists(conn *pgx.Conn, lim int, off int) []string {
|
|||||||
return artists
|
return artists
|
||||||
}
|
}
|
||||||
|
|
||||||
func getScrobbles(conn *pgx.Conn) int {
|
func getScrobbles(conn *pgx.Conn, userId int) int {
|
||||||
var count int
|
var count int
|
||||||
err := conn.QueryRow(context.Background(), "SELECT COUNT (*) FROM history;").Scan(&count)
|
err := conn.QueryRow(context.Background(), "SELECT COUNT(*) FROM history WHERE user_id = $1;", userId).
|
||||||
|
Scan(&count)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "SELECT COUNT failed: %v\n", err)
|
fmt.Fprintf(os.Stderr, "SELECT COUNT failed: %v\n", err)
|
||||||
return 0
|
return 0
|
||||||
@@ -116,6 +132,17 @@ func getScrobbles(conn *pgx.Conn) int {
|
|||||||
return count
|
return count
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getArtistCount(conn *pgx.Conn, userId int) int {
|
||||||
|
var count int
|
||||||
|
err := conn.QueryRow(context.Background(), "SELECT COUNT(DISTINCT artist) FROM history WHERE user_id = $1;", userId).
|
||||||
|
Scan(&count)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "SELECT artist count failed: %v\n", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
func hashPassword(pass []byte) string {
|
func hashPassword(pass []byte) string {
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -150,31 +177,18 @@ func createAccount(w http.ResponseWriter, r *http.Request) {
|
|||||||
username := r.FormValue("uname")
|
username := r.FormValue("uname")
|
||||||
hashedPassword := hashPassword([]byte(r.FormValue("pass")))
|
hashedPassword := hashPassword([]byte(r.FormValue("pass")))
|
||||||
|
|
||||||
if !migrate.TableExists("users", conn) {
|
err = db.CreateUsersTable(conn)
|
||||||
_, err = conn.Exec(
|
if err != nil {
|
||||||
context.Background(),
|
fmt.Fprintf(os.Stderr, "Error ensuring users table exists: %v\n", err)
|
||||||
`CREATE TABLE users (
|
http.Redirect(w, r, "/createaccount", http.StatusSeeOther)
|
||||||
username TEXT,
|
return
|
||||||
password TEXT,
|
|
||||||
bio TEXT,
|
|
||||||
pfp TEXT,
|
|
||||||
pk SERIAL,
|
|
||||||
PRIMARY KEY (pk)
|
|
||||||
);`,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot create users table: %v\n", err)
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = conn.Exec(
|
_, err = conn.Exec(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
`INSERT INTO users (username, password, bio, pfp) VALUES ($1, $2, $3, $4);`,
|
`INSERT INTO users (username, password) VALUES ($1, $2);`,
|
||||||
username,
|
username,
|
||||||
hashedPassword,
|
hashedPassword,
|
||||||
"This profile has no bio.",
|
|
||||||
"/files/assets/default.png",
|
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Cannot add new user to users table: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Cannot add new user to users table: %v\n", err)
|
||||||
@@ -255,61 +269,6 @@ func loginPageHandler() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func historyPage(w http.ResponseWriter, r *http.Request) {
|
|
||||||
conn, err := pgx.Connect(
|
|
||||||
context.Background(),
|
|
||||||
"postgres://postgres:postgres@localhost:5432/muzi",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot connect to muzi database: %v\n", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close(context.Background())
|
|
||||||
|
|
||||||
var pageInt int
|
|
||||||
|
|
||||||
pageStr := r.URL.Query().Get("page")
|
|
||||||
if pageStr == "" {
|
|
||||||
pageInt = 1
|
|
||||||
} else {
|
|
||||||
pageInt, err = strconv.Atoi(pageStr)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Cannot convert page URL query from string to int: %v\n", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
lim := 25
|
|
||||||
off := 0 + (25 * (pageInt - 1))
|
|
||||||
|
|
||||||
data := PageData{
|
|
||||||
Content: getScrobbles(conn),
|
|
||||||
Artists: getArtists(conn, lim, off),
|
|
||||||
Titles: getTitles(conn, lim, off),
|
|
||||||
Times: getTimes(conn, lim, off),
|
|
||||||
Page: pageInt,
|
|
||||||
}
|
|
||||||
|
|
||||||
funcMap := template.FuncMap{
|
|
||||||
"Sub": Sub,
|
|
||||||
"Add": Add,
|
|
||||||
}
|
|
||||||
|
|
||||||
tmp, err := template.New("history.gohtml").
|
|
||||||
Funcs(funcMap).
|
|
||||||
ParseFiles("./templates/history.gohtml")
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = tmp.Execute(w, data)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func profilePageHandler() http.HandlerFunc {
|
func profilePageHandler() http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
username := chi.URLParam(r, "username")
|
username := chi.URLParam(r, "username")
|
||||||
@@ -325,21 +284,56 @@ func profilePageHandler() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
defer conn.Close(context.Background())
|
defer conn.Close(context.Background())
|
||||||
|
|
||||||
var profileData Profile
|
userId, err := getUserIdByUsername(conn, username)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Cannot find user %s: %v\n", username, err)
|
||||||
|
http.Error(w, "User not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pageStr := r.URL.Query().Get("page")
|
||||||
|
var pageInt int
|
||||||
|
if pageStr == "" {
|
||||||
|
pageInt = 1
|
||||||
|
} else {
|
||||||
|
pageInt, err = strconv.Atoi(pageStr)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Cannot convert page URL query from string to int: %v\n", err)
|
||||||
|
pageInt = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lim := 15
|
||||||
|
off := (pageInt - 1) * lim
|
||||||
|
|
||||||
|
var profileData ProfileData
|
||||||
|
|
||||||
err = conn.QueryRow(
|
err = conn.QueryRow(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
"SELECT bio, pfp FROM users WHERE username = $1;",
|
"SELECT bio, pfp, allow_duplicate_edits FROM users WHERE pk = $1;",
|
||||||
username,
|
userId,
|
||||||
).Scan(&profileData.Bio, &profileData.Pfp)
|
).Scan(&profileData.Bio, &profileData.Pfp, &profileData.AllowDuplicateEdits)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Cannot get profile for %s: %v\n", username, err)
|
fmt.Fprintf(os.Stderr, "Cannot get profile for %s: %v\n", username, err)
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
profileData.Username = username
|
profileData.Username = username
|
||||||
|
profileData.ScrobbleCount = getScrobbles(conn, userId)
|
||||||
|
profileData.ArtistCount = getArtistCount(conn, userId)
|
||||||
|
profileData.Artists = getArtists(conn, userId, lim, off)
|
||||||
|
profileData.Titles = getTitles(conn, userId, lim, off)
|
||||||
|
profileData.Times = getTimes(conn, userId, lim, off)
|
||||||
|
profileData.Page = pageInt
|
||||||
|
|
||||||
tmp, err := template.ParseFiles("./templates/profile.gohtml")
|
funcMap := template.FuncMap{
|
||||||
|
"Sub": Sub,
|
||||||
|
"Add": Add,
|
||||||
|
}
|
||||||
|
|
||||||
|
tmp, err := template.New("profile.gohtml").
|
||||||
|
Funcs(funcMap).
|
||||||
|
ParseFiles("./templates/profile.gohtml")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@@ -348,10 +342,33 @@ func profilePageHandler() http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Profile struct {
|
func updateDuplicateEditsSetting(w http.ResponseWriter, r *http.Request) {
|
||||||
Username string
|
conn, err := pgx.Connect(
|
||||||
Bio string
|
context.Background(),
|
||||||
Pfp string
|
"postgres://postgres:postgres@localhost:5432/muzi",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Cannot connect to muzi database: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close(context.Background())
|
||||||
|
|
||||||
|
if r.Method == "POST" {
|
||||||
|
r.ParseForm()
|
||||||
|
username := r.FormValue("username")
|
||||||
|
allow := r.FormValue("allow") == "true"
|
||||||
|
|
||||||
|
_, err = conn.Exec(
|
||||||
|
context.Background(),
|
||||||
|
`UPDATE users SET allow_duplicate_edits = $1 WHERE username = $2;`,
|
||||||
|
allow,
|
||||||
|
username,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error updating setting: %v\n", err)
|
||||||
|
}
|
||||||
|
http.Redirect(w, r, "/profile/"+username, http.StatusSeeOther)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Start() {
|
func Start() {
|
||||||
@@ -359,12 +376,12 @@ func Start() {
|
|||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
r.Use(middleware.Logger)
|
r.Use(middleware.Logger)
|
||||||
r.Handle("/files/*", http.StripPrefix("/files", http.FileServer(http.Dir("./static"))))
|
r.Handle("/files/*", http.StripPrefix("/files", http.FileServer(http.Dir("./static"))))
|
||||||
r.Get("/history", historyPage)
|
|
||||||
r.Get("/login", loginPageHandler())
|
r.Get("/login", loginPageHandler())
|
||||||
r.Get("/createaccount", createAccountPageHandler())
|
r.Get("/createaccount", createAccountPageHandler())
|
||||||
r.Get("/profile/{username}", profilePageHandler())
|
r.Get("/profile/{username}", profilePageHandler())
|
||||||
r.Post("/loginsubmit", loginSubmit)
|
r.Post("/loginsubmit", loginSubmit)
|
||||||
r.Post("/createaccountsubmit", createAccount)
|
r.Post("/createaccountsubmit", createAccount)
|
||||||
|
r.Post("/settings/duplicate-edits", updateDuplicateEditsSetting)
|
||||||
fmt.Printf("WebUI starting on %s\n", addr)
|
fmt.Printf("WebUI starting on %s\n", addr)
|
||||||
http.ListenAndServe(addr, r)
|
http.ListenAndServe(addr, r)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user