self-hosted listenbrainz and last.fm proxy
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943module State exposing (Query, buildQuery, init, landingTab, parsePage, parsePageParam, parseQuery, parseTabParam, similarKey, subscriptions, update, userPath)
import Api exposing (approveRegistration, denyRegistration, fetchListens, fetchRegistrations, fetchSectionData, fetchSimilarTracks, fetchStats, fetchUsers, httpErrorToString, removeUser, submitRegistration)import Browserimport Browser.Eventsimport Browser.Navigation as Navimport Dictimport Json.Decode as Dimport Portsimport Setimport Taskimport Timeimport Types exposing (Flags, Model, Msg(..), Page(..), Period(..), RegField(..), SimilarState(..), Stats, StatsEntry, Tab(..))import Url
init : Flags -> Url.Url -> Nav.Key -> ( Model, Cmd Msg )init flags url navKey = let q = parseQuery url
offset = max 0 ((q.page - 1) * 25)
page = parsePage url
initialFilter = case q.filterField of Just field -> Maybe.map (\value -> { field = field, value = value }) q.filterValue
Nothing -> Nothing in ( { navKey = navKey , listens = [] , stats = Nothing , error = Nothing , hasMoreListens = False , loading = True , currentTime = Nothing , failedCovers = Set.empty , hoveredCover = Nothing , expandedSections = Set.empty , loadedSections = Set.empty , offset = offset , limit = 25 , activeTab = q.tab , activeFilter = initialFilter , statsPeriod = AllTime , customInput = "" , showCustomInput = False , customError = Nothing , userSlug = flags.userSlug , similarStates = Dict.empty , allUsers = flags.allUsers , searchInput = Maybe.withDefault "" q.search , activeSearch = q.search , page = page , visibility = Browser.Events.Visible , registrationEnabled = flags.registrationEnabled , regSlug = "" , regName = "" , regEmail = "" , regLbUser = "" , regLfUser = "" , regSubmitting = False , regSubmitted = False , regError = Nothing , adminToken = flags.adminToken , adminTokenInput = flags.adminToken , registrations = [] , users = [] , confirmingRemoval = Nothing , adminError = Nothing , approvedToken = Nothing } , case page of AdminPage -> Cmd.batch [ Task.perform GotTime Time.now , if String.isEmpty flags.adminToken then Cmd.none
else Cmd.batch [ fetchRegistrations flags.adminToken, fetchUsers flags.adminToken ] ]
RegisterPage -> Task.perform GotTime Time.now
MainPage -> Cmd.batch ([ fetchListens flags.userSlug 25 offset initialFilter q.search , Task.perform GotTime Time.now ] ++ (if q.tab == StatsTab then [ fetchStats flags.userSlug AllTime ]
else [] ) ) )
parsePage : Url.Url -> PageparsePage url = case url.path of "/register" -> RegisterPage
"/admin" -> AdminPage
_ -> MainPage
{-| Pick the tab to show after a URL change lands on the main page.Arriving from another page keeps the tab the user chose; navigating withinthe main page resets to listens.-}landingTab : Page -> Tab -> TablandingTab fromPage currentTab = if fromPage == MainPage then ListensTab
else currentTab
userPath : String -> StringuserPath slug = if String.isEmpty slug then "/"
else "/u/" ++ slug
fetchTabData : Model -> Cmd MsgfetchTabData model = case model.activeTab of StatsTab -> if model.stats == Nothing then fetchStats model.userSlug model.statsPeriod
else Cmd.none
ListensTab -> Cmd.none
AboutTab -> Cmd.none
parsePageParam : Url.Url -> IntparsePageParam url = queryParam url "page" |> Maybe.andThen String.toInt |> Maybe.withDefault 1 |> max 1
{-| The list view state carried in the URL, so reload, back and link sharingrestore the same view.-}type alias Query = { page : Int , filterField : Maybe String , filterValue : Maybe String , search : Maybe String , tab : Tab }
-- | Parse the page, filter, search and tab out of a URL.parseQuery : Url.Url -> QueryparseQuery url = let mField = queryParam url "filterField"
mValue = queryParam url "filterValue" in { page = parsePageParam url , filterField = mField , filterValue = mValue , search = queryParam url "search" , tab = parseTabParam url }
-- | Parse the tab, defaulting to the listens tab.parseTabParam : Url.Url -> TabparseTabParam url = case queryParam url "tab" of Just "stats" -> StatsTab
Just "about" -> AboutTab
_ -> ListensTab
-- | Read one decoded query parameter. Works for any path shape, unlike a-- | `Url.Parser` query parser, which only runs on the route it is attached to.queryParam : Url.Url -> String -> Maybe StringqueryParam url name = parseQueryParams (Maybe.withDefault "" url.query) |> List.filterMap (\( key, value ) -> if key == name && not (String.isEmpty value) then Just value
else Nothing ) |> List.head
-- | Split a raw query string into percent-decoded key/value pairs.parseQueryParams : String -> List ( String, String )parseQueryParams raw = raw |> String.split "&" |> List.filter (not << String.isEmpty) |> List.map (\pair -> let parts = String.split "=" pair
decode = Url.percentDecode >> Maybe.withDefault "" in ( parts |> List.head |> Maybe.withDefault "" |> decode , parts |> List.drop 1 |> String.join "=" |> decode ) )
-- | The query implied by the model's current view state.currentQuery : Model -> Int -> QuerycurrentQuery model page = { page = page , filterField = Maybe.map .field model.activeFilter , filterValue = Maybe.map .value model.activeFilter , search = model.activeSearch , tab = model.activeTab }
-- | Whether the URL names a tab explicitly. A missing tab means "keep what-- | the user chose" (see landingTab), which is not the same as "listens".hasTabParam : Url.Url -> BoolhasTabParam url = queryParam url "tab" /= Nothing
-- | Build a URL path plus query for the given view state.buildQuery : String -> Query -> StringbuildQuery slug q = let params = List.filterMap identity [ Just ("page", String.fromInt q.page) , Maybe.map (\f -> ( "filterField", f )) q.filterField , Maybe.map (\v -> ( "filterValue", v )) q.filterValue , Maybe.map (\s -> ( "search", s )) q.search , Just ( "tab" , case q.tab of ListensTab -> "listens"
StatsTab -> "stats"
AboutTab -> "about" ) ]
encoded = String.join "&" (List.map (\( k, v ) -> k ++ "=" ++ Url.percentEncode v) params) in userPath slug ++ "?" ++ encoded
-- MSG
update : Msg -> Model -> ( Model, Cmd Msg )update msg model = case msg of UrlRequested urlRequest -> case urlRequest of Browser.Internal url -> if String.isEmpty url.path then ( model, Cmd.none )
else ( model, Nav.pushUrl model.navKey (Url.toString url) )
Browser.External href -> ( model, Nav.load href )
UrlChanged url -> case parsePage url of RegisterPage -> ( { model | page = RegisterPage }, Cmd.none )
AdminPage -> ( { model | page = AdminPage, approvedToken = Nothing, confirmingRemoval = Nothing } , if String.isEmpty model.adminToken then Cmd.none
else Cmd.batch [ fetchRegistrations model.adminToken, fetchUsers model.adminToken ] )
MainPage -> let newUserSlug = if String.startsWith "/u/" url.path then String.dropLeft 3 url.path
else ""
q = parseQuery url
targetOffset = max 0 ((q.page - 1) * model.limit)
-- The URL is the source of truth: a bare path means no -- filter and no search. targetFilter = case q.filterField of Just field -> Maybe.map (\value -> { field = field, value = value }) q.filterValue
Nothing -> Nothing
targetSearch = q.search
targetTab = if hasTabParam url then q.tab
else landingTab model.page model.activeTab
userChanged = newUserSlug /= model.userSlug
shouldLoad = model.page /= MainPage || userChanged || model.offset /= targetOffset || model.activeFilter /= targetFilter || model.activeSearch /= targetSearch || model.activeTab /= targetTab in if shouldLoad then let newModel = { model | userSlug = newUserSlug , offset = targetOffset , activeFilter = targetFilter , activeSearch = targetSearch , searchInput = Maybe.withDefault "" targetSearch , activeTab = targetTab , loading = True , page = MainPage }
clearedModel = if userChanged then { newModel | stats = Nothing , expandedSections = Set.empty , loadedSections = Set.empty , similarStates = Dict.empty }
else newModel in ( clearedModel , Cmd.batch [ fetchListens newUserSlug model.limit targetOffset targetFilter targetSearch , fetchTabData clearedModel ] )
else ( { model | page = MainPage }, Cmd.none )
Tick time -> if model.page == MainPage && model.activeTab == ListensTab && model.visibility == Browser.Events.Visible && not model.loading then ( { model | currentTime = Just time, loading = True } , fetchListens model.userSlug model.limit model.offset model.activeFilter model.activeSearch )
else ( { model | currentTime = Just time }, Cmd.none )
VisibilityChanged vis -> ( { model | visibility = vis }, Cmd.none )
GotTime time -> ( { model | currentTime = Just time }, Cmd.none )
GotListens result -> let newModel = case result of Err err -> { model | loading = False, error = Just (httpErrorToString err) }
Ok page -> { model | loading = False, listens = page.listens, hasMoreListens = page.hasMore, error = Nothing } in ( newModel, Task.perform GotTime Time.now )
GotStats result -> case result of Err err -> ( { model | error = Just (httpErrorToString err) }, Cmd.none )
Ok stats -> ( { model | stats = Just stats, error = Nothing }, Cmd.none )
GotSectionData section result -> case result of Err err -> ( { model | error = Just (httpErrorToString err) }, Cmd.none )
Ok entries -> ( { model | expandedSections = Set.insert section model.expandedSections , loadedSections = Set.insert section model.loadedSections , stats = Maybe.map (patchStatSection section entries) model.stats , error = Nothing } , Cmd.none )
ImageError url -> ( { model | failedCovers = Set.insert url model.failedCovers }, Cmd.none )
NextPage -> let newOffset = model.offset + model.limit
page = newOffset // model.limit + 1 in ( { model | offset = newOffset, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit newOffset model.activeFilter model.activeSearch , Nav.pushUrl model.navKey (buildQuery model.userSlug (currentQuery model page)) ] )
PrevPage -> let newOffset = max 0 (model.offset - model.limit)
page = newOffset // model.limit + 1 in ( { model | offset = newOffset, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit newOffset model.activeFilter model.activeSearch , Nav.pushUrl model.navKey (buildQuery model.userSlug (currentQuery model page)) ] )
SwitchTab tab -> let newModel = { model | activeTab = tab } in if model.page == MainPage then ( newModel , Cmd.batch [ fetchTabData newModel , Nav.pushUrl model.navKey (buildQuery model.userSlug { filterField = Maybe.map .field model.activeFilter , filterValue = Maybe.map .value model.activeFilter , search = model.activeSearch , tab = tab , page = model.offset // model.limit + 1 } ) ] )
else -- Leaving /register or /admin: return to the current user's -- page. UrlChanged keeps the chosen tab and loads the listens. ( newModel, Nav.pushUrl model.navKey (userPath model.userSlug) )
SetStatsPeriod period -> ( { model | statsPeriod = period , stats = Nothing , expandedSections = Set.empty , loadedSections = Set.empty , showCustomInput = False } , fetchStats model.userSlug period )
OpenCustomInput -> let prefill = case model.statsPeriod of CustomRange from to -> from ++ " " ++ to
_ -> model.customInput in ( { model | showCustomInput = True, customInput = prefill, customError = Nothing } , Cmd.none )
UpdateCustomInput str -> ( { model | customInput = str, customError = Nothing }, Cmd.none )
ApplyCustomPeriod -> let parts = model.customInput |> String.split " " |> List.filter (not << String.isEmpty) in case parts of [ from, to ] -> if String.length from /= 10 || String.length to /= 10 then ( { model | customError = Just "Dates must be in YYYY-MM-DD format" }, Cmd.none )
else if from > to then ( { model | customError = Just "'from' must be before 'to'" }, Cmd.none )
else let period = CustomRange from to in ( { model | statsPeriod = period , stats = Nothing , expandedSections = Set.empty , loadedSections = Set.empty , showCustomInput = False , customError = Nothing } , fetchStats model.userSlug period )
_ -> ( { model | customError = Just "Enter two dates separated by a space" }, Cmd.none )
FilterBy field value -> let filter = Just { field = field, value = value }
page = 1 in ( { model | activeFilter = filter, activeSearch = Nothing, searchInput = "", offset = 0, activeTab = ListensTab, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit 0 filter Nothing , Nav.pushUrl model.navKey (buildQuery model.userSlug { page = page , filterField = Just field , filterValue = Just value , search = Nothing , tab = ListensTab } ) ] )
ClearFilter -> ( { model | activeFilter = Nothing, offset = 0, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit 0 Nothing model.activeSearch , Nav.pushUrl model.navKey (buildQuery model.userSlug { page = 1 , filterField = Nothing , filterValue = Nothing , search = model.activeSearch , tab = model.activeTab } ) ] )
UpdateSearchInput str -> ( { model | searchInput = str }, Cmd.none )
SubmitSearch -> let q = String.trim model.searchInput in if String.isEmpty q then ( { model | activeSearch = Nothing, offset = 0, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit 0 model.activeFilter Nothing , Nav.pushUrl model.navKey (buildQuery model.userSlug { page = 1 , filterField = Maybe.map .field model.activeFilter , filterValue = Maybe.map .value model.activeFilter , search = Nothing , tab = model.activeTab } ) ] )
else ( { model | activeSearch = Just q, activeFilter = Nothing, offset = 0, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit 0 Nothing (Just q) , Nav.pushUrl model.navKey (buildQuery model.userSlug { page = 1 , filterField = Nothing , filterValue = Nothing , search = Just q , tab = model.activeTab } ) ] )
ClearSearch -> ( { model | searchInput = "", activeSearch = Nothing, offset = 0, loading = True } , Cmd.batch [ fetchListens model.userSlug model.limit 0 model.activeFilter Nothing , Nav.pushUrl model.navKey (buildQuery model.userSlug { page = 1 , filterField = Maybe.map .field model.activeFilter , filterValue = Maybe.map .value model.activeFilter , search = Nothing , tab = model.activeTab } ) ] )
HoverCover idx -> ( { model | hoveredCover = Just idx }, Cmd.none )
UnhoverCover -> ( { model | hoveredCover = Nothing }, Cmd.none )
CoverBackgroundClick -> ( { model | hoveredCover = Nothing }, Cmd.none )
ExpandSection section -> ( { model | expandedSections = Set.insert section model.expandedSections }, Cmd.none )
ShowAllSection section -> ( model, fetchSectionData model.userSlug model.statsPeriod section )
CollapseSection section -> ( { model | expandedSections = Set.remove section model.expandedSections , loadedSections = Set.remove section model.loadedSections } , Cmd.none )
FetchSimilar artist track -> let key = similarKey artist track in if Dict.member key model.similarStates then ( { model | similarStates = Dict.remove key model.similarStates }, Cmd.none )
else ( { model | similarStates = Dict.insert key SimilarLoading model.similarStates } , fetchSimilarTracks artist track )
FetchSimilarTracks artist track result -> let key = similarKey artist track
newStates = case result of Ok tracks -> Dict.insert key (SimilarLoaded tracks) model.similarStates
Err err -> Dict.insert key (SimilarError (httpErrorToString err)) model.similarStates in ( { model | similarStates = newStates }, Cmd.none )
UpdateRegField field val -> let m = { model | regError = Nothing, regSubmitted = False } in ( case field of FSlug -> { m | regSlug = val }
FName -> { m | regName = val }
FEmail -> { m | regEmail = val }
FLbUser -> { m | regLbUser = val }
FLfUser -> { m | regLfUser = val } , Cmd.none )
SubmitRegistration -> if String.isEmpty (String.trim model.regSlug) || String.isEmpty (String.trim model.regName) || String.isEmpty (String.trim model.regEmail) then ( { model | regError = Just "Username, name and email are required" }, Cmd.none )
else ( { model | regSubmitting = True, regError = Nothing } , submitRegistration { slug = model.regSlug , name = model.regName , email = model.regEmail , lbUser = model.regLbUser , lfUser = model.regLfUser } )
GotRegistrationResult result -> case result of Ok () -> ( { model | regSubmitting = False, regSubmitted = True, regError = Nothing }, Cmd.none )
Err msg_ -> ( { model | regSubmitting = False, regError = Just msg_ }, Cmd.none )
UpdateAdminTokenInput val -> ( { model | adminTokenInput = val }, Cmd.none )
SaveAdminToken -> let token = String.trim model.adminTokenInput in ( { model | adminToken = token, adminError = Nothing } , Cmd.batch [ Ports.saveAdminToken token , if String.isEmpty token then Cmd.none
else Cmd.batch [ fetchRegistrations token, fetchUsers token ] ] )
FetchRegistrations -> ( { model | adminError = Nothing } , if String.isEmpty model.adminToken then Cmd.none
else fetchRegistrations model.adminToken )
GotRegistrations result -> case result of Ok regs -> ( { model | registrations = regs, adminError = Nothing }, Cmd.none )
Err err -> ( { model | adminError = Just (httpErrorToString err) }, Cmd.none )
ApproveRegistration id -> ( model, approveRegistration model.adminToken id )
DenyRegistration id -> ( model, denyRegistration model.adminToken id )
GotApproveResult result -> case result of Ok resp -> ( { model | approvedToken = resp.token, adminError = Nothing } , if String.isEmpty model.adminToken then Cmd.none
else Cmd.batch [ fetchRegistrations model.adminToken, fetchUsers model.adminToken ] )
Err err -> ( { model | adminError = Just (httpErrorToString err) }, Cmd.none )
GotDenyResult result -> case result of Ok () -> ( model , if String.isEmpty model.adminToken then Cmd.none
else fetchRegistrations model.adminToken )
Err msg_ -> ( { model | adminError = Just msg_ }, Cmd.none )
FetchUsers -> ( { model | adminError = Nothing } , if String.isEmpty model.adminToken then Cmd.none
else fetchUsers model.adminToken )
GotUsers result -> case result of Ok users -> ( { model | users = users, adminError = Nothing }, Cmd.none )
Err err -> ( { model | adminError = Just (httpErrorToString err) }, Cmd.none )
RequestRemoveUser id -> ( { model | confirmingRemoval = Just id }, Cmd.none )
CancelRemoveUser -> ( { model | confirmingRemoval = Nothing }, Cmd.none )
RemoveUser id -> ( { model | confirmingRemoval = Nothing }, removeUser model.adminToken id )
GotRemoveResult result -> case result of Ok () -> ( model , if String.isEmpty model.adminToken then Cmd.none
else fetchUsers model.adminToken )
Err msg_ -> ( { model | adminError = Just msg_ }, Cmd.none )
{-| Identify a similar-tracks panel by its content. Row indices shiftwhenever a refetch reorders or replaces the current page, so an index wouldstrand open panels and leak dict entries.-}similarKey : String -> String -> StringsimilarKey artist track = artist ++ "\t" ++ track
patchStatSection : String -> List StatsEntry -> Stats -> StatspatchStatSection section entries stats = case section of "artist" -> { stats | artists = entries }
"track" -> { stats | tracks = entries }
"genre" -> { stats | genres = entries }
"label" -> { stats | labels = entries }
"year" -> { stats | years = entries }
_ -> stats
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msgsubscriptions _ = Sub.batch [ Time.every 30000 Tick , Browser.Events.onVisibilityChange VisibilityChanged , Browser.Events.onKeyDown escapeKey ]
-- | Escape dismisses the zoomed cover, matching the backdrop click.escapeKey : D.Decoder MsgescapeKey = D.field "key" D.string |> D.andThen (\key -> if key == "Escape" then D.succeed CoverBackgroundClick
else D.fail "not escape" )
-- HTTP