From 0aec5774d934b08b68625f3c35a896c22ffbbee9 Mon Sep 17 00:00:00 2001 From: Steven Vandevelde Date: Sun, 4 Aug 2019 18:03:11 +0200 Subject: [PATCH] Refactor user layer stuff and save it into multiple files --- elm.json | 5 +- src/Applications/Brain.elm | 163 ++++++++++------- src/Applications/Brain/Ports.elm | 14 +- .../{Authentication.elm => User/Layer.elm} | 159 ++++++++++------ src/Applications/UI.elm | 69 ++++--- src/Applications/UI/Authentication.elm | 8 +- .../UI/Authentication/ContextMenu.elm | 1 - src/Applications/UI/Playlists.elm | 4 +- src/Applications/UI/Reply.elm | 6 +- src/Applications/UI/Settings.elm | 7 +- src/Applications/UI/Tracks.elm | 4 +- src/Javascript/Workers/Brain/user.js | 67 +++---- src/Javascript/Workers/brain.js | 12 +- src/Javascript/textile.js | 11 +- src/Library/Settings.elm | 39 ++++ .../{Authentication.elm => User/Layer.elm} | 173 ++++++++++++------ .../Layer/Methods}/RemoteStorage.elm | 12 +- 17 files changed, 482 insertions(+), 272 deletions(-) rename src/Applications/Brain/{Authentication.elm => User/Layer.elm} (70%) create mode 100644 src/Library/Settings.elm rename src/Library/{Authentication.elm => User/Layer.elm} (51%) rename src/Library/{Authentication => User/Layer/Methods}/RemoteStorage.elm (75%) diff --git a/elm.json b/elm.json index 02dc306d..2e4e8faa 100644 --- a/elm.json +++ b/elm.json @@ -8,6 +8,7 @@ "dependencies": { "direct": { "FabienHenon/elm-infinite-list-view": "3.0.0", + "Gizra/elm-all-set": "1.0.1", "Gizra/elm-debouncer": "2.0.0", "Herteby/enum": "1.0.0", "NoRedInk/elm-json-decode-pipeline": "1.0.0", @@ -41,12 +42,14 @@ "rtfeldman/elm-hex": "1.0.0", "ryannhg/date-format": "2.3.0", "truqu/elm-base64": "2.0.4", + "wernerdegroot/listzipper": "4.0.0", "ymtszw/elm-xml-decode": "3.1.0" }, "indirect": { "elm/parser": "1.1.0", "fredcy/elm-parseint": "2.0.1", - "jinjor/elm-xml-parser": "2.0.0" + "jinjor/elm-xml-parser": "2.0.0", + "pzp1997/assoc-list": "1.0.0" } }, "test-dependencies": { diff --git a/src/Applications/Brain.elm b/src/Applications/Brain.elm index 9bcb4297..bddfaa6d 100644 --- a/src/Applications/Brain.elm +++ b/src/Applications/Brain.elm @@ -1,26 +1,29 @@ module Brain exposing (main) import Alien -import Authentication exposing (HypaethralUserData) -import Brain.Authentication as Authentication import Brain.Ports import Brain.Reply exposing (Reply(..)) import Brain.Sources.Processing as Processing import Brain.Sources.Processing.Common as Processing import Brain.Tracks as Tracks +import Brain.User.Layer as User import Debouncer.Basic as Debouncer exposing (Debouncer) +import EverySet import Json.Decode as Json import Json.Encode +import List.Extra as List import Maybe.Extra as Maybe import Playlists.Encoding as Playlists import Return2 exposing (..) import Return3 +import Settings import Sources.Encoding as Sources import Sources.Processing as Processing import Sources.Processing.Encoding as Processing import Tracks import Tracks.Encoding as Tracks import Url +import User.Layer as User exposing (HypaethralBit(..)) @@ -45,11 +48,11 @@ main = type alias Model = - { authentication : Authentication.Model - , hypaethralUserData : Authentication.HypaethralUserData - , notSoFast : Debouncer Msg Msg + { hypaethralDebouncer : Debouncer HypaethralBit (List HypaethralBit) + , hypaethralUserData : User.HypaethralData , processing : Processing.Model , tracks : Tracks.Model + , userLayer : User.Model } @@ -58,16 +61,17 @@ init _ = ( ----------------------------------------- -- Initial model ----------------------------------------- - { authentication = Authentication.initialModel - , hypaethralUserData = Authentication.emptyHypaethralUserData + { hypaethralUserData = User.emptyHypaethralData , processing = Processing.initialModel , tracks = Tracks.initialModel + , userLayer = User.initialModel -- - , notSoFast = + , hypaethralDebouncer = 2.5 |> Debouncer.fromSeconds |> Debouncer.debounce + |> Debouncer.accumulateWith Debouncer.allInputs |> Debouncer.toDebouncer } ----------------------------------------- @@ -86,7 +90,6 @@ type Msg | Cmd (Cmd Msg) | Initialize String | NotifyUI Alien.Event - | NotSoFast (Debouncer.Msg Msg) | Process Processing.Arguments | ToCache Alien.Event ----------------------------------------- @@ -96,15 +99,16 @@ type Msg ----------------------------------------- -- Children ----------------------------------------- - | AuthenticationMsg Authentication.Msg | ProcessingMsg Processing.Msg | TracksMsg Tracks.Msg + | UserLayerMsg User.Msg ----------------------------------------- -- User data ----------------------------------------- | LoadHypaethralUserData Json.Value | RemoveTracksBySourceId String - | SaveHypaethralData + | SaveHypaethralData HypaethralBit + | SaveHypaethralDataSlowly (Debouncer.Msg HypaethralBit) | SaveFavourites Json.Value | SavePlaylists Json.Value | SaveSettings Json.Value @@ -134,7 +138,7 @@ update msg model = } (Url.fromString href) in - [ Cmd.map AuthenticationMsg (Authentication.initialCommand initialUrl) + [ Cmd.map UserLayerMsg (User.initialCommand initialUrl) , Cmd.map ProcessingMsg Processing.initialCommand ] |> Cmd.batch @@ -155,17 +159,6 @@ update msg model = |> Cmd.batch |> returnWithModel model - NotSoFast debouncerMsg -> - Return3.wieldNested - update - { mapCmd = NotSoFast - , mapModel = \child -> { model | notSoFast = child } - , update = \m -> Debouncer.update m >> Return3.fromDebouncer - } - { model = model.notSoFast - , msg = debouncerMsg - } - Process { origin, sources } -> { origin = origin , sources = sources @@ -191,14 +184,14 @@ update msg model = ----------------------------------------- -- Children ----------------------------------------- - AuthenticationMsg Authentication.PerformSignOut -> + UserLayerMsg User.PerformSignOut -> -- When signing out, remove all traces of the user's data. - updateAuthentication - { model | hypaethralUserData = Authentication.emptyHypaethralUserData } - Authentication.PerformSignOut + updateUserLayer + { model | hypaethralUserData = User.emptyHypaethralData } + User.PerformSignOut - AuthenticationMsg sub -> - updateAuthentication model sub + UserLayerMsg sub -> + updateUserLayer model sub ProcessingMsg sub -> updateProcessing model sub @@ -222,7 +215,7 @@ update msg model = let decodedData = value - |> Authentication.decodeHypaethral + |> User.decodeHypaethralData |> Result.withDefault model.hypaethralUserData encodedTracks = @@ -240,42 +233,67 @@ update msg model = |> .kept |> hypaethralLenses.setTracks model |> updateSearchIndexWithModel - |> andThen saveHypaethralData + |> andThen (saveHypaethralDataBitWithDelay Tracks) - SaveHypaethralData -> + SaveHypaethralData bit -> model.hypaethralUserData - |> Authentication.encodeHypaethral - |> Authentication.SaveHypaethralData - |> AuthenticationMsg + |> User.encodeHypaethralBit bit + |> User.SaveHypaethralData bit + |> UserLayerMsg |> updateWithModel model + SaveHypaethralDataSlowly debouncerMsg -> + Return3.wieldNested + update + { mapCmd = SaveHypaethralDataSlowly + , mapModel = \child -> { model | hypaethralDebouncer = child } + , update = + \dbMsg dbModel -> + let + ( m, c, r ) = + Debouncer.update dbMsg dbModel + in + ( m + , c + , r + |> Debug.log "" + |> Maybe.withDefault [] + |> EverySet.fromList + |> EverySet.toList + |> List.map SaveHypaethralData + ) + } + { model = model.hypaethralDebouncer + , msg = debouncerMsg + } + SaveFavourites value -> value |> Json.decodeValue (Json.list Tracks.favouriteDecoder) |> Result.withDefault model.hypaethralUserData.favourites |> hypaethralLenses.setFavourites model - |> saveHypaethralData + |> saveHypaethralDataBitWithDelay Favourites SavePlaylists value -> value |> Json.decodeValue (Json.list Playlists.decoder) |> Result.withDefault model.hypaethralUserData.playlists |> hypaethralLenses.setPlaylists model - |> saveHypaethralData + |> saveHypaethralDataBitWithDelay Playlists SaveSettings value -> value - |> Json.decodeValue (Json.map Just Authentication.settingsDecoder) + |> Json.decodeValue (Json.map Just Settings.decoder) |> Result.withDefault model.hypaethralUserData.settings |> hypaethralLenses.setSettings model - |> saveHypaethralData + |> saveHypaethralDataBitWithDelay Settings SaveSources value -> value |> Json.decodeValue (Json.list Sources.decoder) |> Result.withDefault model.hypaethralUserData.sources |> hypaethralLenses.setSources model - |> saveHypaethralData + |> saveHypaethralDataBitWithDelay Sources SaveTracks value -> value @@ -283,7 +301,7 @@ update msg model = |> Result.withDefault model.hypaethralUserData.tracks |> hypaethralLenses.setTracks model |> updateSearchIndex value - |> andThen saveHypaethralData + |> andThen (saveHypaethralDataBitWithDelay Tracks) updateWithModel : Model -> Msg -> ( Model, Cmd Msg ) @@ -316,7 +334,7 @@ translateReply : Reply -> Model -> ( Model, Cmd Msg ) translateReply reply model = case reply of FabricatedNewSecretKey -> - update SaveHypaethralData model + saveHypaethralData model ----------------------------------------- -- Tracks @@ -326,7 +344,7 @@ translateReply reply model = |> (++) model.hypaethralUserData.tracks |> hypaethralLenses.setTracks model |> updateSearchIndexWithModel - |> andThen saveHypaethralData + |> andThen (saveHypaethralDataBitWithDelay Tracks) RemoveTracksByPaths args -> model.hypaethralUserData.tracks @@ -334,7 +352,7 @@ translateReply reply model = |> .kept |> hypaethralLenses.setTracks model |> updateSearchIndexWithModel - |> andThen saveHypaethralData + |> andThen (saveHypaethralDataBitWithDelay Tracks) ----------------------------------------- -- To UI @@ -359,15 +377,15 @@ translateReply reply model = -- 📣 ░░ CHILDREN -updateAuthentication : Model -> Authentication.Msg -> ( Model, Cmd Msg ) -updateAuthentication model sub = +updateUserLayer : Model -> User.Msg -> ( Model, Cmd Msg ) +updateUserLayer model sub = Return3.wieldNested translateReply - { mapCmd = AuthenticationMsg - , mapModel = \child -> { model | authentication = child } - , update = Authentication.update + { mapCmd = UserLayerMsg + , mapModel = \child -> { model | userLayer = child } + , update = User.update } - { model = model.authentication + { model = model.userLayer , msg = sub } @@ -411,16 +429,29 @@ hypaethralLenses = } -makeHypaethralLens : (HypaethralUserData -> a -> HypaethralUserData) -> Model -> a -> Model +makeHypaethralLens : (User.HypaethralData -> a -> User.HypaethralData) -> Model -> a -> Model makeHypaethralLens setter model value = { model | hypaethralUserData = setter model.hypaethralUserData value } saveHypaethralData : Model -> ( Model, Cmd Msg ) saveHypaethralData model = - SaveHypaethralData + List.foldl + (\bit -> + bit + |> SaveHypaethralData + |> update + |> andThen + ) + (return model) + (List.map Tuple.second User.hypaethralBit.list) + + +saveHypaethralDataBitWithDelay : User.HypaethralBit -> Model -> ( Model, Cmd Msg ) +saveHypaethralDataBitWithDelay bit model = + bit |> Debouncer.provideInput - |> NotSoFast + |> SaveHypaethralDataSlowly |> updateWithModel model @@ -459,31 +490,31 @@ translateAlienData : Alien.Tag -> Json.Value -> Msg translateAlienData tag data = case tag of Alien.AuthAnonymous -> - AuthenticationMsg (Authentication.HypaethralDataRetrieved data) + UserLayerMsg (User.HypaethralDataRetrieved data) Alien.AuthBlockstack -> - AuthenticationMsg (Authentication.HypaethralDataRetrieved data) + UserLayerMsg (User.HypaethralDataRetrieved data) Alien.AuthDropbox -> - AuthenticationMsg (Authentication.HypaethralDataRetrieved data) + UserLayerMsg (User.HypaethralDataRetrieved data) Alien.AuthEnclosedData -> - AuthenticationMsg (Authentication.EnclosedDataRetrieved data) + UserLayerMsg (User.EnclosedDataRetrieved data) Alien.AuthIpfs -> - AuthenticationMsg (Authentication.HypaethralDataRetrieved data) + UserLayerMsg (User.HypaethralDataRetrieved data) Alien.AuthMethod -> - AuthenticationMsg (Authentication.MethodRetrieved data) + UserLayerMsg (User.MethodRetrieved data) Alien.AuthRemoteStorage -> - AuthenticationMsg (Authentication.HypaethralDataRetrieved data) + UserLayerMsg (User.HypaethralDataRetrieved data) Alien.AuthTextile -> - AuthenticationMsg (Authentication.HypaethralDataRetrieved data) + UserLayerMsg (User.HypaethralDataRetrieved data) Alien.FabricateSecretKey -> - AuthenticationMsg Authentication.SecretKeyFabricated + UserLayerMsg User.SecretKeyFabricated Alien.SearchTracks -> data @@ -518,7 +549,7 @@ translateAlienData tag data = Cmd (Brain.Ports.removeTracksFromCache data) Alien.SaveEnclosedUserData -> - AuthenticationMsg (Authentication.SaveEnclosedData data) + UserLayerMsg (User.SaveEnclosedData data) Alien.SaveFavourites -> SaveFavourites data @@ -536,10 +567,10 @@ translateAlienData tag data = SaveTracks data Alien.SignIn -> - AuthenticationMsg (Authentication.PerformSignIn data) + UserLayerMsg (User.PerformSignIn data) Alien.SignOut -> - AuthenticationMsg Authentication.PerformSignOut + UserLayerMsg User.PerformSignOut Alien.StoreTracksInCache -> Cmd (Brain.Ports.storeTracksInCache data) @@ -555,7 +586,7 @@ translateAlienData tag data = Alien.UpdateEncryptionKey -> case Json.decodeValue Json.string data of Ok passphrase -> - AuthenticationMsg (Authentication.FabricateSecretKey passphrase) + UserLayerMsg (User.FabricateSecretKey passphrase) Err _ -> Bypass diff --git a/src/Applications/Brain/Ports.elm b/src/Applications/Brain/Ports.elm index b7c30626..bae990cd 100644 --- a/src/Applications/Brain/Ports.elm +++ b/src/Applications/Brain/Ports.elm @@ -12,12 +12,6 @@ import Sources.Processing exposing (ContextForTags) port fabricateSecretKey : Alien.Event -> Cmd msg -port handlePendingBlockstackSignIn : String -> Cmd msg - - -port redirectToBlockstackSignIn : () -> Cmd msg - - port removeCache : Alien.Event -> Cmd msg @@ -46,7 +40,7 @@ port updateSearchIndex : Json.Value -> Cmd msg --- 📣 ░░ AUTHENTICATION +-- 📣 ░░ USER LAYER SERVICES port deconstructBlockstack : () -> Cmd msg @@ -55,6 +49,12 @@ port deconstructBlockstack : () -> Cmd msg port deconstructRemoteStorage : () -> Cmd msg +port handlePendingBlockstackSignIn : String -> Cmd msg + + +port redirectToBlockstackSignIn : () -> Cmd msg + + port requestBlockstack : Alien.Event -> Cmd msg diff --git a/src/Applications/Brain/Authentication.elm b/src/Applications/Brain/User/Layer.elm similarity index 70% rename from src/Applications/Brain/Authentication.elm rename to src/Applications/Brain/User/Layer.elm index 3325ee6d..edbccb63 100644 --- a/src/Applications/Brain/Authentication.elm +++ b/src/Applications/Brain/User/Layer.elm @@ -1,35 +1,17 @@ -module Brain.Authentication exposing (Model, Msg(..), initialCommand, initialModel, update) - -{-| Authentication. - -Involves: - - 1. Enclosed UserData (enable shuffle, EQ settings, ... ~> device) - 2. Hypaethral UserData (sources, tracks, favourites, ... ~> account) - -Methods: - - - Local - - IPFS - -Steps: - - 1. Get active method (if none, we're signed out) - 2. Get hypaethral data - --} +module Brain.User.Layer exposing (Model, Msg(..), initialCommand, initialModel, update) import Alien -import Authentication exposing (..) import Brain.Ports as Ports import Brain.Reply exposing (Reply(..)) import Conditional exposing (..) import Json.Decode as Decode import Json.Encode as Json +import List.Zipper as Zipper exposing (Zipper) import Return3 as Return exposing (..) import Task.Extra exposing (do) import Url exposing (Url) import Url.Ext as Url +import User.Layer exposing (..) @@ -38,6 +20,7 @@ import Url.Ext as Url type alias Model = { method : Maybe Method + , hypaethralRetrieval : Maybe (Zipper ( HypaethralBit, Json.Value )) , performingSignIn : Bool } @@ -45,6 +28,7 @@ type alias Model = initialModel : Model initialModel = { method = Nothing + , hypaethralRetrieval = Nothing , performingSignIn = False } @@ -87,13 +71,13 @@ type Msg | RetrieveMethod | MethodRetrieved Json.Value -- 2. Data - | RetrieveHypaethralData + | RetrieveHypaethralData HypaethralBit | HypaethralDataRetrieved Json.Value -- x. Data | RetrieveEnclosedData | EnclosedDataRetrieved Json.Value | SaveEnclosedData Json.Value - | SaveHypaethralData Json.Value + | SaveHypaethralData HypaethralBit Json.Value update : Msg -> Model -> Return Model Msg Reply @@ -117,8 +101,7 @@ update msg model = { model | method = maybeMethod, performingSignIn = True } Ok ( maybeMethod, Nothing ) -> - update - RetrieveHypaethralData + retrieveAllHypaethralData { model | method = maybeMethod, performingSignIn = True } _ -> @@ -168,7 +151,7 @@ update msg model = SecretKeyFabricated -> if model.performingSignIn then - update RetrieveHypaethralData model + retrieveAllHypaethralData model else returnReplyWithModel model FabricatedNewSecretKey @@ -186,8 +169,7 @@ update msg model = case decodeMethod json of -- 🚀 Just method -> - update - RetrieveHypaethralData + retrieveAllHypaethralData { model | method = Just method } -- ✋ @@ -199,17 +181,23 @@ update msg model = ----------------------------------------- -- # 2 ----------------------------------------- - RetrieveHypaethralData -> + RetrieveHypaethralData bit -> + let + file = + Json.string (hypaethralBitFileName bit) + in case model.method of -- 🚀 Just Blockstack -> - Alien.AuthBlockstack - |> Alien.trigger + [ ( "file", file ) ] + |> Json.object + |> Alien.broadcast Alien.AuthBlockstack |> Ports.requestBlockstack |> Return.commandWithModel model Just (Dropbox { token }) -> - [ ( "token", Json.string token ) + [ ( "file", file ) + , ( "token", Json.string token ) ] |> Json.object |> Alien.broadcast Alien.AuthDropbox @@ -218,6 +206,7 @@ update msg model = Just (Ipfs { apiOrigin }) -> [ ( "apiOrigin", Json.string apiOrigin ) + , ( "file", file ) ] |> Json.object |> Alien.broadcast Alien.AuthIpfs @@ -225,13 +214,15 @@ update msg model = |> Return.commandWithModel model Just Local -> - Alien.AuthAnonymous - |> Alien.trigger + [ ( "file", file ) ] + |> Json.object + |> Alien.broadcast Alien.AuthAnonymous |> Ports.requestCache |> Return.commandWithModel model Just (RemoteStorage { userAddress, token }) -> - [ ( "token", Json.string token ) + [ ( "file", file ) + , ( "token", Json.string token ) , ( "userAddress", Json.string userAddress ) ] |> Json.object @@ -241,6 +232,7 @@ update msg model = Just (Textile { apiOrigin }) -> [ ( "apiOrigin", Json.string apiOrigin ) + , ( "file", file ) ] |> Json.object |> Alien.broadcast Alien.AuthTextile @@ -252,23 +244,47 @@ update msg model = return model HypaethralDataRetrieved json -> - ( { model | performingSignIn = False } - -- - , case ( model.performingSignIn, model.method ) of - ( True, Just method ) -> - method - |> encodeMethod - |> Alien.broadcast Alien.AuthMethod - |> Ports.toCache + let + retrieval = + Maybe.map + (Zipper.mapCurrent <| Tuple.mapSecond <| always json) + model.hypaethralRetrieval + in + case Maybe.andThen Zipper.next retrieval of + Just nextRetrieval -> + update + (RetrieveHypaethralData <| Tuple.first <| Zipper.current nextRetrieval) + { model | hypaethralRetrieval = Just nextRetrieval } - _ -> - Cmd.none - -- - , model.method - |> Maybe.map (\method -> Authenticated method json) - |> Maybe.map terminate - |> Maybe.withDefault [] - ) + Nothing -> + -- 🚀 + ( { model + | hypaethralRetrieval = Nothing + , performingSignIn = False + } + -- + , case ( model.performingSignIn, model.method ) of + ( True, Just method ) -> + method + |> encodeMethod + |> Alien.broadcast Alien.AuthMethod + |> Ports.toCache + + _ -> + Cmd.none + -- + , let + allJson = + retrieval + |> Maybe.map Zipper.toList + |> Maybe.withDefault [] + |> putHypaethralJsonBitsTogether + in + model.method + |> Maybe.map (\method -> Authenticated method allJson) + |> Maybe.map terminate + |> Maybe.withDefault [] + ) ----------------------------------------- -- Data @@ -290,17 +306,25 @@ update msg model = |> Ports.toCache |> Return.commandWithModel model - SaveHypaethralData json -> + SaveHypaethralData bit json -> + let + file = + Json.string (hypaethralBitFileName bit) + in case model.method of -- 🚀 Just Blockstack -> - json + [ ( "data", json ) + , ( "file", file ) + ] + |> Json.object |> Alien.broadcast Alien.AuthBlockstack |> Ports.toBlockstack |> Return.commandWithModel model Just (Dropbox { token }) -> [ ( "data", json ) + , ( "file", file ) , ( "token", Json.string token ) ] |> Json.object @@ -311,6 +335,7 @@ update msg model = Just (Ipfs { apiOrigin }) -> [ ( "apiOrigin", Json.string apiOrigin ) , ( "data", json ) + , ( "file", file ) ] |> Json.object |> Alien.broadcast Alien.AuthIpfs @@ -318,13 +343,17 @@ update msg model = |> Return.commandWithModel model Just Local -> - json + [ ( "data", json ) + , ( "file", file ) + ] + |> Json.object |> Alien.broadcast Alien.AuthAnonymous |> Ports.toCache |> Return.commandWithModel model Just (RemoteStorage { userAddress, token }) -> [ ( "data", json ) + , ( "file", file ) , ( "token", Json.string token ) , ( "userAddress", Json.string userAddress ) ] @@ -336,6 +365,7 @@ update msg model = Just (Textile { apiOrigin }) -> [ ( "apiOrigin", Json.string apiOrigin ) , ( "data", json ) + , ( "file", file ) ] |> Json.object |> Alien.broadcast Alien.AuthTextile @@ -347,6 +377,25 @@ update msg model = return model +retrieveAllHypaethralData : Model -> Return Model Msg Reply +retrieveAllHypaethralData model = + let + maybeZipper = + hypaethralBit.list + |> List.map (\( _, b ) -> ( b, Json.null )) + |> Zipper.fromList + in + case maybeZipper of + Just zipper -> + update + (RetrieveHypaethralData <| Tuple.first <| Zipper.current zipper) + { model | hypaethralRetrieval = Just zipper } + + Nothing -> + return + { model | hypaethralRetrieval = Nothing } + + -- TERMINATION @@ -361,7 +410,7 @@ terminate t = case t of Authenticated method hypData -> [ GiveUI Alien.LoadHypaethralUserData hypData - , GiveUI Alien.AuthMethod (Authentication.encodeMethod method) + , GiveUI Alien.AuthMethod (encodeMethod method) ] NotAuthenticated -> diff --git a/src/Applications/UI.elm b/src/Applications/UI.elm index b2601885..e4306d2c 100644 --- a/src/Applications/UI.elm +++ b/src/Applications/UI.elm @@ -2,8 +2,6 @@ module UI exposing (main) import Alfred exposing (Alfred) import Alien -import Authentication exposing (..) -import Authentication.RemoteStorage exposing (RemoteStorage) import Browser import Browser.Dom import Browser.Events @@ -42,6 +40,7 @@ import Playlists.Encoding as Playlists import Process import Return2 exposing (..) import Return3 +import Settings import Sources import Sources.Encoding as Sources import Sources.Services.Dropbox @@ -84,6 +83,8 @@ import UI.Tracks as Tracks import UI.Tracks.ContextMenu as Tracks import UI.Tracks.Scene.List import Url exposing (Url) +import User.Layer exposing (..) +import User.Layer.Methods.RemoteStorage as RemoteStorage @@ -242,7 +243,7 @@ type Msg -- Authentication ----------------------------------------- | AuthenticationBootFailure String - | RemoteStorageWebfinger RemoteStorage (Result Http.Error String) + | RemoteStorageWebfinger RemoteStorage.Attributes (Result Http.Error String) | SyncUserData ----------------------------------------- -- Children @@ -357,10 +358,10 @@ update msg model = -- We're caching the user's data in the browser while offline. -- If we're back online again, sync all the user's data. (case model.authentication of - Authentication.Authenticated (Authentication.Dropbox _) -> + Authentication.Authenticated (Dropbox _) -> update SyncUserData - Authentication.Authenticated (Authentication.RemoteStorage _) -> + Authentication.Authenticated (RemoteStorage _) -> update SyncUserData _ -> @@ -443,7 +444,7 @@ update msg model = Common.urlOrigin model.url in remoteStorage - |> Authentication.RemoteStorage.oauthAddress + |> RemoteStorage.oauthAddress { oauthOrigin = oauthOrigin , origin = origin } @@ -451,7 +452,7 @@ update msg model = |> returnWithModel model RemoteStorageWebfinger _ (Err _) -> - Authentication.RemoteStorage.webfingerError + RemoteStorage.webfingerError |> ShowErrorNotification |> translateReplyWithModel model @@ -575,12 +576,34 @@ update msg model = |> Result.withDefault Json.Encode.null |> LoadHypaethralUserData ) - |> andThen (translateReply SaveFavourites) - |> andThen (translateReply SaveSources) - |> andThen (translateReply SaveTracks) |> andThen (translateReply ClearTracksCache) |> andThen (update <| ShowNotification notification) |> andThen (update <| ChangeUrlUsingPage Page.Index) + ----------------------------- + -- Save all the imported data + ----------------------------- + |> (\return -> + List.foldl + (\( _, bit ) -> + case bit of + Favourites -> + andThen (translateReply SaveFavourites) + + Playlists -> + andThen (translateReply SavePlaylists) + + Settings -> + andThen (translateReply SaveSettings) + + Sources -> + andThen (translateReply SaveSources) + + Tracks -> + andThen (translateReply SaveTracks) + ) + return + hypaethralBit.list + ) ----------------------------------------- -- Notifications @@ -778,13 +801,13 @@ translateReply reply model = ----------------------------------------- -- Authentication ----------------------------------------- - ExternalAuth Authentication.Blockstack _ -> + ExternalAuth Blockstack _ -> Alien.RedirectToBlockstackSignIn |> Alien.trigger |> Ports.toBrain |> returnWithModel model - ExternalAuth (Authentication.Dropbox _) _ -> + ExternalAuth (Dropbox _) _ -> [ ( "response_type", "token" ) , ( "client_id", "te0c9pbeii8f8bw" ) , ( "redirect_uri", Common.urlOrigin model.url ++ "?action=authenticate/dropbox" ) @@ -794,14 +817,14 @@ translateReply reply model = |> Nav.load |> returnWithModel model - ExternalAuth (Authentication.RemoteStorage _) input -> + ExternalAuth (RemoteStorage _) input -> input - |> Authentication.RemoteStorage.parseUserAddress + |> RemoteStorage.parseUserAddress |> Maybe.map - (Authentication.RemoteStorage.webfingerRequest RemoteStorageWebfinger) + (RemoteStorage.webfingerRequest RemoteStorageWebfinger) |> Maybe.unwrap (translateReply - (ShowErrorNotification Authentication.RemoteStorage.userAddressError) + (ShowErrorNotification RemoteStorage.userAddressError) model ) (returnWithModel model) @@ -1346,7 +1369,7 @@ translateReply reply model = , sources = model.sources.collection , tracks = model.tracks.collection.untouched } - |> Authentication.encodeHypaethral + |> encodeHypaethralData |> Json.Encode.encode 2 |> File.Download.string "diffuse.json" "application/json" |> returnWithModel model @@ -1393,7 +1416,7 @@ translateReply reply model = SaveSettings -> model |> gatherSettings - |> Authentication.encodeSettings + |> Settings.encode |> Alien.broadcast Alien.SaveSettings |> Ports.toBrain |> returnWithModel model @@ -1507,7 +1530,7 @@ translateAlienData event = Just Alien.AuthMethod -> -- My brain told me which auth method we're using, -- so we can tell the user in the UI. - case Authentication.decodeMethod event.data of + case decodeMethod event.data of Just method -> AuthenticationMsg (Authentication.SignedIn method) @@ -1979,7 +2002,7 @@ vesselInnerStyles = -- ⚗️ ░░ HYPAETHRAL DATA -gatherSettings : Model -> Settings +gatherSettings : Model -> Settings.Settings gatherSettings { backdrop, tracks } = { backgroundImage = backdrop.chosen , hideDuplicates = tracks.hideDuplicates @@ -1988,7 +2011,7 @@ gatherSettings { backdrop, tracks } = importHypaethral : Json.Decode.Value -> Model -> Return3.Return Model Msg Reply importHypaethral value model = - case decodeHypaethral value of + case decodeHypaethralData value of Ok data -> let { backdrop, sources } = @@ -2049,7 +2072,7 @@ exportEnclosed model = , volume = model.equalizer.volume } in - encodeEnclosed + encodeEnclosedData { cachedTracks = model.tracks.cached , equalizerSettings = equalizerSettings , grouping = model.tracks.grouping @@ -2070,7 +2093,7 @@ importEnclosed value model = { equalizer, playlists, queue, tracks } = model in - case decodeEnclosed value of + case decodeEnclosedData value of Ok data -> let newEqualizer = diff --git a/src/Applications/UI/Authentication.elm b/src/Applications/UI/Authentication.elm index dc89e9ab..7e71b896 100644 --- a/src/Applications/UI/Authentication.elm +++ b/src/Applications/UI/Authentication.elm @@ -1,7 +1,6 @@ module UI.Authentication exposing (Model(..), Msg(..), extractMethod, initialModel, update, view) import Alien -import Authentication exposing (Method(..)) import Base64 import Binary import Chunky exposing (..) @@ -35,6 +34,7 @@ import UI.Reply exposing (Reply(..)) import UI.Svg.Elements import Url exposing (Url) import Url.Ext as Url +import User.Layer exposing (..) @@ -228,7 +228,7 @@ update msg model = SignIn method -> ( Unauthenticated -- - , [ ( "method", Authentication.encodeMethod method ) + , [ ( "method", encodeMethod method ) , ( "passphrase", Json.Encode.null ) ] |> Json.Encode.object @@ -247,7 +247,7 @@ update msg model = else ( Unauthenticated -- - , [ ( "method", Authentication.encodeMethod method ) + , [ ( "method", encodeMethod method ) , ( "passphrase", Json.Encode.string <| hashPassphrase passphrase ) ] |> Json.Encode.object @@ -649,7 +649,7 @@ choicesScreen = , T.z_1 ] [ choiceButton - { action = ShowNewEncryptionKeyScreen Authentication.Local + { action = ShowNewEncryptionKeyScreen Local , icon = Icons.web , infoLink = Nothing , isLast = False diff --git a/src/Applications/UI/Authentication/ContextMenu.elm b/src/Applications/UI/Authentication/ContextMenu.elm index ab1c1c3c..2b7af32c 100644 --- a/src/Applications/UI/Authentication/ContextMenu.elm +++ b/src/Applications/UI/Authentication/ContextMenu.elm @@ -1,6 +1,5 @@ module UI.Authentication.ContextMenu exposing (moreOptionsMenu) -import Authentication import ContextMenu exposing (..) import Coordinates exposing (Coordinates) import Svg diff --git a/src/Applications/UI/Playlists.elm b/src/Applications/UI/Playlists.elm index 9c2fc80d..f257589c 100644 --- a/src/Applications/UI/Playlists.elm +++ b/src/Applications/UI/Playlists.elm @@ -1,6 +1,5 @@ module UI.Playlists exposing (Model, Msg(..), importHypaethral, initialModel, update, view) -import Authentication exposing (HypaethralUserData) import Chunky exposing (..) import Color exposing (Color) import Color.Ext as Color @@ -28,6 +27,7 @@ import UI.Playlists.Directory import UI.Playlists.Page exposing (Page(..)) import UI.Reply exposing (Reply(..)) import Url +import User.Layer exposing (HypaethralData) @@ -198,7 +198,7 @@ update msg model = returnRepliesWithModel model [ ShowPlaylistListMenu coordinates playlist ] -importHypaethral : Model -> HypaethralUserData -> Return Model Msg Reply +importHypaethral : Model -> HypaethralData -> Return Model Msg Reply importHypaethral model data = return { model diff --git a/src/Applications/UI/Reply.elm b/src/Applications/UI/Reply.elm index 09c4483b..456cb6e4 100644 --- a/src/Applications/UI/Reply.elm +++ b/src/Applications/UI/Reply.elm @@ -1,6 +1,5 @@ module UI.Reply exposing (Reply(..)) -import Authentication import Common exposing (Switch(..)) import Coordinates exposing (Coordinates) import Playlists exposing (Playlist, PlaylistTrack) @@ -8,6 +7,7 @@ import Queue import Sources exposing (Source) import Tracks exposing (IdentifiedTrack, Track) import UI.Page exposing (Page) +import User.Layer @@ -28,10 +28,10 @@ type Reply ----------------------------------------- -- Authentication ----------------------------------------- - | ExternalAuth Authentication.Method String + | ExternalAuth User.Layer.Method String | PingIpfsForAuth | PingTextileForAuth - | ShowUpdateEncryptionKeyScreen Authentication.Method + | ShowUpdateEncryptionKeyScreen User.Layer.Method | SignOut ----------------------------------------- -- Context Menu diff --git a/src/Applications/UI/Settings.elm b/src/Applications/UI/Settings.elm index a08546fd..260465d7 100644 --- a/src/Applications/UI/Settings.elm +++ b/src/Applications/UI/Settings.elm @@ -1,6 +1,5 @@ module UI.Settings exposing (Dependencies, view) -import Authentication exposing (Method(..)) import Chunky exposing (..) import Color.Ext as Color import Conditional exposing (ifThenElse) @@ -12,6 +11,7 @@ import Html.Styled.Events exposing (onClick) import Html.Styled.Lazy import Material.Icons.Action as Icons import Material.Icons.Communication as Icons +import Settings exposing (Settings) import String.Ext as String import Tachyons.Classes as T import UI.Backdrop as Backdrop @@ -22,6 +22,7 @@ import UI.Page as Page import UI.Reply exposing (Reply(..)) import UI.Settings.ImportExport import UI.Settings.Page as Settings exposing (..) +import User.Layer exposing (Method(..)) @@ -29,7 +30,7 @@ import UI.Settings.Page as Settings exposing (..) type alias Dependencies = - { authenticationMethod : Maybe Authentication.Method + { authenticationMethod : Maybe User.Layer.Method , chosenBackgroundImage : Maybe String , hideDuplicateTracks : Bool } @@ -161,7 +162,7 @@ label l = -- AUTHENTICATION -changePassphrase : Authentication.Method -> Html Reply +changePassphrase : User.Layer.Method -> Html Reply changePassphrase method = inline [] diff --git a/src/Applications/UI/Tracks.elm b/src/Applications/UI/Tracks.elm index 42f72d8c..2539c1c5 100644 --- a/src/Applications/UI/Tracks.elm +++ b/src/Applications/UI/Tracks.elm @@ -1,7 +1,6 @@ module UI.Tracks exposing (Dependencies, Model, Msg(..), Scene(..), importHypaethral, initialModel, update, view) import Alien -import Authentication exposing (HypaethralUserData) import Chunky exposing (..) import Classes as C import Color exposing (Color) @@ -50,6 +49,7 @@ import UI.Queue.Page import UI.Reply as UI exposing (Reply(..)) import UI.Tracks.Reply as Tracks exposing (Reply(..)) import UI.Tracks.Scene.List +import User.Layer exposing (HypaethralData) @@ -426,7 +426,7 @@ update msg model = ) -importHypaethral : Model -> HypaethralUserData -> Maybe Playlist -> Return Model Msg UI.Reply +importHypaethral : Model -> HypaethralData -> Maybe Playlist -> Return Model Msg UI.Reply importHypaethral model data selectedPlaylist = let adjustedModel = diff --git a/src/Javascript/Workers/Brain/user.js b/src/Javascript/Workers/Brain/user.js index 2c802684..97f97cb1 100644 --- a/src/Javascript/Workers/Brain/user.js +++ b/src/Javascript/Workers/Brain/user.js @@ -8,6 +8,23 @@ const SECRET_KEY_LOCATION = "AUTH_SECRET_KEY" +// Crypto +// ====== + +app.ports.fabricateSecretKey.subscribe(event => { + keyFromPassphrase(event.data) + .then(data => toCache(SECRET_KEY_LOCATION, data)) + .then(_ => { + app.ports.fromAlien.send({ + tag: event.tag, + data: null, + error: null + }) + }) + .catch(reportError(event)) +}) + + // Blockstack // ---------- @@ -92,47 +109,29 @@ app.ports.requestBlockstack.subscribe(event => { const session = bl0ckst4ck() bl - .getFile("diffuse.json") + .getFile(event.data.file) .then( sendJsonData(event) ) .catch( reportError(event) ) }) app.ports.toBlockstack.subscribe(event => { - const json = JSON.stringify(event.data) + const json = JSON.stringify(event.data.data) const session = bl0ckst4ck() bl - .putFile("diffuse.json", json) + .putFile(event.data.file, json) .catch( reportError(event) ) }) -// Crypto -// ------ - -app.ports.fabricateSecretKey.subscribe(event => { - keyFromPassphrase(event.data) - .then(data => toCache(SECRET_KEY_LOCATION, data)) - .then(_ => { - app.ports.fromAlien.send({ - tag: event.tag, - data: null, - error: null - }) - }) - .catch(reportError(event)) -}) - - - // Dropbox // ------- app.ports.requestDropbox.subscribe(event => { const params = { - path: "/diffuse.json" + path: "/" + event.data.file } const dataPromise = @@ -159,7 +158,7 @@ app.ports.toDropbox.subscribe(event => { const json = JSON.stringify(event.data.data) const reporter = reportError(event) const params = { - path: "/diffuse.json", + path: "/" + event.data.file, mode: "overwrite", mute: true } @@ -190,19 +189,9 @@ app.ports.toDropbox.subscribe(event => { const IPFS_ROOT = "/Applications/Diffuse/" -function ipfsFilePath(tag) { - return IPFS_ROOT + (_ => { - switch (tag) { - case "AUTH_IPFS": return "Data.json" - default: return tag - } - })() -} - - app.ports.requestIpfs.subscribe(event => { const apiOrigin = event.data.apiOrigin - const path = ipfsFilePath(event.tag) + const path = IPFS_ROOT + event.data.file fetch(apiOrigin + "/api/v0/files/read?arg=" + path) .then(r => r.ok ? r.text() : r.json()) @@ -217,7 +206,7 @@ app.ports.toIpfs.subscribe(event => { const apiOrigin = event.data.apiOrigin const json = JSON.stringify(event.data.data) const params = new URLSearchParams({ - arg: ipfsFilePath(event.tag), + arg: IPFS_ROOT + event.data.file, create: true, offset: 0, parents: true, @@ -291,7 +280,7 @@ app.ports.requestRemoteStorage.subscribe(event => { isOffline ? fromCache(event.tag) : remoteStorage(event) - .then(_ => rsClient.getFile("diffuse.json")) + .then(_ => rsClient.getFile(event.data.file)) .then(r => r.data) .then(decryptWithSecretKey) @@ -308,7 +297,7 @@ app.ports.toRemoteStorage.subscribe(event => { !isOffline && remoteStorage(event) .then(doEncryption) - .then(data => rsClient.storeFile("application/json", "diffuse.json", data)) + .then(data => rsClient.storeFile("application/json", event.data.file, data)) .catch( reportError(event) ) toCache(event.tag, event.data.data) @@ -339,7 +328,7 @@ app.ports.requestTextile.subscribe(event => { Textile.ensureThread (apiOrigin) - .then(_ => Textile.getFile(apiOrigin)) + .then(_ => Textile.getFile(apiOrigin, event.data.file)) .then(f => f ? Textile.readFile(apiOrigin, f) : null) .then( sendJsonData(event) ) @@ -358,7 +347,7 @@ app.ports.toTextile.subscribe(event => { .then(_ => Textile.getFile(apiOrigin)) .then(f => f ? Textile.deleteBlock(apiOrigin, f) : null) - .then(_ => Textile.useMill(apiOrigin, json)) + .then(_ => Textile.useMill(apiOrigin, event.data.file, json)) .then(m => Textile.addFileToThread(apiOrigin, m)) .catch( reportError(event) ) diff --git a/src/Javascript/Workers/brain.js b/src/Javascript/Workers/brain.js index 0843507d..bb02129c 100644 --- a/src/Javascript/Workers/brain.js +++ b/src/Javascript/Workers/brain.js @@ -56,14 +56,22 @@ app.ports.removeCache.subscribe(event => { app.ports.requestCache.subscribe(event => { - fromCache(event.tag) + const key = event.data && event.data.file + ? event.tag + "_" + event.data.file + : event.tag + + fromCache(key) .then( sendData(event) ) .catch( reportError(event) ) }) app.ports.toCache.subscribe(event => { - toCache(event.tag, event.data) + const key = event.data && event.data.file + ? event.tag + "_" + event.data.file + : event.tag + + toCache(key, event.data.data || event.data) .catch( reportError(event) ) }) diff --git a/src/Javascript/textile.js b/src/Javascript/textile.js index f3ca33fb..c2840c59 100644 --- a/src/Javascript/textile.js +++ b/src/Javascript/textile.js @@ -5,8 +5,7 @@ // Communicating with the Textile HTTP API. -const TEXTILE_THREAD = "diffuse" -const TEXTILE_BLOCK = "userdata" +const TEXTILE_THREAD = "Diffuse" const TEXTILE_SCHEMA = { name: TEXTILE_THREAD, pin: true, @@ -98,7 +97,7 @@ Textile.addFileToThread = (apiOrigin, millResult) => { } -Textile.getFile = (apiOrigin) => { +Textile.getFile = (apiOrigin, file_name) => { const headers = new Headers() headers.append("X-Textile-Opts", "thread=" + Textile.activeThreadId) @@ -107,7 +106,7 @@ Textile.getFile = (apiOrigin) => { method: "GET" }) .then(r => r.json()) - .then(r => r.items.find(i => i.files[0].file.name === TEXTILE_BLOCK)) + .then(r => r.items.find(i => i.files[0].file.name === file_name)) } @@ -140,9 +139,9 @@ Textile.createSchema = (apiOrigin) => { } -Textile.useMill = (apiOrigin, data) => { +Textile.useMill = (apiOrigin, file_name, data) => { const blob = new Blob([data], { type : "application/json" }) - const file = new File([blob], TEXTILE_BLOCK) + const file = new File([blob], file_name) const formData = new FormData() formData.append("file", file) diff --git a/src/Library/Settings.elm b/src/Library/Settings.elm new file mode 100644 index 00000000..85bad17a --- /dev/null +++ b/src/Library/Settings.elm @@ -0,0 +1,39 @@ +module Settings exposing (Settings, decoder, encode) + +import Json.Decode as Json +import Json.Decode.Pipeline exposing (optional) +import Json.Encode +import Maybe.Extra as Maybe + + + +-- 🌳 + + +type alias Settings = + { backgroundImage : Maybe String + , hideDuplicates : Bool + } + + + +-- 🔱 + + +encode : Settings -> Json.Value +encode settings = + Json.Encode.object + [ ( "backgroundImage" + , Maybe.unwrap Json.Encode.null Json.Encode.string settings.backgroundImage + ) + , ( "hideDuplicates" + , Json.Encode.bool settings.hideDuplicates + ) + ] + + +decoder : Json.Decoder Settings +decoder = + Json.succeed Settings + |> optional "backgroundImage" (Json.maybe Json.string) Nothing + |> optional "hideDuplicates" Json.bool False diff --git a/src/Library/Authentication.elm b/src/Library/User/Layer.elm similarity index 51% rename from src/Library/Authentication.elm rename to src/Library/User/Layer.elm index 30aa11a4..b66fda6e 100644 --- a/src/Library/Authentication.elm +++ b/src/Library/User/Layer.elm @@ -1,5 +1,21 @@ -module Authentication exposing (EnclosedUserData, HypaethralUserData, Method(..), Settings, decodeEnclosed, decodeHypaethral, decodeMethod, emptyHypaethralUserData, enclosedDecoder, encodeEnclosed, encodeHypaethral, encodeMethod, encodeSettings, hypaethralDecoder, methodFromString, methodToString, settingsDecoder) +module User.Layer exposing (EnclosedData, HypaethralBit(..), HypaethralData, Method(..), decodeEnclosedData, decodeHypaethralData, decodeMethod, emptyHypaethralData, enclosedDataDecoder, encodeEnclosedData, encodeHypaethralBit, encodeHypaethralData, encodeMethod, hypaethralBit, hypaethralBitFileName, hypaethralBitKey, hypaethralDataDecoder, methodFromString, methodSeparator, methodToString, putHypaethralJsonBitsTogether) +{-| User Layer. + +This concerns data that relates to the app, +controlled by the user and stored by the user. + +**Enclosed** data is data like, the enable-shuffle setting, +equalizer settings, or the currently-active-search term. +Which is stored in the browser. + +**Hypaethral** data is data like, the user's favourites, +processed tracks, or the user's sources. +Which is stored in the location chosen by the user. + +-} + +import Enum exposing (Enum) import Equalizer import Json.Decode as Json import Json.Decode.Ext as Json @@ -8,6 +24,7 @@ import Json.Encode import Maybe.Extra as Maybe import Playlists import Playlists.Encoding as Playlists +import Settings import Sources import Sources.Encoding as Sources import Tracks @@ -27,7 +44,11 @@ type Method | Textile { apiOrigin : String } -type alias EnclosedUserData = + +-- 🌳 ░░ ENCLOSED + + +type alias EnclosedData = { cachedTracks : List String , equalizerSettings : Equalizer.Settings , grouping : Maybe Tracks.Grouping @@ -42,21 +63,27 @@ type alias EnclosedUserData = } -type alias HypaethralUserData = + +-- 🌳 ░░ HYPAETHRAL + + +type HypaethralBit + = Favourites + | Playlists + | Settings + | Sources + | Tracks + + +type alias HypaethralData = { favourites : List Tracks.Favourite , playlists : List Playlists.Playlist - , settings : Maybe Settings + , settings : Maybe Settings.Settings , sources : List Sources.Source , tracks : List Tracks.Track } -type alias Settings = - { backgroundImage : Maybe String - , hideDuplicates : Bool - } - - -- 🔱 ░░ METHOD @@ -144,14 +171,14 @@ methodSeparator = -- 🔱 ░░ ENCLOSED -decodeEnclosed : Json.Value -> Result Json.Error EnclosedUserData -decodeEnclosed = - Json.decodeValue enclosedDecoder +decodeEnclosedData : Json.Value -> Result Json.Error EnclosedData +decodeEnclosedData = + Json.decodeValue enclosedDataDecoder -enclosedDecoder : Json.Decoder EnclosedUserData -enclosedDecoder = - Json.succeed EnclosedUserData +enclosedDataDecoder : Json.Decoder EnclosedData +enclosedDataDecoder = + Json.succeed EnclosedData |> optional "cachedTracks" (Json.list Json.string) [] |> optional "equalizerSettings" Equalizer.settingsDecoder Equalizer.defaultSettings |> optional "grouping" (Json.maybe Tracks.groupingDecoder) Nothing @@ -165,8 +192,8 @@ enclosedDecoder = |> optional "sortDirection" Tracks.sortDirectionDecoder Tracks.Asc -encodeEnclosed : EnclosedUserData -> Json.Value -encodeEnclosed { cachedTracks, equalizerSettings, grouping, onlyShowCachedTracks, onlyShowFavourites, repeat, searchTerm, selectedPlaylist, shuffle, sortBy, sortDirection } = +encodeEnclosedData : EnclosedData -> Json.Value +encodeEnclosedData { cachedTracks, equalizerSettings, grouping, onlyShowCachedTracks, onlyShowFavourites, repeat, searchTerm, selectedPlaylist, shuffle, sortBy, sortDirection } = Json.Encode.object [ ( "cachedTracks", Json.Encode.list Json.Encode.string cachedTracks ) , ( "equalizerSettings", Equalizer.encodeSettings equalizerSettings ) @@ -186,13 +213,13 @@ encodeEnclosed { cachedTracks, equalizerSettings, grouping, onlyShowCachedTracks -- 🔱 ░░ HYPAETHRAL -decodeHypaethral : Json.Value -> Result Json.Error HypaethralUserData -decodeHypaethral = - Json.decodeValue hypaethralDecoder +decodeHypaethralData : Json.Value -> Result Json.Error HypaethralData +decodeHypaethralData = + Json.decodeValue hypaethralDataDecoder -emptyHypaethralUserData : HypaethralUserData -emptyHypaethralUserData = +emptyHypaethralData : HypaethralData +emptyHypaethralData = { favourites = [] , playlists = [] , settings = Nothing @@ -201,41 +228,83 @@ emptyHypaethralUserData = } -encodeHypaethral : HypaethralUserData -> Json.Value -encodeHypaethral { favourites, playlists, settings, sources, tracks } = +encodeHypaethralBit : HypaethralBit -> HypaethralData -> Json.Value +encodeHypaethralBit bit { favourites, playlists, settings, sources, tracks } = + case bit of + Favourites -> + Json.Encode.list Tracks.encodeFavourite favourites + + Playlists -> + Json.Encode.list Playlists.encode playlists + + Settings -> + Maybe.unwrap Json.Encode.null Settings.encode settings + + Sources -> + Json.Encode.list Sources.encode sources + + Tracks -> + Json.Encode.list Tracks.encodeTrack tracks + + +encodeHypaethralData : HypaethralData -> Json.Value +encodeHypaethralData data = Json.Encode.object - [ ( "favourites", Json.Encode.list Tracks.encodeFavourite favourites ) - , ( "playlists", Json.Encode.list Playlists.encode playlists ) - , ( "settings", Maybe.unwrap Json.Encode.null encodeSettings settings ) - , ( "sources", Json.Encode.list Sources.encode sources ) - , ( "tracks", Json.Encode.list Tracks.encodeTrack tracks ) + [ ( hypaethralBitKey Favourites, encodeHypaethralBit Favourites data ) + , ( hypaethralBitKey Playlists, encodeHypaethralBit Playlists data ) + , ( hypaethralBitKey Settings, encodeHypaethralBit Settings data ) + , ( hypaethralBitKey Sources, encodeHypaethralBit Sources data ) + , ( hypaethralBitKey Tracks, encodeHypaethralBit Tracks data ) ] -encodeSettings : Settings -> Json.Value -encodeSettings settings = - Json.Encode.object - [ ( "backgroundImage" - , Maybe.unwrap Json.Encode.null Json.Encode.string settings.backgroundImage - ) - , ( "hideDuplicates" - , Json.Encode.bool settings.hideDuplicates - ) +hypaethralBit : Enum HypaethralBit +hypaethralBit = + Enum.create + [ ( hypaethralBitKey Favourites, Favourites ) + , ( hypaethralBitKey Playlists, Playlists ) + , ( hypaethralBitKey Settings, Settings ) + , ( hypaethralBitKey Sources, Sources ) + , ( hypaethralBitKey Tracks, Tracks ) ] -hypaethralDecoder : Json.Decoder HypaethralUserData -hypaethralDecoder = - Json.succeed HypaethralUserData - |> optional "favourites" (Json.listIgnore Tracks.favouriteDecoder) [] - |> optional "playlists" (Json.listIgnore Playlists.decoder) [] - |> optional "settings" (Json.maybe settingsDecoder) Nothing - |> optional "sources" (Json.listIgnore Sources.decoder) [] - |> optional "tracks" (Json.listIgnore Tracks.trackDecoder) [] +hypaethralBitFileName : HypaethralBit -> String +hypaethralBitFileName bit = + hypaethralBitKey bit ++ ".json" + + +hypaethralBitKey : HypaethralBit -> String +hypaethralBitKey bit = + case bit of + Favourites -> + "favourites" + + Playlists -> + "playlists" + + Settings -> + "settings" + + Sources -> + "sources" + + Tracks -> + "tracks" + + +hypaethralDataDecoder : Json.Decoder HypaethralData +hypaethralDataDecoder = + Json.succeed HypaethralData + |> optional (hypaethralBitKey Favourites) (Json.listIgnore Tracks.favouriteDecoder) [] + |> optional (hypaethralBitKey Playlists) (Json.listIgnore Playlists.decoder) [] + |> optional (hypaethralBitKey Settings) (Json.maybe Settings.decoder) Nothing + |> optional (hypaethralBitKey Sources) (Json.listIgnore Sources.decoder) [] + |> optional (hypaethralBitKey Tracks) (Json.listIgnore Tracks.trackDecoder) [] -settingsDecoder : Json.Decoder Settings -settingsDecoder = - Json.succeed Settings - |> optional "backgroundImage" (Json.maybe Json.string) Nothing - |> optional "hideDuplicates" Json.bool False +putHypaethralJsonBitsTogether : List ( HypaethralBit, Json.Value ) -> Json.Value +putHypaethralJsonBitsTogether bits = + bits + |> List.map (Tuple.mapFirst hypaethralBitKey) + |> Json.Encode.object diff --git a/src/Library/Authentication/RemoteStorage.elm b/src/Library/User/Layer/Methods/RemoteStorage.elm similarity index 75% rename from src/Library/Authentication/RemoteStorage.elm rename to src/Library/User/Layer/Methods/RemoteStorage.elm index e3a2d8aa..efc5db66 100644 --- a/src/Library/Authentication/RemoteStorage.elm +++ b/src/Library/User/Layer/Methods/RemoteStorage.elm @@ -1,4 +1,4 @@ -module Authentication.RemoteStorage exposing (RemoteStorage, oauthAddress, parseUserAddress, userAddressError, webfingerAddress, webfingerDecoder, webfingerError, webfingerRequest) +module User.Layer.Methods.RemoteStorage exposing (Attributes, oauthAddress, parseUserAddress, userAddressError, webfingerAddress, webfingerDecoder, webfingerError, webfingerRequest) import Base64 import Http @@ -10,7 +10,7 @@ import Url -- 🌳 -type alias RemoteStorage = +type alias Attributes = { host : String , username : String } @@ -28,7 +28,7 @@ webfingerError = -- 🔱 -parseUserAddress : String -> Maybe RemoteStorage +parseUserAddress : String -> Maybe Attributes parseUserAddress str = case String.split "@" str of [ u, h ] -> @@ -38,7 +38,7 @@ parseUserAddress str = Nothing -oauthAddress : { oauthOrigin : String, origin : String } -> RemoteStorage -> String +oauthAddress : { oauthOrigin : String, origin : String } -> Attributes -> String oauthAddress { oauthOrigin, origin } { host, username } = let ua = @@ -55,7 +55,7 @@ oauthAddress { oauthOrigin, origin } { host, username } = ] -webfingerAddress : RemoteStorage -> String +webfingerAddress : Attributes -> String webfingerAddress { host, username } = "https://" ++ host ++ "/.well-known/webfinger?resource=acct:" ++ username @@ -71,7 +71,7 @@ webfingerDecoder = Decode.string -webfingerRequest : (RemoteStorage -> Result Http.Error String -> msg) -> RemoteStorage -> Cmd msg +webfingerRequest : (Attributes -> Result Http.Error String -> msg) -> Attributes -> Cmd msg webfingerRequest toMsg rs = Http.get { url = webfingerAddress rs -- knotmirror 0.0.1