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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643module UI.Syncing.State exposing (..)
import Alienimport Base64import Binaryimport Browser.Navigation as Navimport Commonimport Coordinatesimport Dictimport Htmlimport Html.Attributesimport Html.Events.Extra.Mouse as Mouseimport Httpimport Http.Ext as Httpimport Json.Decode as Jsonimport Json.Encodeimport Lens.Ext as Lensimport Managementimport Maybe.Extra as Maybeimport Monocle.Lens exposing (Lens)import Notificationsimport Return exposing (andThen, return)import SHAimport String.Ext as Stringimport Svgimport Timeimport UI.Backdrop as Backdropimport UI.Common.State as Common exposing (showNotification, showNotificationWithModel)import UI.Ports as Portsimport UI.Sources.State as Sourcesimport UI.Svg.Elementsimport UI.Syncing.ContextMenu as Syncingimport UI.Syncing.Types as Syncing exposing (..)import UI.Types as UI exposing (..)import Url exposing (Protocol(..), Url)import Url.Ext as Urlimport UrlBase64import User.Layer exposing (..)import User.Layer.Methods.Dropbox as Dropboximport User.Layer.Methods.RemoteStorage as RemoteStorage
-- ⛩
minimumPassphraseLength : IntminimumPassphraseLength = 16
passphraseLengthErrorMessage : StringpassphraseLengthErrorMessage = "Your passphrase should be atleast *16 characters* long."
-- 🌳
initialModel : Url -> Syncing.StateinitialModel url = case Url.action url of [ "authenticate", "remotestorage", encodedUserAddress ] -> let dict = Url.queryDictionary { url | query = url.fragment }
userAddress = encodedUserAddress |> Url.percentDecode |> Maybe.andThen (UrlBase64.decode Base64.decode >> Result.toMaybe) |> Maybe.withDefault encodedUserAddress in case Dict.get "access_token" dict of Just t -> NewEncryptionKeyScreen (RemoteStorage { userAddress = userAddress , token = t } ) Nothing
Nothing -> NotSynced
_ -> NotSynced
initialCommand : Url -> Cmd Syncing.MsginitialCommand url = case Url.action url of [ "authenticate", "dropbox" ] -> case Dict.get "code" (Url.queryDictionary url) of Just code -> Dropbox.exchangeAuthCode ExchangeDropboxAuthCode url code
_ -> Cmd.none
_ -> Cmd.none
lens : Lens UI.Model Syncing.Statelens = { get = .syncing , set = \a m -> { m | syncing = a } }
-- 📣
update : Syncing.Msg -> Managerupdate msg = case msg of Syncing.Bypass -> Return.singleton
ActivateSync a -> activateSync a
ActivateSyncWithPassphrase a b -> activateSyncWithPassphrase a b
BootFailure a -> bootFailure a
ExchangeDropboxAuthCode a -> exchangeDropboxAuthCode a
GotSyncMethod a -> gotSyncMethod a
RemoteStorageWebfinger a b -> remoteStorageWebfinger a b
ShowSyncDataMenu a -> showSyncDataMenu a
StartedSyncing a -> startedSyncing a
StopSync -> stopSync
TriggerExternalAuth a b -> externalAuth a b
----------------------------------------- -- Encryption ----------------------------------------- KeepPassphraseInMemory a -> keepPassphraseInMemory a
NeedEncryptionKey a -> needEncryptionKey a
RemoveEncryptionKey a -> removeEncryptionKey a
ShowNewEncryptionKeyScreen a -> showNewEncryptionKeyScreen a
ShowUpdateEncryptionKeyScreen a -> showUpdateEncryptionKeyScreen a
UpdateEncryptionKey a b -> updateEncryptionKey a b
----------------------------------------- -- IPFS ----------------------------------------- PingIpfs -> pingIpfs
PingIpfsCallback a -> pingIpfsCallback a
PingOtherIpfs a -> pingOtherIpfs a
PingOtherIpfsCallback a b -> pingOtherIpfsCallback a b
----------------------------------------- -- More Input ----------------------------------------- AskForInput a b -> askForInput a b
CancelInput -> cancelInput
ConfirmInput -> confirmInput
Input a -> input a
organize : Organizer Syncing.State -> Managerorganize = Management.organize lens
replaceState : Syncing.State -> ManagerreplaceState state = lens.set state >> Return.singleton
-- 🔱
activateSync : Method -> ManageractivateSync method model = [ ( "method", encodeMethod method ) , ( "passphrase", Json.Encode.null ) ] |> Json.Encode.object |> Alien.broadcast Alien.SetSyncMethod |> Ports.toBrain -- |> return model
activateSyncWithPassphrase : Method -> String -> ManageractivateSyncWithPassphrase method passphrase model = if String.length passphrase < minimumPassphraseLength then passphraseLengthErrorMessage |> Notifications.error |> Common.showNotificationWithModel model
else [ ( "method", encodeMethod method ) , ( "passphrase", Json.Encode.string <| hashPassphrase passphrase ) ] |> Json.Encode.object |> Alien.broadcast Alien.SetSyncMethod |> Ports.toBrain -- |> return model
bootFailure : String -> ManagerbootFailure err model = model |> showNotification (Notifications.error err) |> andThen Backdrop.setDefault
externalAuth : Method -> String -> ManagerexternalAuth method string model = case method of Dropbox _ -> [ ( "client_id", Dropbox.clientId ) , ( "redirect_uri", Dropbox.redirectUri model.url ) , ( "response_type", "code" ) , ( "token_access_type", "offline" ) ] |> Common.queryString |> String.append "https://www.dropbox.com/oauth2/authorize" |> Nav.load |> return model
RemoteStorage _ -> string |> RemoteStorage.parseUserAddress |> Maybe.map (RemoteStorage.webfingerRequest RemoteStorageWebfinger model.url.protocol) |> Maybe.map (Cmd.map SyncingMsg) |> Maybe.unwrap (RemoteStorage.userAddressError |> Notifications.error |> Common.showNotificationWithModel model ) (return model)
_ -> Return.singleton model
exchangeDropboxAuthCode : Result Http.Error Dropbox.Tokens -> ManagerexchangeDropboxAuthCode result model = case result of Ok tokens -> case tokens.refreshToken of Just refreshToken -> Nothing |> NewEncryptionKeyScreen (Dropbox { accessToken = tokens.accessToken , expiresAt = Time.posixToMillis model.currentTime // 1000 + tokens.expiresIn , refreshToken = refreshToken } ) |> Lens.replace lens model |> Return.singleton
Nothing -> "Missing refresh token in Dropbox code exchange flow." |> Notifications.stickyError |> showNotificationWithModel (Lens.replace lens model NotSynced)
Err err -> [] |> Notifications.errorWithCode "Failed to authenticate with Dropbox" (Http.errorToString err) |> showNotificationWithModel (Lens.replace lens model NotSynced)
gotSyncMethod : Json.Value -> ManagergotSyncMethod json model = let afterwards a = andThen (\m -> if m.processAutomatically then Sources.process m
else Return.singleton m ) (case model.syncing of Syncing { notificationId } -> Common.dismissNotification { id = notificationId } a
_ -> Return.singleton a ) in -- 🧠 told me which auth method we're using, -- so we can tell the user in the UI. case decodeMethod json of Just method -> model |> replaceState (Synced method) |> andThen afterwards
Nothing -> afterwards model
remoteStorageWebfinger : RemoteStorage.Attributes -> Result Http.Error String -> ManagerremoteStorageWebfinger remoteStorage result model = case result of Ok oauthOrigin -> let origin = Common.urlOrigin model.url in remoteStorage |> RemoteStorage.oauthAddress { oauthOrigin = oauthOrigin , origin = origin } |> Nav.load |> return model
Err _ -> RemoteStorage.webfingerError |> Notifications.error |> showNotificationWithModel model
showSyncDataMenu : Mouse.Event -> ManagershowSyncDataMenu mouseEvent model = mouseEvent.clientPos |> Coordinates.fromTuple |> Syncing.syncDataMenu |> Common.showContextMenuWithModel model
startedSyncing : Json.Value -> ManagerstartedSyncing json = -- 🧠 started syncing case decodeMethod json of Just method -> Common.showSyncingNotification method
Nothing -> Return.singleton
stopSync : ManagerstopSync model = Alien.UnsetSyncMethod |> Alien.trigger |> Ports.toBrain |> return model |> andThen (replaceState NotSynced)
-- ENCRYPTION
keepPassphraseInMemory : String -> ManagerkeepPassphraseInMemory passphrase model = (\state -> case state of NewEncryptionKeyScreen method _ -> NewEncryptionKeyScreen method (Just passphrase)
UpdateEncryptionKeyScreen method _ -> UpdateEncryptionKeyScreen method (Just passphrase)
s -> s ) |> Lens.adjust lens model |> Return.singleton
needEncryptionKey : { error : String } -> ManagerneedEncryptionKey { error } model = (case lens.get model of Syncing { notificationId } -> Common.dismissNotification { id = notificationId } model
m -> replaceState m model ) |> andThen (error |> Notifications.stickyError |> Common.showNotification ) |> andThen stopSync
removeEncryptionKey : Method -> ManagerremoveEncryptionKey method model = Alien.RemoveEncryptionKey |> Alien.trigger |> Ports.toBrain -- |> return (lens.set (Synced method) model) |> andThen ("Saving data without encryption ..." |> Notifications.success |> Common.showNotification ) |> andThen Common.forceTracksRerender
showNewEncryptionKeyScreen : Method -> ManagershowNewEncryptionKeyScreen method = replaceState (NewEncryptionKeyScreen method Nothing)
showUpdateEncryptionKeyScreen : Method -> ManagershowUpdateEncryptionKeyScreen method = replaceState (UpdateEncryptionKeyScreen method Nothing)
updateEncryptionKey : Method -> String -> ManagerupdateEncryptionKey method passphrase model = if String.length passphrase < minimumPassphraseLength then passphraseLengthErrorMessage |> Notifications.error |> Common.showNotificationWithModel model
else passphrase |> hashPassphrase |> Json.Encode.string |> Alien.broadcast Alien.UpdateEncryptionKey |> Ports.toBrain -- |> return (lens.set (Synced method) model) |> andThen ("Encrypting data with new passphrase ..." |> Notifications.success |> Common.showNotification ) |> andThen Common.forceTracksRerender
-- IPFS
pingIpfs : ManagerpingIpfs model = case model.url.protocol of Https -> """ Unfortunately the local IPFS API doesn't work with HTTPS. Install the [IPFS Companion](https://github.com/ipfs-shipyard/ipfs-companion#release-channel) browser extension to get around this issue (and make sure it redirects to the local gateway). """ |> Notifications.error |> Common.showNotificationWithModel model
Http -> { url = "//localhost:5001/api/v0/id" , expect = Http.expectWhatever (SyncingMsg << PingIpfsCallback) , body = Http.emptyBody } |> Http.post |> return model
pingIpfsCallback : Result Http.Error () -> ManagerpingIpfsCallback result = case result of Ok _ -> { apiOrigin = "//localhost:5001" } |> Ipfs |> showNewEncryptionKeyScreen
Err _ -> askForInput (Ipfs { apiOrigin = "" }) { icon = \size _ -> Svg.map never (UI.Svg.Elements.ipfsLogo size) , placeholder = "//localhost:5001" , question = { question = "Where's your IPFS API located?" , info = [ Html.text "You can find this address on the IPFS Web UI." , Html.br [] [] , Html.text "Most likely you'll also need to setup CORS." , Html.br [] [] , Html.text "You can find the instructions for that " , Html.a [ Html.Attributes.class "border-b border-current-color font-semibold inline-block leading-tight" , Html.Attributes.href "about/cors/#CORS__IPFS" , Html.Attributes.target "_blank" ] [ Html.text "here" ] ] } , value = "//localhost:5001" }
pingOtherIpfs : String -> ManagerpingOtherIpfs origin model = { url = origin ++ "/api/v0/id" , expect = Http.expectWhatever (SyncingMsg << PingOtherIpfsCallback origin) , body = Http.emptyBody } |> Http.post |> return model
pingOtherIpfsCallback : String -> Result Http.Error () -> ManagerpingOtherIpfsCallback origin result = case result of Ok _ -> { apiOrigin = origin } |> Ipfs |> showNewEncryptionKeyScreen
Err _ -> "Can't reach this IPFS API, maybe it's offline? Or I don't have access?" |> Notifications.error |> Common.showNotification
-- MORE INPUT
askForInput : Method -> Question -> ManageraskForInput method question = question |> InputScreen method |> replaceState
cancelInput : ManagercancelInput model = case lens.get model of InputScreen _ _ -> replaceState NotSynced model
NewEncryptionKeyScreen _ _ -> replaceState NotSynced model
UpdateEncryptionKeyScreen method _ -> replaceState (Synced method) model
m -> replaceState m model
confirmInput : ManagerconfirmInput model = case lens.get model of InputScreen (Ipfs _) { value } -> pingOtherIpfs (String.chopEnd "/" value) model
InputScreen (RemoteStorage r) { value } -> externalAuth (RemoteStorage r) value model
_ -> Return.singleton model
input : String -> Managerinput string model = (\state -> case state of InputScreen method opts -> InputScreen method { opts | value = string }
s -> s ) |> Lens.adjust lens model |> Return.singleton
-- 🛠
hashPassphrase : String -> StringhashPassphrase phrase = phrase |> Binary.fromStringAsUtf8 |> SHA.sha256 |> Binary.toHex |> String.toLower