Compare commits

...

3 Commits

Author SHA1 Message Date
Glenn Thompson de70fbde5a refactor: Address PR review feedback for timestamp handling
- Rename format-timestamp-for-postgres to format-timestamp-iso8601 (database-agnostic)
- Reuse format-timestamp-iso8601 in authenticate-user instead of inline formatting
- Change listened_at field type from integer to timestamp for consistency
2025-12-29 09:39:51 -05:00
Glenn Thompson debf47c9c7 fix: Use correct table name user_listening_history in user-profile.lisp
- Update all references from listening_history to user_listening_history
- Use correct column names: user_id, listened_at, duration_seconds, track_artist
- Update database.lisp collection definition to match PostgreSQL schema
2025-12-29 09:39:51 -05:00
Glenn Thompson 4b49f63991 fix: Normalize USERS table timestamps before dm:save to prevent PostgreSQL type errors
- Add format-timestamp-for-postgres and normalize-user-timestamps functions in database.lisp
- data-model-save now normalizes timestamp fields for USERS table before saving
- Fix authenticate-user to use data-model-save instead of dm:save directly
- Add global auth state in auth-ui.lisp for other scripts to check login status
- Add auth checks in front-page.lisp and stream-player.lisp to skip API calls when not logged in
- Fix ParenScript parentheses structure in stream-player.lisp DOMContentLoaded handler

Fixes password reset, role update, and last-login update failures caused by
integer timestamps being sent to PostgreSQL TIMESTAMP columns.
2025-12-29 09:39:51 -05:00
6 changed files with 106 additions and 57 deletions

View File

@ -57,12 +57,12 @@
(rating :integer)
(created-date :integer))))
(unless (db:collection-exists-p "listening_history")
(db:create "listening_history" '((user-id :integer)
(track-id :integer)
(listened-at :integer)
(listen-duration :integer)
(completed :integer))))
(unless (db:collection-exists-p "user_listening_history")
(db:create "user_listening_history" '((user_id :integer)
(track_title :text)
(track_artist :text)
(listened_at :timestamp)
(duration_seconds :integer))))
(unless (db:collection-exists-p "user_playlists")
(db:create "user_playlists" '((user-id :integer)
@ -98,6 +98,37 @@
(string= (string-upcase (package-name (db:implementation)))
"I-LAMBDALITE"))
(defun format-timestamp-iso8601 (value)
"Convert a timestamp value to ISO 8601 format.
Handles: integers (Unix epoch), local-time timestamps, strings, and NIL."
(cond
((null value) nil)
((stringp value) value) ; Already a string, assume it's formatted
((integerp value)
;; Convert Unix epoch to ISO 8601 string
(local-time:format-timestring nil (local-time:unix-to-timestamp value)
:format '(:year "-" (:month 2) "-" (:day 2) " "
(:hour 2) ":" (:min 2) ":" (:sec 2))
:timezone local-time:+utc-zone+))
((typep value 'local-time:timestamp)
(local-time:format-timestring nil value
:format '(:year "-" (:month 2) "-" (:day 2) " "
(:hour 2) ":" (:min 2) ":" (:sec 2))
:timezone local-time:+utc-zone+))
(t (format nil "~a" value)))) ; Fallback: convert to string
(defun normalize-user-timestamps (data-model)
"Ensure USERS table timestamp fields are properly formatted for PostgreSQL."
(when (string-equal (dm:collection data-model) "USERS")
(let ((created-date (dm:field data-model "created-date"))
(last-login (dm:field data-model "last-login")))
(when created-date
(setf (dm:field data-model "created-date")
(format-timestamp-iso8601 created-date)))
(when last-login
(setf (dm:field data-model "last-login")
(format-timestamp-iso8601 last-login))))))
(defun data-model-save (data-model)
"Wrapper on data-model save method to bypass error using dm:save on lambdalite.
It uses the same approach as dm:save under the hood through db:save."
@ -109,4 +140,6 @@ It uses the same approach as dm:save under the hood through db:save."
(dm:field-table data-model)))
(progn
(format t "Updating database table '~a'~%" (dm:collection data-model))
;; Normalize timestamp fields before saving to PostgreSQL
(normalize-user-timestamps data-model)
(dm:save data-model))))

View File

@ -7,6 +7,9 @@
(ps:ps*
'(progn
;; Global auth state - accessible by other scripts
(defvar *auth-state* (ps:create :logged-in false :is-admin false :user-id nil))
;; Check if user is logged in by calling the API
(defun check-auth-status ()
(ps:chain
@ -16,6 +19,8 @@
(then (lambda (result)
;; api-output wraps response in {status, message, data}
(let ((data (or (ps:@ result data) result)))
;; Store auth state globally for other scripts to use
(setf *auth-state* data)
data)))
(catch (lambda (error)
(ps:chain console (error "Error checking auth status:" error))

View File

@ -171,14 +171,17 @@
;; Cache of user's favorite track titles for quick lookup
(defvar *user-favorites-cache* (array))
;; Load user's favorites into cache
;; Load user's favorites into cache (only if logged in)
(defun load-favorites-cache ()
(ps:chain
(fetch "/api/asteroid/user/favorites")
(then (lambda (response)
(if (ps:@ response ok)
(ps:chain response (json))
nil)))
;; Check global auth state - only call API if logged in
(when (and (not (= (typeof *auth-state*) "undefined"))
(ps:@ *auth-state* logged-in))
(ps:chain
(fetch "/api/asteroid/user/favorites")
(then (lambda (response)
(if (ps:@ response ok)
(ps:chain response (json))
nil)))
(then (lambda (data)
(when (and data (ps:@ data data) (ps:@ data data favorites))
(setf *user-favorites-cache*
@ -186,7 +189,7 @@
(map (lambda (f) (ps:@ f title)))))
;; Update UI after cache is loaded
(check-favorite-status))))
(catch (lambda (error) nil))))
(catch (lambda (error) nil)))))
;; Check if current track is in favorites and update UI
(defun check-favorite-status ()
@ -205,7 +208,10 @@
;; Record track to listening history (only if logged in)
(defun record-track-listen-main (title)
(when (and title (not (= title "")) (not (= title "Loading..."))
;; Check global auth state - only call API if logged in
(when (and (not (= (typeof *auth-state*) "undefined"))
(ps:@ *auth-state* logged-in)
title (not (= title "")) (not (= title "Loading..."))
(not (= title "NA")) (not (= title *last-recorded-title-main*)))
(setf *last-recorded-title-main* title)
(ps:chain
@ -214,7 +220,7 @@
(then (lambda (response)
(ps:@ response ok)))
(catch (lambda (error)
;; Silently fail - user might not be logged in
;; Silently fail
nil)))))
;; Update now playing info from API

View File

@ -204,14 +204,17 @@
;; Cache of user's favorite track titles for quick lookup (mini player)
(defvar *user-favorites-cache-mini* (array))
;; Load user's favorites into cache (mini player)
;; Load user's favorites into cache (mini player - only if logged in)
(defun load-favorites-cache-mini ()
(ps:chain
(fetch "/api/asteroid/user/favorites" (ps:create :credentials "include"))
(then (lambda (response)
(if (ps:@ response ok)
(ps:chain response (json))
nil)))
;; Check global auth state - only call API if logged in
(when (and (not (= (typeof *auth-state*) "undefined"))
(ps:@ *auth-state* logged-in))
(ps:chain
(fetch "/api/asteroid/user/favorites" (ps:create :credentials "include"))
(then (lambda (response)
(if (ps:@ response ok)
(ps:chain response (json))
nil)))
(then (lambda (data)
(when data
;; Handle both wrapped (data.data.favorites) and unwrapped (data.favorites) responses
@ -222,7 +225,7 @@
(ps:chain favorites (map (lambda (f) (ps:@ f title)))))
;; Update UI after cache is loaded
(check-favorite-status-mini))))))
(catch (lambda (error) nil))))
(catch (lambda (error) nil)))))
;; Check if current track is in favorites and update mini player UI
(defun check-favorite-status-mini ()
@ -242,7 +245,10 @@
;; Record track to listening history (only if logged in)
(defun record-track-listen (title)
(when (and title (not (= title "")) (not (= title "Loading...")) (not (= title *last-recorded-title*)))
;; Check global auth state - only call API if logged in
(when (and (not (= (typeof *auth-state*) "undefined"))
(ps:@ *auth-state* logged-in)
title (not (= title "")) (not (= title "Loading...")) (not (= title *last-recorded-title*)))
(setf *last-recorded-title* title)
(ps:chain
(fetch (+ "/api/asteroid/user/history/record?title=" (encode-u-r-i-component title))
@ -784,13 +790,14 @@
(init-persistent-player))
;; Check for popout player
(when (ps:chain document (get-element-by-id "live-audio"))
(init-popout-player))))
;; Listen for messages from parent frame (e.g., favorites cache reload)
(ps:chain window (add-event-listener
"message"
(lambda (event)
(when (= (ps:@ event data) "reload-favorites")
(load-favorites-cache-mini)))))))
(init-popout-player)))))
;; Listen for messages from parent frame (e.g., favorites cache reload)
(ps:chain window (add-event-listener
"message"
(lambda (event)
(when (= (ps:@ event data) "reload-favorites")
(load-favorites-cache-mini))))))
)
"Compiled JavaScript for stream player - generated at load time")

View File

@ -70,15 +70,12 @@
(when (and (= 1 user-active)
(verify-password password user-password))
;; Update last login using data-model (database agnostic)
;; Use ISO 8601 format in UTC that PostgreSQL TIMESTAMP can parse
(handler-case
(progn
(setf (dm:field user "last-login")
(local-time:format-timestring nil (local-time:now)
:format '(:year "-" (:month 2) "-" (:day 2) " "
(:hour 2) ":" (:min 2) ":" (:sec 2))
:timezone local-time:+utc-zone+))
(dm:save user))
(format-timestamp-iso8601 (local-time:now)))
;; Use data-model-save to normalize all timestamp fields before saving
(data-model-save user))
(error (e)
(format t "Warning: Could not update last-login: ~a~%" e)))
user)))))

View File

@ -94,14 +94,14 @@
(when (and user-id track-title)
;; Get recent listens and check timestamps manually since data-model
;; doesn't support interval comparisons directly
(let ((recent (dm:get "listening_history"
(db:query (:and (:= 'user-id user-id)
(let ((recent (dm:get "user_listening_history"
(db:query (:and (:= 'user_id user-id)
(:= 'track_title track-title)))
:amount 1
:sort '(("listened-at" :DESC)))))
:sort '(("listened_at" :DESC)))))
(when recent
(let* ((listen (first recent))
(listened-at (dm:field listen "listened-at")))
(listened-at (dm:field listen "listened_at")))
;; Check if within 60 seconds (listened-at is a timestamp)
(when listened-at
(let ((now (get-universal-time))
@ -116,12 +116,13 @@
(when (and user-id (or track-id track-title))
;; Check for recent duplicate
(unless (get-recent-listen user-id track-title)
(let ((listen (dm:hull "listening_history")))
(setf (dm:field listen "user-id") user-id)
(setf (dm:field listen "listen-duration") (or duration 0))
(setf (dm:field listen "completed") (if completed 1 0))
(when track-id
(setf (dm:field listen "track-id") track-id))
(let ((listen (dm:hull "user_listening_history")))
(setf (dm:field listen "user_id") user-id)
(setf (dm:field listen "duration_seconds") (or duration 0))
(when track-title
(let ((pos (search " - " track-title)))
(when pos
(setf (dm:field listen "track_artist") (subseq track-title 0 pos)))))
(when track-title
(setf (dm:field listen "track_title") track-title))
(dm:insert listen)))))
@ -129,26 +130,26 @@
(defun get-listening-history (user-id &key (limit 20) (offset 0))
"Get user's listening history - works with title-based history"
(when user-id
(dm:get "listening_history" (db:query (:= 'user-id user-id))
(dm:get "user_listening_history" (db:query (:= 'user_id user-id))
:amount limit
:skip offset
:sort '(("listened-at" :DESC)))))
:sort '(("listened_at" :DESC)))))
(defun get-listening-stats (user-id)
"Get aggregate listening statistics for a user"
(when user-id
(let* ((history (dm:get "listening_history" (db:query (:= 'user-id user-id))))
(let* ((history (dm:get "user_listening_history" (db:query (:= 'user_id user-id))))
(tracks-played (length history))
(total-listen-time (reduce #'+ history
:key (lambda (h) (or (dm:field h "listen-duration") 0))
:key (lambda (h) (or (dm:field h "duration_seconds") 0))
:initial-value 0)))
(list :tracks-played tracks-played
:total-listen-time total-listen-time))))
(defun get-top-artists (user-id &key (limit 5))
"Get user's most listened artists - extracts artist from track_title"
"Get user's most listened artists - extracts artist from track_title or uses track_artist"
(when user-id
(let* ((history (dm:get "listening_history" (db:query (:= 'user-id user-id))))
(let* ((history (dm:get "user_listening_history" (db:query (:= 'user_id user-id))))
(artist-counts (make-hash-table :test 'equal)))
;; Count plays per artist
(dolist (h history)
@ -168,19 +169,19 @@
(defun clear-listening-history (user-id)
"Clear all listening history for a user"
(when user-id
(let ((history (dm:get "listening_history" (db:query (:= 'user-id user-id)))))
(let ((history (dm:get "user_listening_history" (db:query (:= 'user_id user-id)))))
(dolist (entry history)
(dm:delete entry)))))
(defun get-listening-activity (user-id &key (days 30))
"Get listening activity aggregated by day for the last N days"
(when user-id
(let* ((history (dm:get "listening_history" (db:query (:= 'user-id user-id))))
(let* ((history (dm:get "user_listening_history" (db:query (:= 'user_id user-id))))
(cutoff-time (- (get-universal-time) (* days 24 60 60)))
(day-counts (make-hash-table :test 'equal)))
;; Filter to recent days and count per day
(dolist (h history)
(let ((listened-at (dm:field h "listened-at")))
(let ((listened-at (dm:field h "listened_at")))
(when (and listened-at (> listened-at cutoff-time))
;; Convert universal time to date string
(multiple-value-bind (sec min hour day month year)