Something went wrong. Try again.
A music player that connects to your cloud/distributed storage. forked from tokono.ma/diffuse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750module Brain.User.State exposing (..)
import Alienimport Brain.Common.State as Commonimport Brain.Ports as Portsimport Brain.Task.Portsimport Brain.Types as Brain exposing (..)import Brain.User.Hypaethral as Hypaethralimport Brain.User.Types as User exposing (..)import Debouncer.Basic as Debouncerimport EverySetimport Json.Decode as Decodeimport Json.Encode as Jsonimport Playlists.Encoding as Playlistsimport Return exposing (andThen, return)import Return.Ext as Returnimport Settingsimport Sources.Encoding as Sourcesimport Syncingimport Syncing.Services.Dropbox.Tokenimport Task exposing (Task)import TaskPort.Extra as TaskPortimport Timeimport Tracks exposing (Track)import Tracks.Encoding as Tracksimport Url exposing (Url)import Url.Ext as Urlimport User.Layer as User exposing (..)import User.Layer.Methods.Dropbox as Dropbox
-- 🌳
initialCommand : Url -> Cmd Brain.MsginitialCommand uiUrl = case Url.action uiUrl of _ -> Cmd.batch [ loadEnclosedData , loadLocalHypaethralData { initialUrl = uiUrl , methodTask = loadSyncMethod } ]
{-| Loads the "enclosed" data from cache and sends it to the UI.-}loadEnclosedData : Cmd Brain.MsgloadEnclosedData = Decode.value |> Brain.Task.Ports.fromCache Alien.EnclosedData |> Task.map (Maybe.withDefault Json.null) |> Common.attemptPortTask (Common.giveUICmdMsg Alien.LoadEnclosedUserData)
{-| Loads the "sync method".-}loadSyncMethod : Task String (Maybe Method)loadSyncMethod = Decode.value |> Brain.Task.Ports.fromCache Alien.SyncMethod |> Task.mapError TaskPort.errorToStringCustom |> Task.map (Maybe.andThen decodeMethod)
{-| Loads the "sync method" and "hypaethral" data,see `Commence` Msg what happens next.-}loadLocalHypaethralData : { initialUrl : Url, methodTask : Task String (Maybe Method) } -> Cmd Brain.MsgloadLocalHypaethralData { initialUrl, methodTask } = methodTask |> Task.andThen (\maybeMethod -> Hypaethral.retrieveLocal |> User.retrieveHypaethralData |> Task.map (\bits -> bits |> List.map (\( a, b ) -> ( hypaethralBitKey a, Maybe.withDefault Json.null b )) |> Json.object ) |> Task.map (Tuple.pair maybeMethod) ) |> Common.attemptTask (\( maybeMethod, hypaethralJson ) -> hypaethralJson |> User.decodeHypaethralData |> Result.map (\hypaethralData -> Commence maybeMethod initialUrl ( hypaethralJson , hypaethralData ) ) |> Result.mapError Decode.errorToString |> Common.reportErrorToUI UserMsg )
-- 📣
update : User.Msg -> Managerupdate msg = case msg of Commence a b c -> commence a b c
SetSyncMethod a -> setSyncMethod a
Sync -> sync { initialTask = Nothing }
UnsetSyncMethod -> unsetSyncMethod
----------------------------------------- -- x. Data ----------------------------------------- RetrieveEnclosedData -> retrieveEnclosedData
EnclosedDataRetrieved a -> enclosedDataRetrieved a
SaveEnclosedData a -> saveEnclosedData a
----------------------------------------- -- y. Data ----------------------------------------- -- The hypaethral user data is received in pieces, -- pieces which are "cached" here in the web worker. -- -- The reasons for this are: -- 1. Lesser performance penalty on the UI when saving data -- (ie. this avoids having to encode/decode everything each time) -- 2. The data can be used in the web worker (brain) as well. -- (eg. for track-search index) -- SaveFavourites a -> saveFavourites a
SavePlaylists a -> savePlaylists a
SaveProgress a -> saveProgress a
SaveSettings a -> saveSettings a
SaveSources a -> saveSources a
SaveTracks a -> saveTracks a
----------------------------------------- -- z. Data ----------------------------------------- FinishedSyncing -> finishedSyncing
GotHypaethralData a -> gotHypaethralData a
SaveHypaethralDataBits a -> saveHypaethralDataBits a
SaveHypaethralDataSlowly a -> saveHypaethralDataSlowly a
----------------------------------------- -- z. Secret Key ----------------------------------------- RemoveEncryptionKey -> removeEncryptionKey
UpdateEncryptionKey a -> updateEncryptionKey a
----------------------------------------- -- 📭 Other ----------------------------------------- RefreshedDropboxTokens a b c -> refreshedDropboxTokens a b c
-- 🔱
commence : Maybe Method -> Url -> ( Json.Value, HypaethralData ) -> Managercommence maybeMethod initialUrl ( hypaethralJson, hypaethralData ) model = -- 🚀 -- Initiated from `initialCommand`. -- Loaded the used-sync method and the local hypaethral data. { model | userSyncMethod = maybeMethod } |> sendHypaethralDataToUI hypaethralJson hypaethralData |> andThen (case Url.action initialUrl of _ -> sync { initialTask = Nothing } )
setSyncMethod : Json.Value -> ManagersetSyncMethod json model = -- 🐤 -- Set & store method, -- and retrieve data. let decoder = Decode.map2 (\a b -> ( a, b )) (Decode.field "method" <| Decode.map methodFromString Decode.string) (Decode.field "passphrase" <| Decode.maybe Decode.string) in case Decode.decodeValue decoder json of Ok ( Just method, Just passphrase ) -> let initialTask = passphrase |> Brain.Task.Ports.fabricateSecretKey |> Task.mapError TaskPort.errorToStringCustom in { model | userSyncMethod = Just method } |> sync { initialTask = Just initialTask } |> andThen (saveMethod method)
Ok ( Just method, Nothing ) -> { model | userSyncMethod = Just method } |> sync { initialTask = Nothing } |> andThen (saveMethod method)
Ok ( Nothing, _ ) -> Return.singleton { model | userSyncMethod = Nothing }
Err _ -> Return.singleton model
sync : { initialTask : Maybe (Task.Task String ()) } -> Managersync { initialTask } model = model |> syncCommand (Maybe.withDefault (Task.succeed ()) initialTask) |> return model |> andThen (case model.userSyncMethod of Just method -> Common.giveUI Alien.StartedSyncing (encodeMethod method)
Nothing -> Return.singleton )
syncCommand : Task.Task String a -> Model -> Cmd Brain.MsgsyncCommand initialTask model = let localData = model.hypaethralUserData
attemptSync args = args |> Syncing.task initialTask { localData = localData , saveLocal = Hypaethral.saveLocal } |> Common.attemptTask (\maybe -> case maybe of Just data -> UserMsg (GotHypaethralData data)
Nothing -> UserMsg FinishedSyncing ) in case model.userSyncMethod of Just (Dropbox { accessToken, expiresAt, refreshToken }) -> if Syncing.Services.Dropbox.Token.isExpired { currentTime = model.currentTime , expiresAt = expiresAt } then refreshDropboxTokens model.currentTime Sync initialTask refreshToken
else attemptSync { retrieve = Hypaethral.retrieveDropbox accessToken , save = Hypaethral.saveDropbox accessToken }
Just (Ipfs { apiOrigin }) -> attemptSync { retrieve = Hypaethral.retrieveIpfs apiOrigin , save = Hypaethral.saveIpfs apiOrigin }
Just (RemoteStorage args) -> attemptSync { retrieve = Hypaethral.retrieveRemoteStorage args , save = Hypaethral.saveRemoteStorage args }
Nothing -> Cmd.none
unsetSyncMethod : ManagerunsetSyncMethod model = -- 💀 -- Unset & remove stored method. [ Common.attemptPortTask (always Brain.Bypass) (Brain.Task.Ports.removeCache Alien.SyncMethod) , Common.attemptPortTask (always Brain.Bypass) (Brain.Task.Ports.removeCache Alien.SecretKey)
-- , case model.userSyncMethod of Just (Dropbox _) -> Cmd.none
Just (Ipfs _) -> Cmd.none
Just (RemoteStorage _) -> Ports.deconstructRemoteStorage ()
Nothing -> Cmd.none ] |> Cmd.batch |> return { model | userSyncMethod = Nothing }
-- 🔱 ░░ DATA - ENCLOSED
enclosedDataRetrieved : Json.Value -> ManagerenclosedDataRetrieved json = Common.giveUI Alien.LoadEnclosedUserData json
retrieveEnclosedData : ManagerretrieveEnclosedData = Decode.value |> Brain.Task.Ports.fromCache Alien.EnclosedData |> Common.attemptPortTask (\maybe -> case maybe of Just json -> Brain.UserMsg (EnclosedDataRetrieved json)
Nothing -> Brain.Bypass ) |> Return.communicate
saveEnclosedData : Json.Value -> ManagersaveEnclosedData json = json |> Brain.Task.Ports.toCache Alien.EnclosedData |> Common.attemptPortTask (always Brain.Bypass) |> Return.communicate
-- 🔱 ░░ DATA - HYPAETHRAL
finishedSyncing : ManagerfinishedSyncing model = case model.userSyncMethod of Just userSyncMethod -> Common.giveUI Alien.SyncMethod (encodeMethod userSyncMethod) model
Nothing -> Return.singleton model
gotHypaethralData : HypaethralData -> ManagergotHypaethralData hypaethralData model = model |> sendHypaethralDataToUI (User.encodeHypaethralData hypaethralData) hypaethralData |> andThen finishedSyncing
saveAllHypaethralDataTask : HypaethralData -> Method -> Task String ()saveAllHypaethralDataTask userData method = let save = saveHypaethralDataBitsTask (ModifiedAt :: User.allHypaethralBits) userData in case method of Dropbox { accessToken } -> save (Hypaethral.saveDropbox accessToken)
Ipfs { apiOrigin } -> save (Hypaethral.saveIpfs apiOrigin)
RemoteStorage a -> save (Hypaethral.saveRemoteStorage a)
saveHypaethralDataBitsTask : List HypaethralBit -> HypaethralData -> (HypaethralBit -> Json.Value -> Task String ()) -> Task String ()saveHypaethralDataBitsTask bits userData saveFn = [ -------- -- LOCAL -------- List.map (\bit -> Hypaethral.saveLocal bit (encodeHypaethralBit bit userData) ) bits , --------- -- REMOTE --------- List.map (\bit -> saveFn bit (encodeHypaethralBit bit userData) ) bits ] |> List.concat |> List.foldl (\nextTask -> Task.andThen (\_ -> nextTask)) (Task.succeed ())
{-| Save different parts of hypaethral data,one part at a time.-}saveHypaethralDataBits : List HypaethralBit -> ManagersaveHypaethralDataBits bitsWithoutModifiedAt model = let bits = ModifiedAt :: bitsWithoutModifiedAt
userData = model.hypaethralUserData
updatedUserData = { userData | modifiedAt = Just model.currentTime }
updatedModel = { model | hypaethralUserData = updatedUserData }
save saveFn = Time.now |> Task.andThen (\currentTime -> saveHypaethralDataBitsTask bits { updatedUserData | modifiedAt = Just currentTime } saveFn ) |> Common.attemptTask (always Brain.Bypass) |> return updatedModel in case model.userSyncMethod of Just (Dropbox { accessToken, expiresAt, refreshToken }) -> if Syncing.Services.Dropbox.Token.isExpired { currentTime = model.currentTime , expiresAt = expiresAt } then refreshToken |> refreshDropboxTokens model.currentTime (SaveHypaethralDataBits bits) (Task.succeed ()) |> return model
else save (Hypaethral.saveDropbox accessToken)
Just (Ipfs { apiOrigin }) -> save (Hypaethral.saveIpfs apiOrigin)
Just (RemoteStorage args) -> save (Hypaethral.saveRemoteStorage args)
Nothing -> -- Only save locally save (\_ _ -> Task.succeed ())
saveHypaethralDataBitWithDebounce : HypaethralBit -> ManagersaveHypaethralDataBitWithDebounce bit = bit |> Debouncer.provideInput |> saveHypaethralDataSlowly
saveHypaethralDataSlowly : Debouncer.Msg HypaethralBit -> ManagersaveHypaethralDataSlowly debouncerMsg model = let ( m, c, e ) = Debouncer.update debouncerMsg model.hypaethralDebouncer
bits = e |> Maybe.withDefault [] |> EverySet.fromList |> EverySet.toList in c |> Cmd.map (SaveHypaethralDataSlowly >> UserMsg) |> return { model | hypaethralDebouncer = m } |> (if not (List.isEmpty bits) then andThen (saveHypaethralDataBits bits)
else identity )
sendHypaethralDataToUI : Json.Value -> HypaethralData -> ManagersendHypaethralDataToUI encodedData decodedData model = [ encodedData |> Alien.broadcast Alien.LoadHypaethralUserData |> Ports.toUI
-- , decodedData.tracks |> Json.list Tracks.encodeTrack |> Ports.updateSearchIndex ] |> Cmd.batch |> return { model | hypaethralUserData = decodedData }
-- 🔱 ░░ DATA - HYPAETHRAL BITS
saveFavourites : Json.Value -> ManagersaveFavourites value model = value |> Decode.decodeValue (Decode.list Tracks.favouriteDecoder) |> Result.withDefault model.hypaethralUserData.favourites |> hypaethralLenses.setFavourites model |> saveHypaethralDataBitWithDebounce Favourites
savePlaylists : Json.Value -> ManagersavePlaylists value model = value |> Decode.decodeValue (Decode.list Playlists.decoder) |> Result.withDefault model.hypaethralUserData.playlists |> hypaethralLenses.setPlaylists model |> saveHypaethralDataBitWithDebounce Playlists
saveProgress : Json.Value -> ManagersaveProgress value model = value |> Decode.decodeValue (Decode.dict Decode.float) |> Result.withDefault model.hypaethralUserData.progress |> hypaethralLenses.setProgress model |> saveHypaethralDataBitWithDebounce Progress
saveSettings : Json.Value -> ManagersaveSettings value model = value |> Decode.decodeValue (Decode.map Just Settings.decoder) |> Result.withDefault model.hypaethralUserData.settings |> hypaethralLenses.setSettings model |> saveHypaethralDataBitWithDebounce Settings
saveSources : Json.Value -> ManagersaveSources value model = value |> Decode.decodeValue (Decode.list Sources.decoder) |> Result.withDefault model.hypaethralUserData.sources |> hypaethralLenses.setSources model |> saveHypaethralDataBitWithDebounce Sources
saveTracks : Json.Value -> ManagersaveTracks value model = saveTracksAndUpdateSearchIndex (value |> Decode.decodeValue (Decode.list Tracks.trackDecoder) |> Result.withDefault model.hypaethralUserData.tracks ) model
saveTracksAndUpdateSearchIndex : List Track -> ManagersaveTracksAndUpdateSearchIndex tracks model = tracks -- Store in model |> hypaethralLenses.setTracks model -- Update search index |> Return.communicate (tracks |> Json.list Tracks.encodeTrack |> Ports.updateSearchIndex ) -- Save with delay |> andThen (saveHypaethralDataBitWithDebounce Tracks)
-- 🔱 ░░ DATA - HYPAETHRAL LENSES
hypaethralLenses = { setFavourites = makeHypaethralLens (\h f -> { h | favourites = f }) , setPlaylists = makeHypaethralLens (\h p -> { h | playlists = p }) , setProgress = makeHypaethralLens (\h p -> { h | progress = p }) , setSettings = makeHypaethralLens (\h s -> { h | settings = s }) , setSources = makeHypaethralLens (\h s -> { h | sources = s }) , setTracks = makeHypaethralLens (\h t -> { h | tracks = t }) }
makeHypaethralLens : (HypaethralData -> a -> HypaethralData) -> Model -> a -> ModelmakeHypaethralLens setter model value = { model | hypaethralUserData = setter model.hypaethralUserData value }
-- 🔱 ░░ METHOD
saveMethod : Method -> ManagersaveMethod method model = method |> encodeMethod |> Brain.Task.Ports.toCache Alien.SyncMethod |> Common.attemptPortTask (always Brain.Bypass) |> return { model | userSyncMethod = Just method }
-- 🔱 ░░ SECRET KEY
removeEncryptionKey : ManagerremoveEncryptionKey model = Alien.SecretKey |> Brain.Task.Ports.removeCache |> Task.mapError TaskPort.errorToStringCustom |> Task.andThen (\_ -> Time.now) |> Task.andThen (\currentTime -> case model.userSyncMethod of Just method -> let data = model.hypaethralUserData in saveAllHypaethralDataTask { data | modifiedAt = Just currentTime } method
Nothing -> Task.succeed () ) |> Common.attemptTask (always Brain.Bypass) |> return model
updateEncryptionKey : Json.Value -> ManagerupdateEncryptionKey json model = case Decode.decodeValue Decode.string json of Ok passphrase -> passphrase |> Brain.Task.Ports.fabricateSecretKey |> Task.mapError TaskPort.errorToStringCustom |> Task.andThen (\_ -> Time.now) |> Task.andThen (\currentTime -> case model.userSyncMethod of Just method -> let data = model.hypaethralUserData in saveAllHypaethralDataTask { data | modifiedAt = Just currentTime } method
Nothing -> Task.succeed () ) |> Common.attemptTask (always Brain.Bypass) |> return model
Err _ -> Return.singleton model
-- 📭 ░░ OTHER
refreshDropboxTokens : Time.Posix -> User.Msg -> Task.Task String a -> String -> Cmd Brain.MsgrefreshDropboxTokens currentTime msg initialTask refreshToken = initialTask |> Task.andThen (\_ -> Dropbox.refreshAccessToken refreshToken) |> Task.attempt (\result -> case result of Ok tokens -> msg |> RefreshedDropboxTokens { currentTime = Time.posixToMillis currentTime // 1000 , refreshToken = refreshToken } tokens |> UserMsg
Err err -> Common.reportUICmdMsg Alien.ReportError err )
refreshedDropboxTokens : { currentTime : Int, refreshToken : String } -> Dropbox.Tokens -> User.Msg -> ManagerrefreshedDropboxTokens { currentTime, refreshToken } tokens msg model = { accessToken = tokens.accessToken , expiresAt = currentTime + tokens.expiresIn , refreshToken = refreshToken } |> Dropbox |> (\m -> saveMethod m model) |> andThen (update msg)