self-hosted listenbrainz and last.fm proxy
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302module Config ( AppConfig , S3Config , SmtpConfig , UserConfig , UserEntry , defaultUserConfig , fillUserConfigFromEnv , loadConfig , s3ConfigFromUser ) where
import Prelude
import Control.Monad.Error.Class (throwError)import Data.Argonaut (decodeJson, (.:), (.:?))import Data.Argonaut.Core (Json)import Data.Either (Either(..))import Data.Function.Uncurried (Fn3, runFn3)import Data.Int (fromString) as Data.Intimport Data.Maybe (Maybe(..), fromMaybe, isJust, isNothing)import Data.String (joinWith)import Data.Traversable (traverse)import Effect (Effect)import Effect.Aff (Aff, makeAff, nonCanceler)import Effect.Class (liftEffect)import Effect.Exception (error)import Node.Process (cwd, lookupEnv)
-- | Per-user runtime configuration after environment values are resolved.type UserConfig = { listenbrainzUser :: Maybe String , lastfmUser :: Maybe String , lastfmApiKey :: Maybe String , discogsToken :: Maybe String , cosineApiKey :: Maybe String , databaseFile :: String , s3Bucket :: Maybe String , s3Region :: String , awsAccessKeyId :: Maybe String , awsSecretAccessKey :: Maybe String , awsEndpointUrl :: Maybe String , awsS3AddressingStyle :: Maybe String , coverCacheEnabled :: Boolean , backupEnabled :: Boolean , backupIntervalHours :: Int }
-- | A configured user and their URL slug.type UserEntry = { slug :: String , name :: Maybe String , config :: UserConfig }
-- | Process-wide configuration and configured users.type AppConfig = { port :: Int , host :: String , metricsEnabled :: Boolean , corsOrigin :: String , adminToken :: Maybe String , adminEmail :: Maybe String , registrationEnabled :: Boolean , registrationsDb :: String , smtp :: SmtpConfig , users :: Array UserEntry }
-- | SMTP settings for notification email.type SmtpConfig = { host :: Maybe String , port :: Int , user :: Maybe String , pass :: Maybe String , from :: Maybe String }
-- | S3-compatible object storage settings.type S3Config = { bucket :: Maybe String , region :: String , accessKeyId :: Maybe String , secretAccessKey :: Maybe String , endpointUrl :: Maybe String , addressingStyle :: Maybe String }
-- | Extract object-storage settings from a user configuration.s3ConfigFromUser :: UserConfig -> S3Configs3ConfigFromUser cfg = { bucket: cfg.s3Bucket , region: cfg.s3Region , accessKeyId: cfg.awsAccessKeyId , secretAccessKey: cfg.awsSecretAccessKey , endpointUrl: cfg.awsEndpointUrl , addressingStyle: cfg.awsS3AddressingStyle }
-- Defaults for a self-registered user; creds and DB path are filled by fillUserConfigFromEnv.-- | Create defaults for a newly self-registered user.defaultUserConfig :: String -> Maybe String -> Maybe String -> UserConfigdefaultUserConfig databaseFile listenbrainzUser lastfmUser = { listenbrainzUser , lastfmUser , lastfmApiKey: Nothing , discogsToken: Nothing , cosineApiKey: Nothing , databaseFile , s3Bucket: Nothing , s3Region: "us-east-1" , awsAccessKeyId: Nothing , awsSecretAccessKey: Nothing , awsEndpointUrl: Nothing , awsS3AddressingStyle: Nothing , coverCacheEnabled: false , backupEnabled: false , backupIntervalHours: 24 }
foreign import loadConfigImpl :: Fn3 String (String -> Effect Unit) (Json -> Effect Unit) (Effect Unit)
-- | Load, resolve, and validate application configuration.loadConfig :: String -> Aff AppConfigloadConfig path = do json <- makeAff \cb -> runFn3 loadConfigImpl path (\msg -> cb (Left (error msg))) (\j -> cb (Right j)) *> pure nonCanceler rawUsers <- case decodeUsersJson json of Left msg -> throwError (error msg) Right users -> pure users portStr <- liftEffect $ lookupEnv "PORT" hostStr <- liftEffect $ lookupEnv "HOST" metricsEnabledStr <- liftEffect $ lookupEnv "METRICS_ENABLED" corsOriginStr <- liftEffect $ lookupEnv "CORS_ORIGIN" adminToken <- liftEffect $ lookupEnv "ADMIN_TOKEN" adminEmail <- liftEffect $ lookupEnv "ADMIN_EMAIL" registrationEnabledStr <- liftEffect $ lookupEnv "REGISTRATION_ENABLED" registrationsDbEnv <- liftEffect $ lookupEnv "CORPUS_REGISTRATIONS_DB" smtpHost <- liftEffect $ lookupEnv "SMTP_HOST" smtpPortStr <- liftEffect $ lookupEnv "SMTP_PORT" smtpUser <- liftEffect $ lookupEnv "SMTP_USER" smtpPass <- liftEffect $ lookupEnv "SMTP_PASS" smtpFrom <- liftEffect $ lookupEnv "SMTP_FROM" databasePath <- liftEffect $ lookupEnv "DATABASE_PATH" defaultPath <- liftEffect cwd filledUsers <- traverse ( \u -> do c <- fillUserConfigFromEnv u.config pure (u { config = c }) ) rawUsers let resolvePath file = case databasePath of Nothing -> defaultPath <> "/" <> file Just dir -> dir <> "/" <> file port = fromMaybe 8000 (portStr >>= Data.Int.fromString) host = fromMaybe "127.0.0.1" hostStr metricsEnabled = metricsEnabledStr == Just "true" corsOrigin = fromMaybe "*" corsOriginStr registrationEnabled = registrationEnabledStr == Just "true" registrationsDb = resolvePath (fromMaybe "registrations.db" registrationsDbEnv) smtp = { host: smtpHost , port: fromMaybe 587 (smtpPortStr >>= Data.Int.fromString) , user: smtpUser , pass: smtpPass , from: smtpFrom } fullConfig = { port , host , metricsEnabled , corsOrigin , adminToken , adminEmail , registrationEnabled , registrationsDb , smtp , users: filledUsers } case validateConfig fullConfig of Left msg -> throwError (error msg) Right cfg -> pure cfg
-- Fills shared credentials and resolves the database path from the environment.-- | Fill shared credentials and resolve the database path from the environment.fillUserConfigFromEnv :: UserConfig -> Aff UserConfigfillUserConfigFromEnv cfg = do lastfmApiKey <- liftEffect $ lookupEnv "LASTFM_API_KEY" discogsToken <- liftEffect $ lookupEnv "DISCOGS_TOKEN" cosineApiKey <- liftEffect $ lookupEnv "COSINE_API_KEY" s3Bucket <- liftEffect $ lookupEnv "S3_BUCKET" s3Region <- liftEffect $ map (fromMaybe "us-east-1") $ lookupEnv "S3_REGION" awsAccessKeyId <- liftEffect $ lookupEnv "AWS_ACCESS_KEY_ID" awsSecretAccessKey <- liftEffect $ lookupEnv "AWS_SECRET_ACCESS_KEY" awsEndpointUrl <- liftEffect $ lookupEnv "AWS_ENDPOINT_URL" awsS3AddressingStyle <- liftEffect $ lookupEnv "AWS_S3_ADDRESSING_STYLE" databasePath <- liftEffect $ lookupEnv "DATABASE_PATH" defaultPath <- liftEffect cwd let resolvePath file = case databasePath of Nothing -> defaultPath <> "/" <> file Just dir -> dir <> "/" <> file pure cfg { lastfmApiKey = lastfmApiKey , discogsToken = discogsToken , cosineApiKey = cosineApiKey , s3Bucket = s3Bucket , s3Region = s3Region , awsAccessKeyId = awsAccessKeyId , awsSecretAccessKey = awsSecretAccessKey , awsEndpointUrl = awsEndpointUrl , awsS3AddressingStyle = awsS3AddressingStyle , databaseFile = resolvePath cfg.databaseFile }
validateConfig :: AppConfig -> Either String AppConfigvalidateConfig cfg = do _ <- traverse validateUserEntry cfg.users pure cfg
validateUserEntry :: UserEntry -> Either String UserEntryvalidateUserEntry entry = let c = entry.config label = if entry.slug == "" then "root" else entry.slug lfmMissing = if isJust c.lastfmUser && isNothing c.lastfmApiKey then [ "LASTFM_API_KEY" ] else [] s3Missing = if c.coverCacheEnabled || c.backupEnabled then (if isNothing c.s3Bucket then [ "S3_BUCKET" ] else []) <> (if isNothing c.awsAccessKeyId then [ "AWS_ACCESS_KEY_ID" ] else []) <> ( if isNothing c.awsSecretAccessKey then [ "AWS_SECRET_ACCESS_KEY" ] else [] ) <> (if isNothing c.awsEndpointUrl then [ "AWS_ENDPOINT_URL" ] else []) else [] missing = lfmMissing <> s3Missing in if missing == [] then Right entry else Left ( "User '" <> label <> "': missing required env vars: " <> joinWith ", " missing )
mapLeft :: forall a b c. (a -> c) -> Either a b -> Either c bmapLeft f (Left a) = Left (f a)mapLeft _ (Right b) = Right b
decodeUsersJson :: Json -> Either String (Array UserEntry)decodeUsersJson json = do obj <- mapLeft show $ decodeJson json usersArr <- mapLeft show (obj .: "users" :: Either _ (Array Json)) traverse decodeUserEntry usersArr
decodeUserEntry :: Json -> Either String UserEntrydecodeUserEntry json = do obj <- mapLeft show $ decodeJson json slug <- mapLeft show $ obj .: "slug" name <- mapLeft show $ obj .:? "name" configJson <- mapLeft show (obj .: "config" :: Either _ Json) config <- decodeUserConfig configJson pure { slug, name, config }
-- Decodes only the non-sensitive, per-user fields from users.json.-- Shared credentials are injected from environment variables in loadConfig.decodeUserConfig :: Json -> Either String UserConfigdecodeUserConfig json = do obj <- mapLeft show $ decodeJson json listenbrainzUser <- mapLeft show $ obj .:? "listenbrainzUser" lastfmUser <- mapLeft show $ obj .:? "lastfmUser" databaseFile <- mapLeft show $ obj .: "databaseFile" coverCacheEnabled <- mapLeft show $ obj .: "coverCacheEnabled" backupEnabled <- mapLeft show $ obj .: "backupEnabled" backupIntervalHours <- mapLeft show $ obj .: "backupIntervalHours" pure { listenbrainzUser , lastfmUser , lastfmApiKey: Nothing , discogsToken: Nothing , cosineApiKey: Nothing , databaseFile , s3Bucket: Nothing , s3Region: "us-east-1" , awsAccessKeyId: Nothing , awsSecretAccessKey: Nothing , awsEndpointUrl: Nothing , awsS3AddressingStyle: Nothing , coverCacheEnabled , backupEnabled , backupIntervalHours }