mirror of
https://github.com/riwiwa/muzi.git
synced 2026-03-04 00:51:59 -08:00
add manual scrobbling
This commit is contained in:
4
static/assets/icons/add.svg
Normal file
4
static/assets/icons/add.svg
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<line x1="12" y1="5" x2="12" y2="19"></line>
|
||||||
|
<line x1="5" y1="12" x2="19" y2="12"></line>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 259 B |
@@ -45,6 +45,10 @@
|
|||||||
<img src="/files/assets/icons/settings.svg" class="menu-icon" alt="Settings">
|
<img src="/files/assets/icons/settings.svg" class="menu-icon" alt="Settings">
|
||||||
<span>Settings</span>
|
<span>Settings</span>
|
||||||
</a>
|
</a>
|
||||||
|
<a href="/scrobble" class="menu-item">
|
||||||
|
<img src="/files/assets/icons/add.svg" class="menu-icon" alt="Scrobble">
|
||||||
|
<span>Manual Scrobble</span>
|
||||||
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -57,6 +61,7 @@
|
|||||||
{{ if eq .TemplateName "artist"}}{{block "artist" .}}{{end}}{{end}}
|
{{ if eq .TemplateName "artist"}}{{block "artist" .}}{{end}}{{end}}
|
||||||
{{ if eq .TemplateName "song"}}{{block "song" .}}{{end}}{{end}}
|
{{ if eq .TemplateName "song"}}{{block "song" .}}{{end}}{{end}}
|
||||||
{{ if eq .TemplateName "album"}}{{block "album" .}}{{end}}{{end}}
|
{{ if eq .TemplateName "album"}}{{block "album" .}}{{end}}{{end}}
|
||||||
|
{{ if eq .TemplateName "scrobble"}}{{block "scrobble" .}}{{end}}{{end}}
|
||||||
|
|
||||||
<script src="/files/menu.js"></script>
|
<script src="/files/menu.js"></script>
|
||||||
{{if eq .TemplateName "profile"}}
|
{{if eq .TemplateName "profile"}}
|
||||||
|
|||||||
148
templates/scrobble.gohtml
Normal file
148
templates/scrobble.gohtml
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
{{define "scrobble"}}
|
||||||
|
<div class="scrobble-container">
|
||||||
|
<h1>Manual Scrobble</h1>
|
||||||
|
<p>Manually add listening history entries.</p>
|
||||||
|
|
||||||
|
<div id="message" class="message" style="display: none;"></div>
|
||||||
|
|
||||||
|
<form id="scrobble-form">
|
||||||
|
<div id="rows-container">
|
||||||
|
<div class="scrobble-row">
|
||||||
|
<input type="text" name="song_name" placeholder="Song Name" required>
|
||||||
|
<input type="text" name="artist" placeholder="Artist" required>
|
||||||
|
<input type="text" name="album_name" placeholder="Album (optional)">
|
||||||
|
<input type="date" name="date" required>
|
||||||
|
<input type="time" name="time" required step="1">
|
||||||
|
<input type="number" name="duration" placeholder="Duration (sec)" min="0">
|
||||||
|
<button type="button" class="remove-row" style="display: none;">×</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="scrobble-actions">
|
||||||
|
<button type="button" id="add-row">+ Add Row</button>
|
||||||
|
<button type="submit">Submit All</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const now = new Date();
|
||||||
|
const dateStr = now.toISOString().split('T')[0];
|
||||||
|
const timeStr = now.toTimeString().split(' ')[0];
|
||||||
|
|
||||||
|
document.querySelectorAll('.scrobble-row').forEach(row => {
|
||||||
|
row.querySelector('input[name="date"]').value = dateStr;
|
||||||
|
row.querySelector('input[name="time"]').value = timeStr;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('add-row').addEventListener('click', () => {
|
||||||
|
const container = document.getElementById('rows-container');
|
||||||
|
const newRow = document.createElement('div');
|
||||||
|
newRow.className = 'scrobble-row';
|
||||||
|
newRow.innerHTML = `
|
||||||
|
<input type="text" name="song_name" placeholder="Song Name" required>
|
||||||
|
<input type="text" name="artist" placeholder="Artist" required>
|
||||||
|
<input type="text" name="album_name" placeholder="Album (optional)">
|
||||||
|
<input type="date" name="date" required value="${dateStr}">
|
||||||
|
<input type="time" name="time" required step="1" value="${timeStr}">
|
||||||
|
<input type="number" name="duration" placeholder="Duration (sec)" min="0">
|
||||||
|
<button type="button" class="remove-row">×</button>
|
||||||
|
`;
|
||||||
|
container.appendChild(newRow);
|
||||||
|
updateRemoveButtons();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('rows-container').addEventListener('click', (e) => {
|
||||||
|
if (e.target.classList.contains('remove-row')) {
|
||||||
|
e.target.closest('.scrobble-row').remove();
|
||||||
|
updateRemoveButtons();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function updateRemoveButtons() {
|
||||||
|
const rows = document.querySelectorAll('.scrobble-row');
|
||||||
|
const buttons = document.querySelectorAll('.remove-row');
|
||||||
|
buttons.forEach(btn => {
|
||||||
|
btn.style.display = rows.length > 1 ? 'block' : 'none';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('scrobble-form').addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const rows = document.querySelectorAll('.scrobble-row');
|
||||||
|
const tracks = [];
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const songName = row.querySelector('input[name="song_name"]').value.trim();
|
||||||
|
const artist = row.querySelector('input[name="artist"]').value.trim();
|
||||||
|
const albumName = row.querySelector('input[name="album_name"]').value.trim();
|
||||||
|
const date = row.querySelector('input[name="date"]').value;
|
||||||
|
const time = row.querySelector('input[name="time"]').value;
|
||||||
|
const duration = row.querySelector('input[name="duration"]').value;
|
||||||
|
|
||||||
|
if (!songName || !artist || !date || !time) continue;
|
||||||
|
|
||||||
|
const timestamp = new Date(`${date}T${time}`).toISOString();
|
||||||
|
const msPlayed = duration ? parseInt(duration) * 1000 : 0;
|
||||||
|
|
||||||
|
tracks.push({
|
||||||
|
song_name: songName,
|
||||||
|
artist: artist,
|
||||||
|
album_name: albumName,
|
||||||
|
timestamp: timestamp,
|
||||||
|
ms_played: msPlayed
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tracks.length === 0) {
|
||||||
|
showMessage('Please fill in at least one complete row.', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/scrobble', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ tracks })
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
showMessage(`Successfully scrobbled ${result.count} track(s)!`, 'success');
|
||||||
|
resetForm();
|
||||||
|
} else {
|
||||||
|
showMessage(result.error || 'Failed to scrobble tracks.', 'error');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showMessage('An error occurred. Please try again.', 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function showMessage(text, type) {
|
||||||
|
const msg = document.getElementById('message');
|
||||||
|
msg.textContent = text;
|
||||||
|
msg.className = 'message ' + type;
|
||||||
|
msg.style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetForm() {
|
||||||
|
const container = document.getElementById('rows-container');
|
||||||
|
container.innerHTML = `
|
||||||
|
<div class="scrobble-row">
|
||||||
|
<input type="text" name="song_name" placeholder="Song Name" required>
|
||||||
|
<input type="text" name="artist" placeholder="Artist" required>
|
||||||
|
<input type="text" name="album_name" placeholder="Album (optional)">
|
||||||
|
<input type="date" name="date" required value="${dateStr}">
|
||||||
|
<input type="time" name="time" required step="1" value="${timeStr}">
|
||||||
|
<input type="number" name="duration" placeholder="Duration (sec)" min="0">
|
||||||
|
<button type="button" class="remove-row" style="display: none;">×</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
updateRemoveButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
updateRemoveButtons();
|
||||||
|
</script>
|
||||||
|
{{end}}
|
||||||
183
web/scrobble.go
Normal file
183
web/scrobble.go
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"muzi/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ScrobbleTrack struct {
|
||||||
|
SongName string `json:"song_name"`
|
||||||
|
Artist string `json:"artist"`
|
||||||
|
AlbumName string `json:"album_name"`
|
||||||
|
Timestamp string `json:"timestamp"`
|
||||||
|
MsPlayed int `json:"ms_played"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScrobbleRequest struct {
|
||||||
|
Tracks []ScrobbleTrack `json:"tracks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type scrobbleData struct {
|
||||||
|
Title string
|
||||||
|
LoggedInUsername string
|
||||||
|
TemplateName string
|
||||||
|
}
|
||||||
|
|
||||||
|
func scrobblePageHandler() http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
username := getLoggedInUsername(r)
|
||||||
|
if username == "" {
|
||||||
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
data := scrobbleData{
|
||||||
|
Title: "muzi | Manual Scrobble",
|
||||||
|
LoggedInUsername: username,
|
||||||
|
TemplateName: "scrobble",
|
||||||
|
}
|
||||||
|
|
||||||
|
err := templates.ExecuteTemplate(w, "base", data)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func scrobbleSubmitHandler() http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
username := getLoggedInUsername(r)
|
||||||
|
if username == "" {
|
||||||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Method != "POST" {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userId, err := getUserIdByUsername(r.Context(), 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
|
||||||
|
}
|
||||||
|
|
||||||
|
var req ScrobbleRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(req.Tracks) == 0 {
|
||||||
|
http.Error(w, "No tracks provided", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
count, err := insertScrobbles(r.Context(), userId, req.Tracks)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error inserting scrobbles: %v\n", err)
|
||||||
|
http.Error(w, fmt.Sprintf("Error inserting scrobbles: %v", err), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"count": count,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func insertScrobbles(ctx context.Context, userId int, tracks []ScrobbleTrack) (int, error) {
|
||||||
|
artistIdMap := make(map[string][]int)
|
||||||
|
|
||||||
|
for _, track := range tracks {
|
||||||
|
if track.Artist == "" || track.SongName == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
artistNames := parseArtistString(track.Artist)
|
||||||
|
var artistIds []int
|
||||||
|
for _, name := range artistNames {
|
||||||
|
artistId, _, err := db.GetOrCreateArtist(userId, name)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error creating artist %s: %v\n", name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
artistIds = append(artistIds, artistId)
|
||||||
|
}
|
||||||
|
artistIdMap[track.Artist+"|"+track.SongName] = artistIds
|
||||||
|
}
|
||||||
|
|
||||||
|
imported := 0
|
||||||
|
for _, track := range tracks {
|
||||||
|
if track.Artist == "" || track.SongName == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
timestamp, err := time.Parse(time.RFC3339, track.Timestamp)
|
||||||
|
if err != nil {
|
||||||
|
timestamp = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
artistIds := artistIdMap[track.Artist+"|"+track.SongName]
|
||||||
|
var artistId int
|
||||||
|
if len(artistIds) > 0 {
|
||||||
|
artistId = artistIds[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
var albumId int
|
||||||
|
if track.AlbumName != "" && artistId > 0 {
|
||||||
|
albumId, _, _ = db.GetOrCreateAlbum(userId, track.AlbumName, artistId)
|
||||||
|
}
|
||||||
|
|
||||||
|
var songId int
|
||||||
|
if track.SongName != "" && artistId > 0 {
|
||||||
|
songId, _, _ = db.GetOrCreateSong(userId, track.SongName, artistId, albumId)
|
||||||
|
}
|
||||||
|
|
||||||
|
var albumNamePg *string
|
||||||
|
if track.AlbumName != "" {
|
||||||
|
albumNamePg = &track.AlbumName
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = db.Pool.Exec(ctx,
|
||||||
|
`INSERT INTO history (user_id, timestamp, song_name, artist, album_name, ms_played, platform, artist_id, song_id, artist_ids)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
|
ON CONFLICT (user_id, song_name, artist, timestamp) DO NOTHING`,
|
||||||
|
userId, timestamp, track.SongName, track.Artist, albumNamePg, track.MsPlayed, "manual", artistId, songId, artistIds,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
if !strings.Contains(err.Error(), "duplicate") {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error inserting scrobble: %v\n", err)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
imported++
|
||||||
|
}
|
||||||
|
|
||||||
|
return imported, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseArtistString(artist string) []string {
|
||||||
|
if artist == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var artists []string
|
||||||
|
for _, a := range strings.Split(artist, ",") {
|
||||||
|
a = strings.TrimSpace(a)
|
||||||
|
if a != "" {
|
||||||
|
artists = append(artists, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return artists
|
||||||
|
}
|
||||||
@@ -129,6 +129,8 @@ func Start() {
|
|||||||
r.Post("/import/spotify", importSpotifyHandler)
|
r.Post("/import/spotify", importSpotifyHandler)
|
||||||
r.Get("/import/lastfm/progress", importLastFMProgressHandler)
|
r.Get("/import/lastfm/progress", importLastFMProgressHandler)
|
||||||
r.Get("/import/spotify/progress", importSpotifyProgressHandler)
|
r.Get("/import/spotify/progress", importSpotifyProgressHandler)
|
||||||
|
r.Get("/scrobble", scrobblePageHandler())
|
||||||
|
r.Post("/scrobble", scrobbleSubmitHandler())
|
||||||
|
|
||||||
r.Handle("/2.0", scrobble.NewLastFMHandler())
|
r.Handle("/2.0", scrobble.NewLastFMHandler())
|
||||||
r.Handle("/2.0/", scrobble.NewLastFMHandler())
|
r.Handle("/2.0/", scrobble.NewLastFMHandler())
|
||||||
|
|||||||
Reference in New Issue
Block a user