roon-api (empty) → 0.1.0.0
raw patch · 28 files changed
+5157/−0 lines, 28 filesdep +aesondep +asyncdep +base
Dependencies added: aeson, async, base, bytestring, containers, deepseq, directory, effectful, effectful-core, effectful-streamly, effectful-streamly-http, effectful-websockets, filepath, flatparse, network, roon-api, scientific, stm, streamly-bytestring, streamly-core, streamly-http, streamly-network-udp, streamly-websockets, tasty, tasty-bench, tasty-hunit, tasty-quickcheck, temporary, text, unix, vector
Files
- CHANGELOG.md +16/−0
- LICENSE +29/−0
- README.md +57/−0
- app/Main.hs +185/−0
- bench/Main.hs +356/−0
- roon-api.cabal +162/−0
- src/Roon/Browse.hs +449/−0
- src/Roon/Connection.hs +172/−0
- src/Roon/Discovery.hs +180/−0
- src/Roon/Effect/Moo.hs +300/−0
- src/Roon/Effect/TokenStore.hs +113/−0
- src/Roon/Effect/WebSocket.hs +136/−0
- src/Roon/Error.hs +36/−0
- src/Roon/Image.hs +189/−0
- src/Roon/Moo/Message.hs +251/−0
- src/Roon/Registry.hs +148/−0
- src/Roon/Service.hs +111/−0
- src/Roon/Transport.hs +686/−0
- test/Main.hs +26/−0
- test/Roon/BrowseSpec.hs +243/−0
- test/Roon/ConnectionSpec.hs +214/−0
- test/Roon/DiscoverySpec.hs +106/−0
- test/Roon/Effect/TokenStoreSpec.hs +51/−0
- test/Roon/Effect/WebSocketSpec.hs +165/−0
- test/Roon/ImageSpec.hs +153/−0
- test/Roon/Moo/MessageSpec.hs +163/−0
- test/Roon/Test/Server.hs +159/−0
- test/Roon/TransportSpec.hs +301/−0
+ CHANGELOG.md view
@@ -0,0 +1,16 @@+# Revision history for roon-api++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* MOO messages (`Roon.Moo.Message`), and requests and subscriptions over+ one WebSocket with keep-alive (`Roon.Effect.Moo`, `Roon.Effect.WebSocket`).+* Discovery of the Roon Servers of the local network (`Roon.Discovery`).+* Registration of an extension, its token kept from one run to the next+ (`Roon.Registry`, `Roon.Effect.TokenStore`, `Roon.Connection`).+* The transport service (`Roon.Transport`): zones and outputs, their+ changes, the queue, playback, seek, settings, volume and mute.+* The browse service (`Roon.Browse`): sessions, lists, the search for+ tracks, and the actions Roon offers on tracks, albums and playlists.+* Images over HTTP (`Roon.Image`).+* `roon-probe`, a program to try the library against a server.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,57 @@+# roon-api++A Haskell client library for the Roon extension API, built on+[Effectful](https://hackage.haskell.org/package/effectful) and+[Streamly](https://hackage.haskell.org/package/streamly-core).++This is an independent, unofficial implementation. It is not affiliated+with or endorsed by Roon Labs. The protocol was learnt from the public+reference implementation,+[node-roon-api](https://github.com/RoonLabs/node-roon-api); no code was+taken from it.++## Status++- [x] MOO message encoding and parsing+- [x] WebSocket transport with keep-alive+- [x] Extension registration and token persistence+- [x] Server discovery (SOOD)+- [x] Transport service (zones, queue, playback control)+- [x] Browse service (search, library navigation, play actions)+- [x] Images (over HTTP)++## Building++ cabal build all+ cabal test++To build against copies of the libraries this package is built on+([effectful-streamly](https://hackage.haskell.org/package/effectful-streamly),+[effectful-streamly-http](https://hackage.haskell.org/package/effectful-streamly-http),+[effectful-websockets](https://hackage.haskell.org/package/effectful-websockets),+[streamly-network-udp](https://hackage.haskell.org/package/streamly-network-udp)+and those under them) checked out next to this repository, pass+`--project-file=cabal.project.siblings`.++## Trying it against a server++ cabal run roon-probe -- [HOST [PORT]]++`roon-probe` connects to a Roon Server (by default `127.0.0.1`, port+`9330`), registers as an extension, prints what the server answers and lists+the zones.+The first time, it waits until you enable "roon-api probe" in Roon,+under Settings, Extensions. The token the server hands out is kept in+`$XDG_STATE_HOME/roon-api/`. With `ROON_TRACE=1`, it describes every+frame sent and received on stderr. `roon-probe discover` lists the Roon+Servers that answer on the local network.+`roon-probe browse HIERARCHY [TITLE...]` walks the library by the titles of+its items and prints the level reached, without playing anything.+`roon-probe image KEY FILE [HOST [PORT]]` writes the image of an image key+(as found in the traced frames) to a file.++Tested with GHC 9.8.4, 9.10.3 and 9.12.4, and against Roon Server 2.75.++## License++BSD-3-Clause. See [LICENSE](LICENSE).
+ app/Main.hs view
@@ -0,0 +1,185 @@+-- | @roon-probe@: connects to a Roon Server, registers as an extension and+-- prints what the server answers, then the zones. A smoke test for the+-- library against a real server.+module Main (main) where++import Data.ByteString qualified as BS (length)+import Data.Text (Text, intercalate, pack, stripPrefix, toCaseFold)+import Data.Text.Encoding (encodeUtf8)+import Data.Version (showVersion)+import Effectful (Eff, IOE, runEff, type (:>))+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Console.ByteString (Console, runConsole)+import Effectful.Console.ByteString qualified as C (putStrLn)+import Effectful.Environment (Environment, getArgs, getProgName, lookupEnv,+ runEnvironment)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.FileSystem (FileSystem, runFileSystem)+import Effectful.FileSystem.IO (stderr)+import Effectful.FileSystem.IO.ByteString (hPutStrLn, writeFile)+import Paths_roon_api (version)+import Prelude hiding (writeFile)+import Roon.Browse (BrowseResult (..), Hierarchy (..), Item (..), ItemHint (..),+ List (..), LoadResult (..), Navigation (..), Session (..),+ browse, load)+import Roon.Connection (withRoon)+import Roon.Discovery (Core (..), defaultDiscovery, discover)+import Roon.Effect.Moo (defaultRequestHandler, pingService, runMoo)+import Roon.Effect.TokenStore (defaultTokenFile, loadToken, runTokenStoreFile,+ saveToken)+import Roon.Effect.WebSocket (ServerAddress (..), localServer, runWebSocket,+ traceFrames)+import Roon.Error (RoonError)+import Roon.Image (Image (..), defaultImageLimits, fetchImage, fitWithin,+ runImageHttp)+import Roon.Registry (CoreInfo (coreId, displayName, displayVersion),+ ExtensionInfo (..),+ Registration (core, grantedServices, token), info,+ register)+import Roon.Transport (DisplayLines (..), NowPlaying (..), Zone (..), ZoneId,+ getZones)+import System.Exit (exitFailure)+import Text.Read (readMaybe)++main :: IO ()+main = do+ succeeded <- runEff . runConcurrent . runFileSystem . runConsole . runEnvironment $ program+ if succeeded then pure () else exitFailure++type Effects = '[Environment, Console, FileSystem, Concurrent, IOE]++-- | 'False' when the probe failed.+program :: Eff Effects Bool+program =+ getArgs >>= \case+ [] -> probe localServer+ ["discover"] -> do+ cores <- discover defaultDiscovery+ case cores of+ [] -> False <$ complain "No Roon Server answered."+ _ -> True <$ mapM_ (\core -> say (core.uniqueId <> " " <> maybe "" id core.name <> " " <> maybe "" id core.displayVersion <> " " <> pack core.address.host <> ":" <> pack (show core.address.port))) cores+ "browse" : name : path | Just hierarchy <- lookup name hierarchies -> explore localServer hierarchy (map pack path)+ ["image", key, file] -> saveImage localServer key file+ ["image", key, file, host] -> saveImage localServer {host} key file+ ["image", key, file, host, portText] | Just port <- readMaybe portText -> saveImage ServerAddress {host, port} key file+ [host] -> probe localServer {host}+ [host, portText] | Just port <- readMaybe portText -> probe ServerAddress {host, port}+ _ -> do+ name <- getProgName+ complain ("usage: " <> pack name <> " [HOST [PORT] | discover | image KEY FILE [HOST [PORT]] | browse HIERARCHY [TITLE...]] (default: 127.0.0.1 9330; ROON_TRACE=1 describes every frame; hierarchies: " <> intercalate ", " (map (pack . fst) hierarchies) <> ")")+ pure False++extension :: ExtensionInfo+extension =+ ExtensionInfo+ { extensionId = "io.github.guillaumedevolpiano.roon-api.probe"+ , displayName = "roon-api probe"+ , displayVersion = pack (showVersion version)+ , publisher = "roon-api"+ , email = "nobody@example.invalid"+ , website = Just "https://github.com/GuillaumedeVolpiano/roon-api"+ , requiredServices = ["com.roonlabs.transport:2", "com.roonlabs.browse:1"]+ , optionalServices = []+ , providedServices = [pingService]+ }++hierarchies :: [(String, Hierarchy)]+hierarchies =+ [ ("browse", Browse)+ , ("playlists", Playlists)+ , ("internet_radio", InternetRadio)+ , ("albums", Albums)+ , ("artists", Artists)+ , ("genres", Genres)+ , ("composers", Composers)+ , ("search", Search)+ ]++-- | Walk a hierarchy of the local server by the titles of its items and+-- print the level reached. For @search@ the first title is the text to+-- search for. @<@ goes back one level and @#KEY@ opens an item by its key. Nothing is played: an item that is an action is not opened.+explore :: ServerAddress -> Hierarchy -> [Text] -> Eff Effects Bool+explore address hierarchy path = do+ tokenFile <- defaultTokenFile extension.extensionId+ outcome <- runErrorNoCallStack @RoonError . runTokenStoreFile tokenFile . withRoon address extension $ \_ -> do+ let current = Session {hierarchy, multiSessionKey = Just "roon-probe"}+ (input, titles) = case (hierarchy, path) of+ (Search, query : rest) -> (Just query, rest)+ _ -> (Nothing, path)+ walk [] = pure Nothing+ -- "<" goes back one level; "#KEY" opens an item by its key, even+ -- one of an earlier level.+ walk ("<" : rest) = browse current (Nothing :: Maybe ZoneId) (Back 1) >> walk rest+ walk (wanted : rest)+ | Just key <- stripPrefix "#" wanted = browse current (Nothing :: Maybe ZoneId) (Select key) >>= \result -> case result of+ BrowseList _ -> walk rest+ other -> pure (Just ("opening the key " <> key <> " gave " <> pack (show other)))+ walk (wanted : rest) = do+ level <- load current 0 500+ case [item | item <- level.items, toCaseFold item.title == toCaseFold wanted] of+ Item {hint = Just Action} : _ -> pure (Just ("\"" <> wanted <> "\" is an action: not opened"))+ Item {itemKey = Just key} : _ -> browse current (Nothing :: Maybe ZoneId) (Select key) >> walk rest+ _ -> pure (Just ("no item titled \"" <> wanted <> "\" at this level"))+ _ <- browse current (Nothing :: Maybe ZoneId) (Top input)+ stopped <- walk titles+ level <- load current 0 40+ say (level.list.title <> maybe "" (" / " <>) level.list.subtitle <> ": " <> pack (show level.list.count) <> " items, level " <> pack (show level.list.level) <> maybe "" ((", hint " <>) . pack . show) level.list.hint)+ mapM_ (\item -> say (" " <> maybe "-" (pack . show) item.hint <> " | " <> item.title <> maybe "" (" | " <>) item.subtitle <> maybe "" (const " | image") item.imageKey <> maybe "" (const " | asks for input") item.inputPrompt <> maybe "" (" | #" <>) item.itemKey)) level.items+ pure stopped+ case outcome of+ Right Nothing -> pure True+ Right (Just problem) -> False <$ complain ("roon-probe: " <> problem)+ Left err -> False <$ complain ("roon-probe: " <> pack (show err))++-- | Fetch the image of a key, at most 1000 pixels wide and high, and write+-- it to a file.+saveImage :: ServerAddress -> String -> FilePath -> Eff Effects Bool+saveImage address key file = do+ outcome <- runErrorNoCallStack @RoonError (runImageHttp defaultImageLimits (fetchImage address (pack key) (fitWithin 1000)))+ case outcome of+ Left err -> False <$ complain ("roon-probe: " <> pack (show err))+ Right image -> do+ writeFile file image.bytes+ say (pack file <> ": " <> image.contentType <> ", " <> pack (show (BS.length image.bytes)) <> " bytes")+ pure True++probe :: ServerAddress -> Eff Effects Bool+probe address = do+ tokenFile <- defaultTokenFile extension.extensionId+ -- ROON_TRACE, when set, describes every frame on stderr.+ tracing <- maybe False (not . null) <$> lookupEnv "ROON_TRACE"+ let trace = if tracing then traceFrames 300 complain else id+ say ("Connecting to " <> pack address.host <> ":" <> pack (show address.port))+ outcome <-+ runErrorNoCallStack @RoonError . runTokenStoreFile tokenFile $+ runWebSocket address . trace . runMoo defaultRequestHandler $ do+ core <- info+ say ("Server: " <> core.displayName <> ", version " <> core.displayVersion)+ say ("Core id: " <> core.coreId)+ token <- loadToken core.coreId+ say $ case token of+ Just _ -> "Registering with the stored token"+ Nothing -> "Registering. Enable \"" <> extension.displayName <> "\" in Roon, under Settings, Extensions"+ registration <- register extension token+ saveToken registration.core.coreId registration.token+ say ("Registered. Token saved in " <> pack tokenFile)+ say $ case registration.grantedServices of+ [] -> "Granted services: none"+ services -> "Granted services: " <> intercalate ", " services+ zones <- getZones+ mapM_ (say . describe) zones+ case outcome of+ Right () -> pure True+ Left err -> False <$ complain ("roon-probe: " <> pack (show err))++describe :: Zone -> Text+describe zone =+ "Zone " <> zone.displayName <> " (" <> pack (show zone.state) <> ")" <> case zone.nowPlaying of+ Nothing -> ""+ Just playing -> ": " <> intercalate " / " (playing.threeLine.line1 : maybe [] pure playing.threeLine.line2 <> maybe [] pure playing.threeLine.line3)++say :: Console :> es => Text -> Eff es ()+say = C.putStrLn . encodeUtf8++complain :: FileSystem :> es => Text -> Eff es ()+complain = hPutStrLn stderr . encodeUtf8
+ bench/Main.hs view
@@ -0,0 +1,356 @@+-- | How fast the parsers of the hot paths are, against other ways to+-- write them: the header block of a MOO message, the head of an HTTP+-- response, and the JSON body of a list of zones. Measured with+-- tasty-bench; the checks at the end make sure the ways compared agree.+--+-- The zones come from the Roon Server of this machine when it answers.+module Main (main) where++import Control.Applicative ((<|>))+import Control.DeepSeq (force)+import Control.Exception (SomeException, try)+import Control.Monad (void)+import Data.Aeson (KeyValue ((.=)), Value (..), decodeStrict, object)+import Data.Aeson qualified as J (encode)+import Data.Aeson.Key (fromText)+import Data.Aeson.KeyMap qualified as JK (fromList, lookup)+import Data.Aeson.Types (parseEither, parseJSON)+import Data.ByteString (ByteString, breakSubstring, dropWhileEnd, pack,+ toStrict, unpack)+import Data.ByteString qualified as BS (break, concat, drop, dropWhile, length,+ map, take)+import Data.ByteString.Char8 qualified as BS8 (lines, map)+import Data.Char (chr, isDigit)+import Data.Functor.Identity (Identity (..))+import Data.List qualified as L (foldl')+import Data.Map.Strict (empty)+import Data.Scientific (scientific)+import Data.Text (Text, singleton)+import Data.Text.Encoding (decodeUtf8', decodeUtf8Lenient, encodeUtf8)+import Data.Vector qualified as V (fromList)+import Data.Word (Word8)+import Effectful (runEff)+import Effectful.Concurrent (runConcurrent)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.FileSystem (runFileSystem)+import FlatParse.Basic (Result (OK), anyAsciiDecimalInt, anyAsciiDecimalInteger,+ anyAsciiHexInt, anyWord8, byteString, byteStringOf,+ failed, isolate, runParser, skipMany, skipSatisfyAscii,+ skipSome, withByteString, word8)+import FlatParse.Basic qualified as FB (Parser, eof, many)+import Roon.Connection (withRoon)+import Roon.Effect.Moo (Reply (..), pingService, request)+import Roon.Effect.TokenStore (defaultTokenFile, runTokenStoreFile)+import Roon.Effect.WebSocket (localServer)+import Roon.Error (RoonError)+import Roon.Moo.Message (Body (..), MooMessage (..), RequestId (..), Verb (..))+import Roon.Moo.Message qualified as MM (encode, parse)+import Roon.Registry (ExtensionInfo (..))+import Roon.Transport (Zone)+import Streamly.Data.Array (toParserK)+import Streamly.Data.Array qualified as A (parse)+import Streamly.Data.Fold (toList)+import Streamly.Data.Parser (Parser, die, listEq, satisfy, takeWhile1)+import Streamly.Data.Parser qualified as P (dropWhile, eof, many, takeWhile)+import Streamly.Data.Stream (unfold)+import Streamly.Data.Stream qualified as S (parse)+import Streamly.Data.StreamK (fromPure)+import Streamly.External.ByteString (reader, toArray)+import Streamly.External.Network.HTTP.Wire (Response (..),+ readResponseHeadWithin,+ responseHead)+import Test.Tasty.Bench (bench, bgroup, defaultMain, nf, nfIO)+import Test.Tasty.HUnit (assertBool, testCase, (@?=))+import Text.Printf (printf)++main :: IO ()+main = do+ (source, zonesValue) <- zonesBody+ let zonesJson = toStrict (J.encode zonesValue)+ frame = MM.encode MooMessage {verb = Complete, name = "Success", requestId = RequestId "42", headers = empty, body = JsonBody zonesValue}+ block = BS.take (BS.length (fst (breakSubstring "\n\n" frame)) + 1) frame+ printf "Zones body: %s, %d bytes. MOO header block: %d bytes. HTTP head: %d bytes.\n\n" source (BS.length zonesJson) (BS.length block) (BS.length httpHead)+ defaultMain+ [ bgroup+ "MOO header block"+ [ bench "Streamly parser, monadic (as Roon.Moo.Message was)" (nf (run mooMonadic) block)+ , bench "Streamly parser, applicative" (nf (run mooApplicative) block)+ , bench "flatparse (as Roon.Moo.Message is)" (nf (flat mooFlat) block)+ , bench "ByteString splitting by hand (a floor, not a proposal)" (nf mooByHand block)+ ]+ , bgroup+ "MOO message, whole"+ [ bench "Roon.Moo.Message.parse" (nf (either (const Nothing) (Just . whole) . MM.parse) frame)+ ]+ , bgroup+ "HTTP response head"+ [ bench "streamly-http as it is (flatparse, through streamly-flatparse)" $+ nfIO (summary . fst <$> readResponseHeadWithin (Just 65536) (fromPure (toArray httpHead)))+ , bench "streamly-http as it was (Streamly parser over arrays, ParserK)" $+ nf (either (const Nothing) Just . runIdentity . A.parse (toParserK streamlyHead) . fromPure . toArray) httpHead+ , bench "the Streamly parser over a stream of bytes" (nf (run streamlyHead) httpHead)+ , bench "a flatparse parser written for this benchmark" (nf (flat httpFlat) httpHead)+ ]+ , bgroup+ "JSON body of the zones"+ [ bench "aeson, to Value" (nf (decodeStrict :: ByteString -> Maybe Value) zonesJson)+ , bench "flatparse, to Value" (nf (flat (jsonFlat <* FB.eof)) zonesJson)+ , -- Zone has no NFData instance: the zones are shown to force them,+ -- which adds to these two times alike.+ bench "aeson, to Value, then FromJSON to [Zone]" (nf (fmap (length . show) . toZones) zonesJson)+ , bench "FromJSON to [Zone] alone, from a Value" (nf (fmap (length . show) . fromValue) zonesValue)+ ]+ , bgroup+ "the ways compared agree"+ [ testCase "MOO header block" $+ assertBool "differ" (all (== run mooMonadic block) [run mooApplicative block, flat mooFlat block, Just (mooByHand block)])+ , testCase "HTTP head" $ do+ fmap summary (flat (responseHead <* FB.eof) httpHead) @?= flat httpFlat httpHead+ run streamlyHead httpHead @?= flat httpFlat httpHead+ , testCase "JSON" $+ flat (jsonFlat <* FB.eof) zonesJson @?= decodeStrict zonesJson+ ]+ ]+ where+ run :: Parser Word8 Identity a -> ByteString -> Maybe a+ run parser bytes = either (const Nothing) Just (runIdentity (S.parse parser (unfold reader bytes)))+ flat :: FB.Parser e a -> ByteString -> Maybe a+ flat parser bytes = case runParser parser bytes of+ OK found _ -> Just found+ _ -> Nothing+ whole message = (message.name, message.headers, case message.body of JsonBody value -> value; _ -> Null)+ summary response = (response.status, response.reason, response.headers)+ toZones bytes = decodeStrict bytes >>= fromValue+ fromValue :: Value -> Maybe [Zone]+ fromValue = \case+ Object fields | Just zones <- JK.lookup "zones" fields -> either (const Nothing) Just (parseEither parseJSON zones)+ _ -> Nothing++-- Inputs++-- | The zones of the Roon Server of this machine, or made-up ones when it+-- cannot be reached.+zonesBody :: IO (String, Value)+zonesBody = do+ tokenFile <- runEff (runFileSystem (defaultTokenFile extension.extensionId))+ outcome <- try . runEff . runConcurrent . runFileSystem . runErrorNoCallStack @RoonError . runTokenStoreFile tokenFile . withRoon localServer extension $ \_ ->+ request "com.roonlabs.transport:2/get_zones" NoBody+ pure $ case outcome of+ Right (Right Reply {body = JsonBody value}) -> ("from the Roon Server of this machine", force value)+ Right _ -> ("made up (the server gave no zones)", madeUp)+ Left (_ :: SomeException) -> ("made up (no server reached)", madeUp)+ where+ madeUp = object ["zones" .= ([] :: [Value])]+ extension =+ ExtensionInfo+ { extensionId = "io.github.guillaumedevolpiano.roon-api.probe"+ , displayName = "roon-api probe"+ , displayVersion = "bench"+ , publisher = "roon-api"+ , email = "nobody@example.invalid"+ , website = Nothing+ , requiredServices = ["com.roonlabs.transport:2", "com.roonlabs.browse:1"]+ , optionalServices = []+ , providedServices = [pingService]+ }++-- | The head of an image response, as Roon Server 2.75 sent it.+httpHead :: ByteString+httpHead =+ "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nEtag: 96f45bde867a0aaf6df5ff2f47526aa6916ed3ff:6a8027a650750256c151c53e7ee9017f\r\n\+ \Accept-Ranges: bytes\r\nCache-Control: max-age=21600, public\r\nContent-Type: image/jpeg\r\nContent-Length: 43183\r\n\r\n"++-- The MOO header block, four ways++-- | As in Roon.Moo.Message.+mooMonadic :: Parser Word8 Identity (Text, Text, [(Text, Text)])+mooMonadic = do+ void (listEq (unpack "MOO/1 "))+ verbName <- utf8 (takeWhile1 isUpperAscii toList)+ void (satisfy (== 32))+ name <- restOfLine+ headerList <- P.many headerLine toList+ P.eof+ pure (verbName, name, headerList)+ where+ headerLine = do+ key <- utf8 (takeWhile1 (\byte -> byte /= 58 && byte /= 10) toList)+ void (satisfy (== 58))+ P.dropWhile (== 32)+ value <- restOfLine+ pure (key, value)+ restOfLine = utf8 (P.takeWhile (/= 10) toList) <* satisfy (== 10)+ utf8 bytesParser = do+ bytes <- bytesParser+ case decodeUtf8' (pack bytes) of+ Left _ -> die "invalid UTF-8"+ Right decoded -> pure decoded+ isUpperAscii byte = byte >= 65 && byte <= 90++-- | The same grammar without any bind: UTF-8 is decoded leniently, since+-- deciding to fail on a decoded value needs a bind.+mooApplicative :: Parser Word8 Identity (Text, Text, [(Text, Text)])+mooApplicative =+ (,,)+ <$> (listEq (unpack "MOO/1 ") *> text (takeWhile1 isUpperAscii toList) <* satisfy (== 32))+ <*> restOfLine+ <*> P.many headerLine toList+ <* P.eof+ where+ headerLine =+ (,)+ <$> (text (takeWhile1 (\byte -> byte /= 58 && byte /= 10) toList) <* satisfy (== 58) <* P.dropWhile (== 32))+ <*> restOfLine+ restOfLine = text (P.takeWhile (/= 10) toList) <* satisfy (== 10)+ text = fmap (decodeUtf8Lenient . pack)+ isUpperAscii byte = byte >= 65 && byte <= 90++mooFlat :: FB.Parser () (Text, Text, [(Text, Text)])+mooFlat = do+ byteString "MOO/1 "+ verbName <- utf8 (byteStringOf (skipSome (skipSatisfyAscii (\c -> c >= 'A' && c <= 'Z'))))+ word8 32+ name <- restOfLine+ headerList <- FB.many headerLine+ FB.eof+ pure (verbName, name, headerList)+ where+ headerLine = do+ key <- utf8 (byteStringOf (skipSome (notByte2 58 10)))+ word8 58+ skipMany (word8 32)+ value <- restOfLine+ pure (key, value)+ restOfLine = utf8 (byteStringOf (skipMany (notByte 10))) <* word8 10+ utf8 parser = parser >>= either (const failed) pure . decodeUtf8'++-- | Any byte but one.+notByte :: Word8 -> FB.Parser e ()+notByte excluded = anyWord8 >>= \byte -> if byte == excluded then failed else pure ()++notByte2 :: Word8 -> Word8 -> FB.Parser e ()+notByte2 one other = anyWord8 >>= \byte -> if byte == one || byte == other then failed else pure ()++-- | What the same block gives when its lines are split by hand: no error+-- reporting, no check of the grammar.+mooByHand :: ByteString -> (Text, Text, [(Text, Text)])+mooByHand block = case BS8.lines block of+ first : rest ->+ let (verbName, name) = BS.break (== 32) (BS.drop 6 first)+ in (decodeUtf8Lenient verbName, decodeUtf8Lenient (BS.drop 1 name), map header rest)+ [] -> ("", "", [])+ where+ header line =+ let (key, value) = BS.break (== 58) line+ in (decodeUtf8Lenient key, decodeUtf8Lenient (BS.dropWhile (== 32) (BS.drop 1 value)))++-- The HTTP head++-- | The parser of streamly-http before it moved to flatparse.+streamlyHead :: Parser Word8 Identity (Int, ByteString, [(ByteString, ByteString)])+streamlyHead = do+ void (listEq (unpack "HTTP/1."))+ void (satisfy isDigitByte)+ void (satisfy (== 32))+ digits <- takeWhile1 isDigitByte toList+ reason <- restOfLine+ found <- P.many headerLine toList+ P.dropWhile (== 13)+ void (satisfy (== 10))+ pure (L.foldl' (\total byte -> total * 10 + fromIntegral (byte - 48)) 0 digits, reason, found)+ where+ headerLine = do+ name <- takeWhile1 (\byte -> byte > 32 && byte < 127 && byte /= 58) toList+ void (satisfy (== 58))+ value <- restOfLine+ pure (BS.map (\byte -> if byte >= 65 && byte <= 90 then byte + 32 else byte) (pack name), value)+ restOfLine = do+ bytes <- P.takeWhile (/= 10) toList+ void (satisfy (== 10))+ pure (BS.dropWhile blank (dropWhileEnd blank (pack bytes)))+ blank byte = byte == 32 || byte == 9 || byte == 13+ isDigitByte byte = byte >= 48 && byte <= 57++httpFlat :: FB.Parser () (Int, ByteString, [(ByteString, ByteString)])+httpFlat = do+ byteString "HTTP/1."+ skipSatisfyAscii isDigit+ word8 32+ status <- anyAsciiDecimalInt+ reason <- restOfLine+ found <- FB.many headerLine+ lineEnd+ pure (status, reason, found)+ where+ headerLine = do+ name <- byteStringOf (skipSome (skipSatisfyAscii tokenChar))+ word8 58+ value <- restOfLine+ pure (BS8.map lower name, value)+ restOfLine = do+ line <- byteStringOf (skipMany (notByte 10))+ word8 10+ pure (BS.dropWhile blank (dropWhileEnd blank line))+ lineEnd = skipMany (word8 13) *> word8 10+ blank byte = byte == 32 || byte == 9 || byte == 13+ tokenChar c = c > ' ' && c < '\DEL' && c /= ':'+ lower c = if c >= 'A' && c <= 'Z' then chr (fromEnum c + 32) else c++-- JSON, to the Value of aeson++jsonFlat :: FB.Parser () Value+jsonFlat = spaces *> value <* spaces+ where+ spaces = skipMany (skipSatisfyAscii (\c -> c == ' ' || c == '\n' || c == '\r' || c == '\t'))+ value =+ (String <$> string)+ <|> (word8 123 *> spaces *> (Object . JK.fromList <$> members) <* word8 125)+ <|> (word8 91 *> spaces *> (Array . V.fromList <$> elements) <* word8 93)+ <|> (Bool True <$ byteString "true")+ <|> (Bool False <$ byteString "false")+ <|> (Null <$ byteString "null")+ <|> number+ members = sepByComma ((,) <$> (fromText <$> string) <* spaces <* word8 58 <*> jsonFlat) <|> pure []+ elements = sepByComma jsonFlat <|> pure []+ sepByComma item = (:) <$> (item <* spaces) <*> FB.many (word8 44 *> spaces *> item <* spaces)+ string = do+ word8 34+ plain <- byteStringOf (skipMany plainByte)+ (word8 34 *> decoded plain) <|> (escaped [plain] >>= decoded . BS.concat . reverse)+ plainByte = anyWord8 >>= \byte -> if byte == 34 || byte == 92 || byte < 32 then failed else pure ()+ decoded bytes = either (const failed) pure (decodeUtf8' bytes)+ -- The rest of a string that holds escapes, its pieces in reverse.+ escaped pieces = do+ word8 92+ piece <- escape+ plain <- byteStringOf (skipMany plainByte)+ (reverse' (plain : piece : pieces) <$ word8 34) <|> escaped (plain : piece : pieces)+ reverse' = id+ escape =+ anyWord8 >>= \case+ 34 -> pure "\""+ 92 -> pure "\\"+ 47 -> pure "/"+ 98 -> pure "\b"+ 102 -> pure "\f"+ 110 -> pure "\n"+ 114 -> pure "\r"+ 116 -> pure "\t"+ 117 -> do+ high <- hex4+ if high >= 0xD800 && high < 0xDC00+ then do+ word8 92 *> word8 117+ low <- hex4+ pure (encodeUtf8 (singleton (chr (0x10000 + (high - 0xD800) * 0x400 + (low - 0xDC00)))))+ else pure (encodeUtf8 (singleton (chr high)))+ _ -> failed+ hex4 = isolate 4 anyAsciiHexInt+ number = do+ negative <- (True <$ word8 45) <|> pure False+ whole <- anyAsciiDecimalInteger+ (fraction, digits) <- (word8 46 *> withByteString anyAsciiDecimalInteger (\n bytes -> pure (n, BS.length bytes))) <|> pure (0, 0)+ power <- ((word8 101 <|> word8 69) *> signedInt) <|> pure 0+ let mantissa = whole * 10 ^ digits + fraction+ pure (Number (scientific (if negative then negate mantissa else mantissa) (power - digits)))+ signedInt = (word8 45 *> (negate <$> anyAsciiDecimalInt)) <|> (word8 43 *> anyAsciiDecimalInt) <|> anyAsciiDecimalInt
+ roon-api.cabal view
@@ -0,0 +1,162 @@+cabal-version: 3.12+name: roon-api+version: 0.1.0.0+synopsis: Client library for the Roon extension API+description:+ An independent, unofficial Haskell implementation of the protocol that+ Roon extensions use to talk to a Roon Server: MOO messages over a+ WebSocket, discovery of the servers on the network, the registration of+ an extension, the transport service (zones, queue, playback, volume),+ the browse service (search, library, play actions) and images. Built on+ Effectful and Streamly. Not affiliated with Roon Labs.++homepage: https://github.com/GuillaumedeVolpiano/roon-api+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: Sound, Network+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/roon-api.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ DuplicateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ NoFieldSelectors+ OverloadedRecordDot+ OverloadedStrings+ RoleAnnotations+ TypeFamilies++ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ Roon.Browse+ Roon.Connection+ Roon.Discovery+ Roon.Effect.Moo+ Roon.Effect.TokenStore+ Roon.Effect.WebSocket+ Roon.Error+ Roon.Image+ Roon.Moo.Message+ Roon.Registry+ Roon.Service+ Roon.Transport++ build-depends:+ , aeson ^>=2.3+ , base >=4.19 && <4.22+ , bytestring ^>=0.12+ , containers >=0.6.7 && <0.8+ , effectful ^>=2.7+ , effectful-core ^>=2.7.1+ , effectful-streamly ^>=0.1+ , effectful-streamly-http ^>=0.1+ , effectful-websockets ^>=0.1+ , filepath >=1.4.200 && <1.6+ , flatparse ^>=0.5+ , network ^>=3.2+ , streamly-bytestring ^>=0.2.3+ , streamly-core ^>=0.3.3+ , streamly-network-udp ^>=0.1+ , text ^>=2.1++executable roon-probe+ import: shared+ hs-source-dirs: app+ main-is: Main.hs+ other-modules: Paths_roon_api+ autogen-modules: Paths_roon_api+ ghc-options: -threaded+ build-depends:+ , base+ , bytestring+ , effectful+ , roon-api+ , text++test-suite roon-api-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ other-modules:+ Roon.BrowseSpec+ Roon.ConnectionSpec+ Roon.DiscoverySpec+ Roon.Effect.TokenStoreSpec+ Roon.Effect.WebSocketSpec+ Roon.ImageSpec+ Roon.Moo.MessageSpec+ Roon.Test.Server+ Roon.TransportSpec++ ghc-options: -threaded+ build-depends:+ , aeson+ , async ^>=2.2+ , base+ , bytestring+ , containers+ , directory ^>=1.3+ , effectful-streamly-http+ , effectful+ , filepath+ , network+ , roon-api+ , stm ^>=2.5+ , streamly-core+ , temporary ^>=1.3+ , unix ^>=2.8+ , streamly-websockets ^>=0.1+ , text+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10+ , tasty-quickcheck ^>=0.11++-- Measures the parsers of the hot paths against other ways to write+-- them. Not a regression test: run it by hand, with cabal bench.+benchmark roon-api-bench+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: bench+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , aeson+ , base+ , bytestring+ , containers+ , deepseq ^>=1.5+ , effectful+ , flatparse+ , roon-api+ , scientific ^>=0.3+ , streamly-bytestring+ , streamly-core+ , streamly-http ^>=0.1+ , tasty-bench >=0.4 && <0.6+ , tasty-hunit+ , text+ , vector ^>=0.13
+ src/Roon/Browse.hs view
@@ -0,0 +1,449 @@+-- |+-- Module : Roon.Browse+-- Description : Browsing the library, searching, and playing what is found+-- License : BSD-3-Clause+--+-- The browse service, @com.roonlabs.browse:1@, presents the library as+-- lists: the server keeps a stack of levels for each browsing session,+-- 'browse' moves in that stack, and 'load' reads the items of a level.+--+-- Item keys are only valid while the session stays where it was when they+-- were loaded. A session is identified by its hierarchy and, to run+-- several at once, a key of its own: see t'Session'.+--+-- Categories and actions are only known by their titles, such as+-- @Tracks@ or @Play Now@. Those of this module are the English ones; they+-- may follow the language of the Roon interface.+module Roon.Browse+ ( browseService++ -- * Sessions+ , Hierarchy (..)+ , Session (..)+ , session++ -- * Lists and items+ , List (..)+ , ListHint (..)+ , Item (..)+ , ItemHint (..)+ , InputPrompt (..)++ -- * Browsing+ , Navigation (..)+ , BrowseResult (..)+ , browse+ , LoadResult (..)+ , load++ -- * Searching for tracks+ , Candidate (..)+ , SearchOptions (..)+ , defaultSearchOptions+ , searchTracks+ , searchTracksConcurrently++ -- * Acting on a track+ , TrackAction (..)+ , trackActionTitle+ , performTrackAction+ , performAction+ , performTrackActions+ ) where++import Data.Aeson (FromJSON (..), object, withObject, withText, (.!=), (.:),+ (.:?), (.=))+import Data.Aeson.Types (Pair)+import Data.Maybe (catMaybes)+import Data.Text (Text, isPrefixOf, pack)+import Effectful (Eff, IOE, type (:>))+import Effectful.Error.Static (Error, runErrorNoCallStack, throwError)+import Effectful.Streamly.Stream (ordered, parMapM)+import Roon.Effect.Moo (Moo, request)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (..))+import Roon.Service (expect)+import Roon.Transport (ZoneOrOutput (..))+import Streamly.Data.Stream (fromList, toList)++-- | The name of the browse service, version included.+browseService :: Text+browseService = "com.roonlabs.browse:1"++-- Sessions++-- | The hierarchies the reference implementation lists.+data Hierarchy+ = Browse+ | Playlists+ | Settings+ | InternetRadio+ | Albums+ | Artists+ | Genres+ | Composers+ | Search+ deriving stock (Eq, Show, Enum, Bounded)++hierarchyName :: Hierarchy -> Text+hierarchyName = \case+ Browse -> "browse"+ Playlists -> "playlists"+ Settings -> "settings"+ InternetRadio -> "internet_radio"+ Albums -> "albums"+ Artists -> "artists"+ Genres -> "genres"+ Composers -> "composers"+ Search -> "search"++-- | A browsing session: a hierarchy, and a key to tell apart several+-- sessions of the same hierarchy.+data Session = Session+ { hierarchy :: Hierarchy+ , multiSessionKey :: Maybe Text+ }+ deriving stock (Eq, Show)++-- | The default session of a hierarchy.+session :: Hierarchy -> Session+session hierarchy = Session {hierarchy, multiSessionKey = Nothing}++sessionFields :: Session -> [Pair]+sessionFields Session {hierarchy, multiSessionKey} =+ ("hierarchy" .= hierarchyName hierarchy) : catMaybes [("multi_session_key" .=) <$> multiSessionKey]++-- Lists and items++-- | A level of the browsing stack.+data List = List+ { title :: Text+ , subtitle :: Maybe Text+ , count :: Int+ -- ^ How many items the level holds.+ , level :: Int+ -- ^ 0 at the top.+ , imageKey :: Maybe Text+ , displayOffset :: Maybe Int+ , hint :: Maybe ListHint+ }+ deriving stock (Eq, Show)++instance FromJSON List where+ parseJSON = withObject "List" $ \fields ->+ List+ <$> fields .: "title"+ <*> fields .:? "subtitle"+ <*> fields .: "count"+ <*> fields .: "level"+ <*> fields .:? "image_key"+ <*> fields .:? "display_offset"+ <*> fields .:? "hint"++-- | Unknown hints are kept as they are named; the reference asks to treat+-- them as no hint.+data ListHint = ActionListHint | OtherListHint Text+ deriving stock (Eq, Show)++instance FromJSON ListHint where+ parseJSON = withText "ListHint" $ \case+ "action_list" -> pure ActionListHint+ other -> pure (OtherListHint other)++-- | An item of a list.+data Item = Item+ { title :: Text+ , subtitle :: Maybe Text+ -- ^ For a track, its artists.+ , imageKey :: Maybe Text+ , itemKey :: Maybe Text+ -- ^ What to select to open the item.+ , hint :: Maybe ItemHint+ , inputPrompt :: Maybe InputPrompt+ -- ^ Present when opening the item needs some input.+ }+ deriving stock (Eq, Show)++instance FromJSON Item where+ parseJSON = withObject "Item" $ \fields ->+ Item+ <$> fields .: "title"+ <*> fields .:? "subtitle"+ <*> fields .:? "image_key"+ <*> fields .:? "item_key"+ <*> fields .:? "hint"+ <*> fields .:? "input_prompt"++-- | What selecting an item does.+data ItemHint+ = -- | Selecting the item does something, such as playing.+ Action+ | -- | Opens a list of actions.+ ActionList+ | -- | Opens a list.+ ListItem+ | -- | Only displayed.+ Header+ | OtherItemHint Text+ deriving stock (Eq, Show)++instance FromJSON ItemHint where+ parseJSON = withText "ItemHint" $ \case+ "action" -> pure Action+ "action_list" -> pure ActionList+ "list" -> pure ListItem+ "header" -> pure Header+ other -> pure (OtherItemHint other)++-- | The input an item asks for before it opens, such as the text of a+-- search.+data InputPrompt = InputPrompt+ { prompt :: Text+ , action :: Text+ , value :: Maybe Text+ , isPassword :: Bool+ }+ deriving stock (Eq, Show)++instance FromJSON InputPrompt where+ parseJSON = withObject "InputPrompt" $ \fields ->+ InputPrompt+ <$> fields .: "prompt"+ <*> fields .: "action"+ <*> fields .:? "value"+ <*> fields .:? "is_password" .!= False++-- Browsing++-- | Where to go in a session.+data Navigation+ = -- | Open an item.+ Select Text+ | -- | Open an item that asks for input, with that input.+ SelectWithInput Text Text+ | -- | Go back to the top of the hierarchy. For 'Search', the input is+ -- the text to search for.+ Top (Maybe Text)+ | -- | Go back some levels.+ Back Int+ | -- | Reload the current level.+ Reload+ deriving stock (Eq, Show)++navigationFields :: Navigation -> [Pair]+navigationFields = \case+ Select key -> ["item_key" .= key]+ SelectWithInput key input -> ["item_key" .= key, "input" .= input]+ Top input -> ("pop_all" .= True) : catMaybes [("input" .=) <$> input]+ Back levels -> ["pop_levels" .= levels]+ Reload -> ["refresh_list" .= True]++-- | What to show after a move.+data BrowseResult+ = -- | A message for the user; 'True' for an error.+ BrowseMessage Text Bool+ | BrowseNone+ | -- | The current level changed: 'load' its items.+ BrowseList List+ | -- | Replace the selected item.+ BrowseReplaceItem Item+ | -- | Remove the selected item.+ BrowseRemoveItem+ | -- | An action not in the reference, kept as named.+ BrowseOther Text+ deriving stock (Eq, Show)++instance FromJSON BrowseResult where+ parseJSON = withObject "BrowseResult" $ \fields ->+ fields .: "action" >>= \case+ ("message" :: Text) -> BrowseMessage <$> fields .:? "message" .!= "" <*> fields .:? "is_error" .!= False+ "none" -> pure BrowseNone+ "list" -> BrowseList <$> fields .: "list"+ "replace_item" -> BrowseReplaceItem <$> fields .: "item"+ "remove_item" -> pure BrowseRemoveItem+ other -> pure (BrowseOther other)++-- | Move in a session. The zone matters for actions that play.+browse+ :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es)+ => Session+ -> Maybe target+ -> Navigation+ -> Eff es BrowseResult+browse current target navigation =+ request name (JsonBody body) >>= expect name "Success"+ where+ name = browseService <> "/browse"+ body =+ object $+ sessionFields current+ <> navigationFields navigation+ <> catMaybes [("zone_or_output_id" .=) . zoneOrOutputId <$> target]++-- | A part of a list: the list, where the part starts, and its items.+data LoadResult = LoadResult+ { list :: List+ , offset :: Int+ , items :: [Item]+ }+ deriving stock (Eq, Show)++instance FromJSON LoadResult where+ parseJSON = withObject "LoadResult" $ \fields ->+ LoadResult <$> fields .: "list" <*> fields .:? "offset" .!= 0 <*> fields .:? "items" .!= []++-- | Read items of the current level, from an offset.+load :: (Moo :> es, Error RoonError :> es) => Session -> Int -> Int -> Eff es LoadResult+load current offset count =+ request name (JsonBody (object (sessionFields current <> ["offset" .= offset, "count" .= count]))) >>= expect name "Success"+ where+ name = browseService <> "/load"++-- Searching for tracks++-- | A track found by a search, and the session where its key is valid.+data Candidate = Candidate+ { session :: Session+ , item :: Item+ }+ deriving stock (Eq, Show)++-- | How to read the results of a search for tracks.+data SearchOptions = SearchOptions+ { tracksTitle :: Text+ -- ^ The title of the category of tracks in the results.+ , maxCandidates :: Int+ }+ deriving stock (Eq, Show)++-- | The English category, and ten candidates.+defaultSearchOptions :: SearchOptions+defaultSearchOptions = SearchOptions {tracksTitle = "Tracks", maxCandidates = 10}++-- | Search for tracks in a session, which this moves. Returns the tracks+-- of the category of tracks, best first; none if the search found no+-- track.+searchTracks+ :: (Moo :> es, Error RoonError :> es)+ => SearchOptions+ -> Session+ -> Text+ -> Eff es [Candidate]+searchTracks options current query = do+ _ <- browse current noTarget (Top (Just query))+ top <- load current 0 100+ case [key | Item {title, hint = Just ListItem, itemKey = Just key} <- top.items, title == options.tracksTitle] of+ [] -> pure []+ key : _ -> do+ _ <- browse current noTarget (Select key)+ tracks <- load current 0 options.maxCandidates+ pure [Candidate {session = current, item} | item@Item {hint = Just ActionList} <- tracks.items]++-- | Run several searches at once, each in a session of its own, keyed by+-- the prefix and the position of the query. A failed search does not stop+-- the others: each query gets its own outcome.+searchTracksConcurrently+ :: (IOE :> es, Moo :> es)+ => SearchOptions+ -> Text+ -- ^ The prefix of the session keys.+ -> [Text]+ -> Eff es [(Text, Either RoonError [Candidate])]+searchTracksConcurrently options prefix queries =+ toList $+ parMapM (ordered True) search (fromList (zip [0 :: Int ..] queries))+ where+ search (index, query) =+ (query,) <$> runErrorNoCallStack (searchTracks options (Session Search (Just (prefix <> pack (show index)))) query)++-- Acting on a track++-- | What can be done with a track.+data TrackAction = PlayNow | AddNext | Queue | StartRadio+ deriving stock (Eq, Show, Enum, Bounded)++-- | The English title of an action.+trackActionTitle :: TrackAction -> Text+trackActionTitle = \case+ PlayNow -> "Play Now"+ AddNext -> "Add Next"+ Queue -> "Queue"+ StartRadio -> "Start Radio"++-- | Open a candidate down to its list of actions, then select the action+-- with the given title, for a zone. The session must not have moved since+-- the search. After an action, Roon goes back to the level of the track;+-- the zone reports the change a moment later. Throws 'BrowseFailed' when Roon reports an error, and+-- 'BrowseItemMissing' when no such action is offered.+performTrackAction+ :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es)+ => target+ -> Text+ -- ^ The title of the action, such as @trackActionTitle Queue@.+ -> Candidate+ -> Eff es ()+performTrackAction = performAction++-- | Like 'performTrackAction', for anything Roon can play: a track, but+-- also an album, a playlist, an artist or a radio.+--+-- Observed with Roon Server 2.75: an album and a playlist open on a level+-- whose first item, @Play Album@ or @Play Playlist@, leads to the actions,+-- before the tracks; a playlist also offers @Shuffle@. An album found by a+-- search first opens on a level that holds only itself. A key of an earlier+-- level is still accepted after the session has gone deeper: Roon goes+-- back by itself. A key that Roon no longer knows is answered+-- @InvalidItemKey@ ('UnexpectedReply').+performAction+ :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es)+ => target+ -> Text+ -- ^ The title of the action, such as @trackActionTitle Queue@.+ -> Candidate+ -> Eff es ()+performAction target actionTitle candidate = case candidate.item.itemKey of+ Nothing -> throwError (BrowseItemMissing ("no key for " <> candidate.item.title))+ Just key -> descend (4 :: Int) key+ where+ current = candidate.session+ missing = throwError (BrowseItemMissing (actionTitle <> " for " <> candidate.item.title))+ -- A track opens on a level that holds only itself, then on its+ -- actions; an album or a playlist on a level that starts with the item+ -- that plays the whole of it. The depth bounds the descent.+ descend 0 _ = throwError (BrowseItemMissing ("no action list for " <> candidate.item.title))+ descend depth key = do+ _ <- browse current (Just target) (Select key)+ level <- load current 0 100+ case [actionKey | Item {title, hint = Just Action, itemKey = Just actionKey} <- level.items, title == actionTitle] of+ actionKey : _ ->+ browse current (Just target) (Select actionKey) >>= \case+ BrowseMessage message True -> throwError (BrowseFailed message)+ _ -> pure ()+ []+ | level.list.hint == Just ActionListHint -> missing+ | otherwise -> case [(title, next) | Item {title, hint = Just ActionList, itemKey = Just next} <- level.items] of+ [(_, next)] -> descend (depth - 1) next+ (title, next) : _ | "Play " `isPrefixOf` title -> descend (depth - 1) next+ -- An album found by a search opens on a level that holds+ -- only itself, as a list, before its tracks.+ [] | [Item {hint = Just ListItem, itemKey = Just next}] <- level.items -> descend (depth - 1) next+ _ -> missing++-- | Perform actions one after the other, in order, and report each one.+-- A failure does not stop the next ones.+performTrackActions+ :: (ZoneOrOutput target, Moo :> es)+ => target+ -> [(Text, Candidate)]+ -> Eff es [(Candidate, Either RoonError ())]+performTrackActions target =+ traverse (\(actionTitle, candidate) -> (candidate,) <$> runErrorNoCallStack (performTrackAction target actionTitle candidate))++noTarget :: Maybe NoTarget+noTarget = Nothing++-- | No zone, for moves that do not play.+data NoTarget++instance ZoneOrOutput NoTarget where+ zoneOrOutputId = \case {}
+ src/Roon/Connection.hs view
@@ -0,0 +1,172 @@+-- |+-- Module : Roon.Connection+-- Description : Connecting to a Roon Server as an extension+-- License : BSD-3-Clause+module Roon.Connection+ ( withRoon+ , withRoonWithin+ , runRoon+ , runRoonWithin+ , registerExtension+ , registerExtensionWithin++ -- * Reconnection+ , Reconnect (..)+ , defaultReconnect+ , reconnecting+ , withRoonReconnecting+ ) where++import Effectful (Eff, IOE, raise, type (:>))+import Effectful.Concurrent (Concurrent, threadDelay)+import Effectful.Concurrent.STM (atomically, newTVarIO, readTVar, writeTVar)+import Effectful.Error.Static (Error, throwError, tryError)+import Roon.Effect.Moo (Moo, defaultRequestHandler, pingService, runMoo)+import Roon.Effect.TokenStore (TokenStore, loadToken, saveToken)+import Roon.Effect.WebSocket (ServerAddress, WebSocket, runWebSocket)+import Roon.Error (RoonError (..))+import Roon.Registry (CoreInfo (..), ExtensionInfo (..), Registration (..),+ info, register, registerWithin)++-- | Register the extension, reusing the stored token if there is one, and+-- store the token that the server returns.+--+-- The first time, this waits until the user enables the extension in+-- Roon, under Settings, Extensions.+registerExtension+ :: (Moo :> es, TokenStore :> es, Error RoonError :> es)+ => ExtensionInfo+ -> Eff es Registration+registerExtension = registerExtensionWithin Nothing++-- | 'registerExtension', waiting at most a number of microseconds for the+-- server to answer the registration, and so for the user to enable the+-- extension; 'Nothing' waits as long as needed. Throws 'TimedOut' when the+-- time is up.+registerExtensionWithin+ :: (Moo :> es, TokenStore :> es, Error RoonError :> es)+ => Maybe Int+ -> ExtensionInfo+ -> Eff es Registration+registerExtensionWithin limit extension = do+ core <- info+ token <- loadToken core.coreId+ registration <- maybe register registerWithin limit extension token+ saveToken registration.core.coreId registration.token+ pure registration++-- | Register the extension over an established transport and run an+-- action. 'withRoon' is this over a real WebSocket.+--+-- The ping service, which every extension must provide, is added to the+-- provided services and answered automatically.+runRoon+ :: (WebSocket :> es, Concurrent :> es, TokenStore :> es, Error RoonError :> es)+ => ExtensionInfo+ -> (Registration -> Eff (Moo : es) a)+ -> Eff es a+runRoon = runRoonWithin Nothing++-- | 'runRoon', with a limit on the registration ('registerExtensionWithin').+runRoonWithin+ :: (WebSocket :> es, Concurrent :> es, TokenStore :> es, Error RoonError :> es)+ => Maybe Int+ -> ExtensionInfo+ -> (Registration -> Eff (Moo : es) a)+ -> Eff es a+runRoonWithin limit extension action =+ runMoo defaultRequestHandler (registerExtensionWithin limit withPing >>= action)+ where+ withPing+ | pingService `elem` extension.providedServices = extension+ | otherwise = extension {providedServices = pingService : extension.providedServices}++-- | Connect to a Roon Server, register the extension and run an action.+--+-- Roon keeps one connection per extension. Observed with Roon Server 2.75:+-- when a second connection of the same extension registers, Roon sends an+-- empty frame to the first one, which then fails with a 'ProtocolViolation'.+-- A program that connects for each task should take its connections one at+-- a time.+-- The connection is closed when the action returns.+withRoon+ :: (IOE :> es, Concurrent :> es, TokenStore :> es, Error RoonError :> es)+ => ServerAddress+ -> ExtensionInfo+ -> (Registration -> Eff (Moo : WebSocket : es) a)+ -> Eff es a+withRoon = withRoonWithin Nothing++-- | 'withRoon', with a limit on the registration+-- ('registerExtensionWithin'): for a program that cannot wait for the user+-- to enable the extension.+withRoonWithin+ :: (IOE :> es, Concurrent :> es, TokenStore :> es, Error RoonError :> es)+ => Maybe Int+ -> ServerAddress+ -> ExtensionInfo+ -> (Registration -> Eff (Moo : WebSocket : es) a)+ -> Eff es a+withRoonWithin limit address extension = runWebSocket address . runRoonWithin limit extension++-- | When to try again after the connection is lost or refused.+data Reconnect = Reconnect+ { firstDelay :: Int+ -- ^ Microseconds before the first new attempt. The delay doubles after+ -- each failed attempt, and starts again from this one once an attempt+ -- has connected.+ , maxDelay :: Int+ -- ^ Microseconds the delay never exceeds.+ , maxAttempts :: Maybe Int+ -- ^ How many attempts in a row may fail; 'Nothing' for no limit.+ }+ deriving stock (Eq, Show)++-- | One second, doubling up to one minute, without end.+defaultReconnect :: Reconnect+defaultReconnect = Reconnect {firstDelay = 1_000_000, maxDelay = 60_000_000, maxAttempts = Nothing}++-- | Run an action again whenever it fails with 'ConnectionLost' or+-- 'ConnectFailed', after a growing delay. The action receives a function+-- to call once it is connected, which resets the delay and the count of+-- failed attempts. Other failures, and the last one when 'maxAttempts' is+-- reached, are thrown.+reconnecting+ :: (Concurrent :> es, Error RoonError :> es)+ => Reconnect+ -> (Eff es () -> Eff es a)+ -> Eff es a+reconnecting policy attempt = go policy.firstDelay (1 :: Int)+ where+ go delay count = do+ connected <- newTVarIO False+ outcome <- tryError @RoonError (attempt (atomically (writeTVar connected True)))+ wasConnected <- atomically (readTVar connected)+ let (delay', count') = if wasConnected then (policy.firstDelay, 1) else (delay, count)+ case outcome of+ Right value -> pure value+ Left (_, failure)+ | retriable failure && maybe True (count' <) policy.maxAttempts -> do+ threadDelay delay'+ go (min policy.maxDelay (2 * delay')) (count' + 1)+ | otherwise -> throwError failure+ retriable = \case+ ConnectionLost -> True+ ConnectFailed _ -> True+ _ -> False++-- | 'withRoon', connecting again when the connection is lost or refused.+-- The action runs again from the start on each new connection, so the+-- subscriptions it opens are opened again.+withRoonReconnecting+ :: (IOE :> es, Concurrent :> es, TokenStore :> es, Error RoonError :> es)+ => Reconnect+ -> ServerAddress+ -> ExtensionInfo+ -> (Registration -> Eff (Moo : WebSocket : es) a)+ -> Eff es a+withRoonReconnecting policy address extension action =+ reconnecting policy $ \markConnected ->+ withRoon address extension $ \registration -> do+ raise (raise markConnected)+ action registration
+ src/Roon/Discovery.hs view
@@ -0,0 +1,180 @@+-- |+-- Module : Roon.Discovery+-- Description : Finding Roon Servers on the local network (SOOD)+-- License : BSD-3-Clause+--+-- Roon Servers answer SOOD queries: UDP datagrams sent to port 9003, by+-- multicast to 239.255.90.90 and by broadcast. A query names the service+-- it looks for; each server answers with its name, version, unique id and+-- ports, to the port the query came from.+--+-- Observed with Roon Server 2.75: a server answers each query several+-- times, and its answers do not repeat the transaction id of the query.+-- Answers are told apart by the unique id of the server. A query without a+-- transaction id of its own was answered only the first time.+--+-- Queries go out through the default interface only.+module Roon.Discovery+ ( -- * Discovering+ Core (..)+ , DiscoveryOptions (..)+ , defaultDiscovery+ , discover++ -- * The SOOD format+ , SoodMessage (..)+ , encodeSood+ , decodeSood+ , roonServiceId+ , coreFromAnswer+ ) where++import Control.Monad (when)+import Data.Bits (shiftR, (.&.))+import Data.ByteString (ByteString, singleton)+import Data.ByteString qualified as BS (length, pack, take)+import Data.Function (on)+import Data.List (nubBy)+import Data.Text (Text, unpack)+import Data.Text qualified as T (pack)+import Data.Text.Encoding (decodeUtf8', encodeUtf8)+import Effectful (Eff, IOE, MonadIO (liftIO), type (:>))+import FlatParse.Basic (Parser, Result (OK), anyWord16be, anyWord8, byteString,+ eof, failed, many, runParser, word8)+import FlatParse.Basic qualified as FB (take)+import GHC.Clock (getMonotonicTimeNSec)+import Network.Socket (HostAddress, PortNumber, SockAddr (SockAddrInet),+ hostAddressToTuple, tupleToHostAddress)+import Roon.Effect.WebSocket (ServerAddress (..))+import Streamly.Data.Stream (fold, fromList, mapMaybe, toList)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.Network.UDP (SocketConfig (broadcast), anyAddress,+ datagramsWithin, socketAt, withSocket,+ writeTo)+import Text.Read (readMaybe)++-- | A SOOD datagram: its type (@Q@ for a query, @R@ for an answer) and its+-- properties, in order. A property may have no value.+data SoodMessage = SoodMessage+ { kind :: Char+ , properties :: [(Text, Maybe Text)]+ }+ deriving stock (Eq, Show)++-- | The service id of Roon Servers.+roonServiceId :: Text+roonServiceId = "00720724-5143-4a9b-abac-0e50cba674bb"++-- | Encode a datagram. Names longer than 255 bytes and values longer than+-- 65534 bytes are cut.+encodeSood :: SoodMessage -> ByteString+encodeSood SoodMessage {kind, properties} =+ "SOOD" <> BS.pack [2, fromIntegral (fromEnum kind)] <> foldMap property properties+ where+ property (name, value) =+ let nameBytes = BS.take 255 (encodeUtf8 name)+ in singleton (fromIntegral (BS.length nameBytes)) <> nameBytes <> case value of+ Nothing -> BS.pack [0xff, 0xff]+ Just text ->+ let valueBytes = BS.take 65534 (encodeUtf8 text)+ in word16 (BS.length valueBytes) <> valueBytes+ word16 n = BS.pack [fromIntegral (n `shiftR` 8), fromIntegral (n .&. 0xff)]++-- | Decode a datagram. 'Nothing' if it is not SOOD version 2, or if a+-- property is cut short.+decodeSood :: ByteString -> Maybe SoodMessage+decodeSood bytes = case runParser soodParser bytes of+ OK message _ -> Just message+ _ -> Nothing++-- | A SOOD datagram, read to its end: the mark, the version, the type,+-- then properties, each a name with its length on one byte and a value+-- with its length on two, 0xffff standing for no value.+soodParser :: Parser () SoodMessage+soodParser = do+ byteString "SOOD"+ word8 2+ kindByte <- anyWord8+ properties <- many property+ eof+ pure SoodMessage {kind = toEnum (fromIntegral kindByte), properties}+ where+ property = do+ nameLength <- anyWord8+ when (nameLength == 0) failed+ name <- utf8 (FB.take (fromIntegral nameLength))+ valueLength <- anyWord16be+ value <- if valueLength == 0xffff then pure Nothing else Just <$> utf8 (FB.take (fromIntegral valueLength))+ pure (name, value)+ utf8 parser = parser >>= either (const failed) pure . decodeUtf8'++-- | A Roon Server found on the network.+data Core = Core+ { uniqueId :: Text+ -- ^ The same as the core id the registry reports.+ , name :: Maybe Text+ , displayVersion :: Maybe Text+ , address :: ServerAddress+ -- ^ Where its extension API listens.+ , properties :: [(Text, Maybe Text)]+ -- ^ Everything the answer said.+ }+ deriving stock (Eq, Show)++-- | The server an answer describes, from the address it came from. The+-- answer may name another address and port to reply to (@_replyaddr@,+-- @_replyport@); the extension API listens on @http_port@.+coreFromAnswer :: String -> SoodMessage -> Maybe Core+coreFromAnswer sender SoodMessage {kind, properties}+ | kind /= 'R' = Nothing+ | lookup' "service_id" /= Just roonServiceId = Nothing+ | otherwise = do+ uniqueId <- lookup' "unique_id"+ port <- lookup' "http_port" >>= readMaybe . unpack+ let host = maybe sender unpack (lookup' "_replyaddr")+ pure+ Core+ { uniqueId+ , name = lookup' "name"+ , displayVersion = lookup' "display_version"+ , address = ServerAddress {host, port}+ , properties+ }+ where+ lookup' key = case lookup key properties of+ Just (Just value) -> Just value+ _ -> Nothing++-- | Where to look for servers, and for how long.+data DiscoveryOptions = DiscoveryOptions+ { targets :: [(HostAddress, PortNumber)]+ -- ^ Where to send the query.+ , wait :: Int+ -- ^ Microseconds to collect answers.+ }+ deriving stock (Eq, Show)++-- | The SOOD multicast group and the broadcast address, port 9003; one+-- second for the answers.+defaultDiscovery :: DiscoveryOptions+defaultDiscovery =+ DiscoveryOptions+ { targets = [(tupleToHostAddress (239, 255, 90, 90), 9003), (tupleToHostAddress (255, 255, 255, 255), 9003)]+ , wait = 1_000_000+ }++-- | Query the network for Roon Servers and collect the answers for a+-- while. Each server is listed once, in the order of its first answer.+discover :: IOE :> es => DiscoveryOptions -> Eff es [Core]+discover options = liftIO . withSocket (socketAt anyAddress) {broadcast = True} $ \socket -> do+ -- A transaction id of its own for each query: with none, Roon Server+ -- 2.75 answered the first query only.+ transaction <- T.pack . show <$> getMonotonicTimeNSec+ let query = toArray (encodeSood SoodMessage {kind = 'Q', properties = [("query_service_id", Just roonServiceId), ("_tid", Just transaction)]})+ fold (writeTo socket) (fromList [(SockAddrInet port host, query) | (host, port) <- options.targets])+ nubBy ((==) `on` (.uniqueId)) <$> toList (mapMaybe core (datagramsWithin options.wait socket))+ where+ core (sender, datagram) = decodeSood (fromArray datagram) >>= coreFromAnswer (hostOf sender)+ hostOf = \case+ SockAddrInet _ host -> let (a, b, c, d) = hostAddressToTuple host in foldr1 (\x y -> x <> "." <> y) (map show [a, b, c, d])+ other -> show other
+ src/Roon/Effect/Moo.hs view
@@ -0,0 +1,300 @@+-- |+-- Module : Roon.Effect.Moo+-- Description : Requests and subscriptions multiplexed over one connection+-- License : BSD-3-Clause+--+-- Many exchanges share one WebSocket. Each request carries an identifier+-- that its replies repeat; a request gets any number of @CONTINUE@+-- replies, then at most one @COMPLETE@. The server also sends requests of+-- its own, such as pings, which the extension must answer.+--+-- 'runMoo' reads the socket in a background thread and routes each reply+-- to the exchange that waits for it; another thread answers the server's+-- requests.+module Roon.Effect.Moo+ ( -- * Effect+ Moo+ , Exchange+ , Reply (..)+ , openExchange+ , nextReply+ , nextReplyWithin+ , closeExchange+ , newSubscriptionKey++ -- * Requests and subscriptions+ , request+ , requestWithin+ , defaultRequestTimeout+ , withSubscription++ -- * Interpreter+ , runMoo+ , RequestHandler+ , defaultRequestHandler+ , pingService+ ) where++import Control.Monad (forever, void, (>=>))+import Data.Aeson (object, (.=))+import Data.Bool (bool)+import Data.ByteString (ByteString)+import Data.Map.Strict (Map, delete, empty, insert)+import Data.Map.Strict qualified as M (lookup)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Word (Word64)+import Effectful (Dispatch (Dynamic), DispatchOf, Eff, Effect, type (:>))+import Effectful.Concurrent (Concurrent)+import Effectful.Concurrent.Async (withAsync)+import Effectful.Concurrent.STM (STM, TQueue, TVar, atomically, modifyTVar',+ newTQueue, newTQueueIO, newTVar, newTVarIO,+ orElse, readTQueue, readTVar, registerDelay,+ retry, writeTQueue, writeTVar)+import Effectful.Dispatch.Dynamic (interpret_, send)+import Effectful.Error.Static (Error, throwError)+import Effectful.Exception (finally)+import Roon.Effect.WebSocket (WebSocket, frames, sendFrame)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (..), MooMessage (..), RequestId, Verb (..),+ encode, parse, requestIdFromWord, splitServiceMethod)+import Streamly.Data.Fold (catMaybes, one)+import Streamly.Data.Stream (Stream, fold, unfoldrM)+import Streamly.Data.Stream qualified as S (mapM)++-- | A reply to a request.+data Reply = Reply+ { final :: Bool+ -- ^ 'True' for @COMPLETE@: no other reply will follow.+ , name :: Text+ -- ^ The status, such as @Success@.+ , body :: Body+ }+ deriving stock (Eq, Show)++-- | A request that has been sent, and the replies it has received so far.+data Exchange = Exchange+ { requestId :: RequestId+ , name :: Text+ -- ^ The request name, for errors.+ , replies :: TQueue Reply+ , finished :: TVar Bool+ }++-- | Exchange MOO messages with a Roon Server.+data Moo :: Effect where+ -- The failures are returned rather than thrown: an error thrown by the+ -- interpreter would reach the Error handler around 'runMoo', not the one+ -- of the caller.+ OpenExchange :: Text -> Body -> Moo m (Either RoonError Exchange)+ NextReply :: Maybe Int -> Exchange -> Moo m (Either RoonError (Maybe Reply))+ CloseExchange :: Exchange -> Moo m ()+ NewSubscriptionKey :: Moo m Word64++type instance DispatchOf Moo = Dynamic++-- | Send a request, named @service/method@, and return the handle to read+-- its replies. Throws if the connection is closed.+openExchange :: (Moo :> es, Error RoonError :> es) => Text -> Body -> Eff es Exchange+openExchange name body = send (OpenExchange name body) >>= either throwError pure++-- | Wait for the next reply. 'Nothing' means the exchange is over: its+-- final reply has been read, or it was closed. Throws if the connection+-- closes first.+nextReply :: (Moo :> es, Error RoonError :> es) => Exchange -> Eff es (Maybe Reply)+nextReply = nextReplyBefore Nothing++-- | 'nextReply', waiting at most a number of microseconds. Throws+-- 'TimedOut' when no reply comes in time; the exchange stays open.+nextReplyWithin :: (Moo :> es, Error RoonError :> es) => Int -> Exchange -> Eff es (Maybe Reply)+nextReplyWithin = nextReplyBefore . Just++nextReplyBefore :: (Moo :> es, Error RoonError :> es) => Maybe Int -> Exchange -> Eff es (Maybe Reply)+nextReplyBefore limit exchange = send (NextReply limit exchange) >>= either throwError pure++-- | Stop listening to an exchange. Replies that arrive later are dropped.+-- This does not tell the server anything.+closeExchange :: Moo :> es => Exchange -> Eff es ()+closeExchange = send . CloseExchange++-- | A number not yet used as a subscription key on this connection.+-- Services tie a subscription to the key given when it is opened, and+-- expect the same key to end it.+newSubscriptionKey :: Moo :> es => Eff es Word64+newSubscriptionKey = send NewSubscriptionKey++-- | Send a request and wait for its final reply, at most+-- 'defaultRequestTimeout'. Intermediate replies are discarded.+request :: (Moo :> es, Error RoonError :> es) => Text -> Body -> Eff es Reply+request = requestWithin (Just defaultRequestTimeout)++-- | Thirty seconds, in microseconds.+defaultRequestTimeout :: Int+defaultRequestTimeout = 30_000_000++-- | 'request' with another limit, in microseconds, for each reply;+-- 'Nothing' waits as long as needed. Throws 'TimedOut' when a reply does+-- not come in time.+requestWithin :: (Moo :> es, Error RoonError :> es) => Maybe Int -> Text -> Body -> Eff es Reply+requestWithin limit name body = do+ exchange <- openExchange name body+ await exchange `finally` closeExchange exchange+ where+ await exchange =+ nextReplyBefore limit exchange >>= \case+ Just reply+ | reply.final -> pure reply+ | otherwise -> await exchange+ Nothing -> throwError ConnectionLost++-- | Send a request and consume its replies as a stream, which ends after+-- the final reply. The exchange is closed when the consumer returns.+withSubscription+ :: (Moo :> es, Error RoonError :> es)+ => Text+ -> Body+ -> (Stream (Eff es) Reply -> Eff es a)+ -> Eff es a+withSubscription name body consume = do+ exchange <- openExchange name body+ consume (unfoldrM (const (fmap (,()) <$> nextReply exchange)) ())+ `finally` closeExchange exchange++-- | Answers a request made by the server. Receives the service, the+-- method and the body; returns the status and the body of the reply.+--+-- The handler runs in a thread of its own, one request after the other,+-- so that a slow answer does not hold up the replies to the extension.+-- Changes it makes to thread-local effects, such as a local @State@, are+-- not seen by the action given to 'runMoo': share data through a+-- shared-state effect or a 'TVar'.+type RequestHandler es = Text -> Text -> Body -> Eff es (Text, Body)++-- | The service every extension must provide: the server calls it to+-- check that the extension is alive.+pingService :: Text+pingService = "com.roonlabs.ping:1"++-- | Answers pings and rejects everything else.+defaultRequestHandler :: RequestHandler es+defaultRequestHandler service method _+ | service /= pingService = invalid ("unknown service: " <> service)+ | method /= "ping" = invalid ("unknown request name (" <> service <> ") : " <> method)+ | otherwise = pure ("Success", NoBody)+ where+ invalid reason = pure ("InvalidRequest", JsonBody (object ["error" .= (reason :: Text)]))++data MooState = MooState+ { nextId :: TVar Word64+ , pending :: TVar (Map RequestId Exchange)+ , closed :: TVar (Maybe RoonError)+ -- ^ Why no more reply will come, once the receive loop has stopped.+ , nextSubscriptionKey :: TVar Word64+ , serverRequests :: TQueue MooMessage+ -- ^ Requests of the server, waiting for the handler.+ }++-- | Run MOO exchanges over a WebSocket. The handler answers the requests+-- that the server makes.+runMoo+ :: (WebSocket :> es, Concurrent :> es)+ => RequestHandler es+ -> Eff (Moo : es) a+ -> Eff es a+runMoo handler action = do+ state <- MooState <$> newTVarIO 0 <*> newTVarIO empty <*> newTVarIO Nothing <*> newTVarIO 0 <*> newTQueueIO+ withAsync (receiveLoop state) $ \_ ->+ withAsync (answerLoop state handler) $ \_ ->+ interpret_ (handleMoo state) action++handleMoo+ :: (WebSocket :> es, Concurrent :> es)+ => MooState+ -> Moo (Eff localEs) a+ -> Eff es a+handleMoo state = \case+ OpenExchange name body -> do+ opened <- atomically $ do+ readTVar state.closed >>= \case+ Just reason -> pure (Left reason)+ Nothing -> do+ requestId <- requestIdFromWord <$> readTVar state.nextId+ modifyTVar' state.nextId (+ 1)+ exchange <- Exchange requestId name <$> newTQueue <*> newTVar False+ modifyTVar' state.pending (insert requestId exchange)+ pure (Right exchange)+ case opened of+ Left reason -> pure (Left reason)+ Right exchange -> do+ sent <- sendFrame (encode MooMessage {verb = Request, name, requestId = exchange.requestId, headers = empty, body})+ if sent+ then pure (Right exchange)+ else Left ConnectionLost <$ atomically (forget state exchange)+ NextReply limit exchange -> do+ expired <- maybe (pure Nothing) (fmap Just . registerDelay) limit+ let timer = maybe retry (readTVar >=> bool retry (pure (Left (TimedOut exchange.name)))) expired+ atomically $+ (Right . Just <$> readTQueue exchange.replies)+ `orElse` ( readTVar exchange.finished >>= \case+ True -> pure (Right Nothing)+ False -> readTVar state.closed >>= maybe retry (pure . Left)+ )+ `orElse` timer+ CloseExchange exchange -> atomically (forget state exchange)+ NewSubscriptionKey -> atomically $ do+ key <- readTVar state.nextSubscriptionKey+ writeTVar state.nextSubscriptionKey (key + 1)+ pure key++-- | Remove an exchange from the routing table and mark it as over.+forget :: MooState -> Exchange -> STM ()+forget state exchange = do+ modifyTVar' state.pending (delete exchange.requestId)+ writeTVar exchange.finished True++-- | Route incoming frames until the connection closes or the server+-- breaks the protocol, then record why.+receiveLoop :: (WebSocket :> es, Concurrent :> es) => MooState -> Eff es ()+receiveLoop state =+ ( do+ failure <- fold (catMaybes one) (S.mapM (dispatch state) frames)+ closeConnection state (fromMaybe ConnectionLost failure)+ )+ `finally` closeConnection state ConnectionLost++-- | Record why no more reply will come. Keeps the first reason.+closeConnection :: Concurrent :> es => MooState -> RoonError -> Eff es ()+closeConnection state reason = atomically (modifyTVar' state.closed (Just . fromMaybe reason))++-- | Answer the requests of the server, in the order they came. If the+-- handler fails, the connection counts as lost: the server would no+-- longer get answers.+answerLoop :: (WebSocket :> es, Concurrent :> es) => MooState -> RequestHandler es -> Eff es ()+answerLoop state handler = forever answerNext `finally` closeConnection state ConnectionLost+ where+ answerNext = do+ message <- atomically (readTQueue state.serverRequests)+ (status, body) <- case splitServiceMethod message.name of+ Just (service, method) -> handler service method message.body+ Nothing -> pure ("InvalidRequest", JsonBody (object ["error" .= ("malformed request name: " <> message.name)]))+ void . sendFrame $+ encode MooMessage {verb = Complete, name = status, requestId = message.requestId, headers = empty, body}++-- | Handle one frame. Returns the reason to stop, if any.+dispatch :: Concurrent :> es => MooState -> ByteString -> Eff es (Maybe RoonError)+dispatch state frame = case parse frame of+ Left err -> pure (Just (ProtocolViolation err))+ Right message ->+ Nothing <$ case message.verb of+ Request -> atomically (writeTQueue state.serverRequests message)+ Continue -> deliver message False+ Complete -> deliver message True+ where+ -- A reply to an unknown or closed exchange is dropped.+ deliver message final = atomically $ do+ exchanges <- readTVar state.pending+ case M.lookup message.requestId exchanges of+ Nothing -> pure ()+ Just exchange -> do+ writeTQueue exchange.replies Reply {final, name = message.name, body = message.body}+ if final then forget state exchange else pure ()
+ src/Roon/Effect/TokenStore.hs view
@@ -0,0 +1,113 @@+-- The FileSystem constraint of openBinaryTempFile is what grants the+-- access; GHC cannot see it used, as with the lifted functions of+-- Effectful.FileSystem.+{-# OPTIONS_GHC -Wno-redundant-constraints #-}++-- |+-- Module : Roon.Effect.TokenStore+-- Description : Where the authorisation tokens are kept+-- License : BSD-3-Clause+--+-- When the user enables an extension in Roon, the server hands it a+-- token. Presenting that token on later connections skips the manual+-- step. There is one token per server, identified by its core id.+module Roon.Effect.TokenStore+ ( -- * Effect+ TokenStore (..)+ , loadToken+ , saveToken++ -- * Interpreters+ , runTokenStoreFile+ , defaultTokenFile+ , runTokenStorePure+ ) where++import Data.Aeson (decodeStrict, encode, object, withObject, (.:), (.=))+import Data.Aeson.Types (parseMaybe)+import Data.Map.Strict (Map, empty, insert)+import Data.Map.Strict qualified as M (lookup)+import Data.Text (Text, unpack)+import Effectful (Dispatch (Dynamic), DispatchOf, Eff, Effect, type (:>))+import Effectful.Dispatch.Dynamic (interpret_, reinterpret_, send)+import Effectful.Dispatch.Static (unsafeEff_)+import Effectful.Exception (bracketOnError)+import Effectful.FileSystem (FileSystem, XdgDirectory (XdgState),+ createDirectoryIfMissing, doesFileExist,+ getXdgDirectory, removeFile, renameFile)+import Effectful.FileSystem.IO (Handle, hClose)+import Effectful.FileSystem.IO.ByteString qualified as FS (readFile)+import Effectful.FileSystem.IO.ByteString.Lazy (hPut)+import Effectful.State.Static.Local (gets, modify, runState)+import System.FilePath (takeDirectory, (<.>), (</>))+import System.IO qualified as IO (openBinaryTempFile)++-- | Remember the token that each server gave to this extension.+data TokenStore :: Effect where+ LoadToken :: Text -> TokenStore m (Maybe Text)+ SaveToken :: Text -> Text -> TokenStore m ()++type instance DispatchOf TokenStore = Dynamic++-- | The token for the server with this core id, if one was saved.+loadToken :: TokenStore :> es => Text -> Eff es (Maybe Text)+loadToken = send . LoadToken++-- | Save the token for the server with this core id.+saveToken :: TokenStore :> es => Text -> Text -> Eff es ()+saveToken coreId token = send (SaveToken coreId token)++-- | Keep the tokens in a JSON file.+--+-- The file is created readable by its owner only, and replaced+-- atomically. A missing or unreadable file counts as empty: the cost is+-- to enable the extension in Roon once more.+runTokenStoreFile :: FileSystem :> es => FilePath -> Eff (TokenStore : es) a -> Eff es a+runTokenStoreFile path = interpret_ $ \case+ LoadToken coreId -> M.lookup coreId <$> readTokens path+ SaveToken coreId token -> do+ tokens <- readTokens path+ writeTokens path (insert coreId token tokens)++-- | The conventional place for the tokens of an extension:+-- @$XDG_STATE_HOME\/roon-api\/\<extension id\>.json@.+defaultTokenFile :: FileSystem :> es => Text -> Eff es FilePath+defaultTokenFile extensionId = do+ directory <- getXdgDirectory XdgState "roon-api"+ pure (directory </> unpack extensionId <.> "json")++-- | Keep the tokens in memory, starting from the given ones. Returns the+-- tokens held at the end. Meant for tests.+runTokenStorePure :: Map Text Text -> Eff (TokenStore : es) a -> Eff es (a, Map Text Text)+runTokenStorePure initial = reinterpret_ (runState initial) $ \case+ LoadToken coreId -> gets (M.lookup coreId)+ SaveToken coreId token -> modify (insert coreId token)++readTokens :: FileSystem :> es => FilePath -> Eff es (Map Text Text)+readTokens path = do+ exists <- doesFileExist path+ if not exists+ then pure empty+ else do+ contents <- FS.readFile path+ pure . maybe empty id $+ decodeStrict contents >>= parseMaybe (withObject "token file" (.: "tokens"))++writeTokens :: FileSystem :> es => FilePath -> Map Text Text -> Eff es ()+writeTokens path tokens = do+ let directory = takeDirectory path+ createDirectoryIfMissing True directory+ -- 'openBinaryTempFile' creates the file with mode 0600.+ bracketOnError+ (openBinaryTempFile directory "tokens.tmp")+ (\(temporary, handle) -> hClose handle >> removeFile temporary)+ ( \(temporary, handle) -> do+ hPut handle (encode (object ["tokens" .= tokens]))+ hClose handle+ renameFile temporary path+ )++-- | Lifted 'IO.openBinaryTempFile', which "Effectful.FileSystem.IO" does+-- not provide.+openBinaryTempFile :: FileSystem :> es => FilePath -> String -> Eff es (FilePath, Handle)+openBinaryTempFile directory template = unsafeEff_ (IO.openBinaryTempFile directory template)
+ src/Roon/Effect/WebSocket.hs view
@@ -0,0 +1,136 @@+-- |+-- Module : Roon.Effect.WebSocket+-- Description : The frame transport under the MOO protocol+-- License : BSD-3-Clause+--+-- A Roon Server exposes its extension API on @ws:\/\/host:port\/api@ and+-- exchanges binary frames there. This module adapts the 'WebSocket' effect+-- of @effectful-websockets@ to that use.+module Roon.Effect.WebSocket+ ( -- * Effect+ WebSocket+ , sendFrame+ , frames++ -- * Tracing+ , traceFrames+ , describeFrame++ -- * Interpreters+ , ServerAddress (..)+ , localServer+ , runWebSocket+ , runWebSocketWith+ ) where++import Data.Aeson (encode)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS (length, null)+import Data.ByteString.Lazy (toStrict)+import Data.Text (Text, pack, replace, toUpper)+import Data.Text qualified as T (length, take)+import Data.Text.Encoding (decodeUtf8Lenient, encodeUtf8)+import Effectful (Eff, IOE, inject, type (:>))+import Effectful.Error.Static (Error, runErrorNoCallStack, throwError)+import Effectful.WebSocket (Message (..), Traffic (..), WebSocket, messages,+ sendBinary, traced)+import Effectful.WebSocket qualified as W (runWebSocketWith)+import Effectful.WebSocket.Client (ClientConfig (closeTimeout), WebSocketError,+ clientConfig, runWebSocketClient)+import Effectful.WebSocket.Client qualified as WC (WebSocketError (ConnectFailed, NoPong))+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (..), MooMessage (..), RequestId (..), parse)+import Streamly.Data.Stream (Stream)++-- | Send one frame. 'False' means the connection is closed and the frame+-- was not sent.+sendFrame :: WebSocket :> es => ByteString -> Eff es Bool+sendFrame = sendBinary++-- | The frames received until the connection closes. Roon sends binary+-- frames; a text frame is passed on as its UTF-8 bytes.+frames :: WebSocket :> es => Stream (Eff es) ByteString+frames = fmap toBytes messages+ where+ toBytes = \case+ BinaryMessage bytes -> bytes+ TextMessage text -> encodeUtf8 text++-- | Where a Roon Server listens.+data ServerAddress = ServerAddress+ { host :: String+ , port :: Int+ }+ deriving stock (Eq, Show)++-- | A Roon Server on this machine, on its default port.+localServer :: ServerAddress+localServer = ServerAddress {host = "127.0.0.1", port = 9330}++-- | Interpret the effect with two actions on frames. Meant for tests.+runWebSocketWith+ :: (ByteString -> Eff es Bool)+ -- ^ Send a frame; 'False' when the connection is closed.+ -> Eff es (Maybe ByteString)+ -- ^ Receive a frame; 'Nothing' when the connection is closed.+ -> Eff (WebSocket : es) a+ -> Eff es a+runWebSocketWith sendAction receiveAction =+ W.runWebSocketWith+ (sendAction . \case BinaryMessage bytes -> bytes; TextMessage text -> encodeUtf8 text)+ (fmap BinaryMessage <$> receiveAction)++-- | Open a connection to a Roon Server and run an action over it.+--+-- The server is pinged every ten seconds, as the reference implementation+-- does. Throws 'ConnectFailed' if the connection cannot be opened, and+-- 'ConnectionLost' if the server stops answering pings before the action+-- is done. The action must keep receiving frames for pongs to be seen.+runWebSocket+ :: (IOE :> es, Error RoonError :> es)+ => ServerAddress+ -> Eff (WebSocket : es) a+ -> Eff es a+runWebSocket address action =+ runErrorNoCallStack @WebSocketError (runWebSocketClient config (inject action)) >>= \case+ Right value -> pure value+ Left (WC.ConnectFailed cause) -> throwError (ConnectFailed cause)+ Left WC.NoPong -> throwError ConnectionLost+ where+ -- Roon Server 2.75 never answers the close frame: waiting for it would+ -- last the whole limit. A short wait still lets Roon read our last+ -- frames, and us read its own, before the TCP connection goes.+ config = (clientConfig address.host address.port "/api") {closeTimeout = 100_000}++-- | Report every frame of an action, as one line of text each: @->@ for+-- the frames sent, @<-@ for those received. Bodies are cut after the given+-- number of characters.+traceFrames :: WebSocket :> es => Int -> (Text -> Eff es ()) -> Eff es a -> Eff es a+traceFrames limit report = traced $ \case+ Sent message sent -> report ("-> " <> describeMessage message <> (if sent then "" else " (not sent: connection closed)"))+ Received (Just message) -> report ("<- " <> describeMessage message)+ Received Nothing -> report "<- connection closed"+ where+ describeMessage = \case+ BinaryMessage bytes -> describeFrame limit bytes+ TextMessage text -> "text frame, not MOO: " <> cut limit text++-- | One line about a frame: its verb, name, request id and body, cut after+-- the given number of characters, or why it is not a MOO message.+describeFrame :: Int -> ByteString -> Text+describeFrame limit frame+ | BS.null frame = "empty frame"+ | otherwise = case parse frame of+ Left err -> "not a MOO message (" <> pack (show err) <> "): " <> cut limit (decodeUtf8Lenient frame)+ Right MooMessage {verb, name, requestId = RequestId requestId, body} ->+ toUpper (pack (show verb)) <> " " <> name <> " [" <> requestId <> "]" <> case body of+ NoBody -> ""+ JsonBody value -> " " <> cut limit (decodeUtf8Lenient (toStrict (encode value)))+ RawBody contentType bytes -> " " <> contentType <> ", " <> pack (show (BS.length bytes)) <> " bytes"++cut :: Int -> Text -> Text+cut limit text+ | T.length flat <= limit = flat+ | otherwise = T.take limit flat <> "... (" <> pack (show (T.length flat)) <> " characters)"+ where+ flat = replace "\n" "\\n" text
+ src/Roon/Error.hs view
@@ -0,0 +1,36 @@+-- |+-- Module : Roon.Error+-- Description : What can go wrong when talking to a Roon Server+-- License : BSD-3-Clause+module Roon.Error+ ( RoonError (..)+ ) where++import Data.Text (Text)+import Roon.Moo.Message (MooParseError)++-- | Failures reported through the @Error RoonError@ effect.+data RoonError+ = -- | The WebSocket could not be opened. Carries the cause.+ ConnectFailed Text+ | -- | The connection closed, or the server stopped answering pings.+ ConnectionLost+ | -- | The server sent a frame that is not a MOO message.+ ProtocolViolation MooParseError+ | -- | A request was answered with an unexpected status. Carries the+ -- request name, then the reply name.+ UnexpectedReply Text Text+ | -- | A reply had the expected status but not the expected body.+ -- Carries the request name, then the decoding error.+ UnexpectedReplyBody Text Text+ | -- | No reply came in time. Carries the request name.+ TimedOut Text+ | -- | Browsing ended on an error message from Roon. Carries the message.+ BrowseFailed Text+ | -- | An item expected while browsing, such as an action, is not there.+ -- Carries what was looked for.+ BrowseItemMissing Text+ | -- | An image could not be fetched: the server refused, answered+ -- something unexpected, or sent too large an image. Carries the reason.+ ImageFailed Text+ deriving stock (Eq, Show)
+ src/Roon/Image.hs view
@@ -0,0 +1,189 @@+-- |+-- Module : Roon.Image+-- Description : The images of a Roon Server, fetched over HTTP+-- License : BSD-3-Clause+--+-- Zones, queue items and browse items carry image keys. A Roon Server+-- serves the image of a key over HTTP, on the port of its extension API:+-- @http:\/\/host:port\/api\/image\/KEY@, with the size wanted in the query.+-- No registration and no token are needed.+--+-- The request goes through the t'Http' effect of @effectful-streamly-http@:+-- 'runImageHttp' reaches the server, and tests answer from a function.+--+-- Observed with Roon Server 2.75: an unknown key answers 404; an invalid+-- option answers 400 with a line of text; without options the image comes+-- in its stored size; @image\/png@ was asked and @image\/jpeg@ came back,+-- so the content type to trust is the one of the answer.+module Roon.Image+ ( -- * Options+ ImageOptions (..)+ , ImageSize (..)+ , Scale (..)+ , ImageFormat (..)+ , originalImage+ , fitWithin+ , imageTarget++ -- * Fetching+ , Image (..)+ , fetchImage++ -- * Reaching the server+ , runImageHttp+ , ImageLimits (..)+ , defaultImageLimits+ ) where++import Data.ByteString (ByteString, index, intercalate)+import Data.ByteString qualified as BS (elem, foldr, take)+import Data.ByteString.Builder (char7, toLazyByteString, word8)+import Data.ByteString.Char8 qualified as BS8 (pack)+import Data.ByteString.Lazy (toStrict)+import Data.Text (Text, strip)+import Data.Text qualified as T (pack, unwords)+import Data.Text.Encoding (decodeUtf8Lenient, encodeUtf8)+import Effectful (Eff, IOE, inject, type (:>))+import Effectful.Error.Static (Error, runErrorNoCallStack, throwError)+import Effectful.HTTP (Http, HttpError (..), HttpFailure, Limits (..),+ Response (..), Scheme (..), defaultLimits, fetch, get,+ header, runHttpClear)+import Effectful.HTTP qualified as H (HttpFailure (ConnectFailed, RequestFailed))+import Roon.Effect.WebSocket (ServerAddress (..))+import Roon.Error (RoonError (..))++-- | How Roon fits an image into the size asked.+data Scale+ = -- | The whole image inside the size, its proportions kept.+ Fit+ | -- | The size covered, its proportions kept, what exceeds cut off.+ Fill+ | -- | Exactly the size, proportions given up.+ Stretch+ deriving stock (Eq, Show)++-- | The size of the image wanted.+data ImageSize+ = -- | As stored by Roon.+ Original+ | -- | Scaled to a width and a height in pixels.+ Scaled Scale Int Int+ deriving stock (Eq, Show)++-- | The format to ask for.+data ImageFormat+ = Jpeg+ | Png+ deriving stock (Eq, Show)++-- | What to ask for. 'Nothing' as the format leaves the choice to Roon.+data ImageOptions = ImageOptions+ { size :: ImageSize+ , format :: Maybe ImageFormat+ }+ deriving stock (Eq, Show)++-- | The image as stored, in the format Roon chooses.+originalImage :: ImageOptions+originalImage = ImageOptions {size = Original, format = Nothing}++-- | The whole image within a square of that many pixels, in the format+-- Roon chooses.+fitWithin :: Int -> ImageOptions+fitWithin side = ImageOptions {size = Scaled Fit side side, format = Nothing}++-- | The path and the query that ask a Roon Server for an image.+imageTarget :: Text -> ImageOptions -> ByteString+imageTarget key options =+ "/api/image/" <> percentEncode (encodeUtf8 key) <> case sizeFields <> formatFields of+ [] -> ""+ fields -> "?" <> intercalate "&" [name <> "=" <> value | (name, value) <- fields]+ where+ sizeFields = case options.size of+ Original -> []+ Scaled scale width height ->+ [("scale", scaleName scale), ("width", BS8.pack (show width)), ("height", BS8.pack (show height))]+ formatFields = case options.format of+ Nothing -> []+ Just Jpeg -> [("format", "image/jpeg")]+ Just Png -> [("format", "image/png")]+ scaleName = \case+ Fit -> "fit"+ Fill -> "fill"+ Stretch -> "stretch"++-- | Percent-encode every byte that is not unreserved (RFC 3986).+percentEncode :: ByteString -> ByteString+percentEncode = toStrict . toLazyByteString . BS.foldr (\byte rest -> encode byte <> rest) mempty+ where+ encode byte+ | unreserved byte = word8 byte+ | otherwise = char7 '%' <> hexDigit (byte `div` 16) <> hexDigit (byte `mod` 16)+ hexDigit digit = word8 (index "0123456789ABCDEF" (fromIntegral digit))+ unreserved byte =+ (byte >= 48 && byte <= 57)+ || (byte >= 65 && byte <= 90)+ || (byte >= 97 && byte <= 122)+ || BS.elem byte "-._~"++-- | An image as served by Roon.+data Image = Image+ { contentType :: Text+ -- ^ For example @image\/jpeg@. Empty when the server names none.+ , bytes :: ByteString+ }+ deriving stock (Eq, Show)++-- | Fetch the image of a key from a Roon Server.+--+-- Throws 'ImageFailed' when the server refuses (unknown key, invalid+-- option). What the connection itself can do wrong is up to the+-- interpreter of t'Http': see 'runImageHttp'.+fetchImage :: (Http :> es, Error RoonError :> es) => ServerAddress -> Text -> ImageOptions -> Eff es Image+fetchImage address key options = do+ response <- fetch Http (get address.host address.port (imageTarget key options))+ if response.status /= 200+ then+ -- Roon explains a refusal in a line of text.+ throwError . ImageFailed . strip . T.unwords $+ [T.pack (show response.status), decodeUtf8Lenient response.reason, decodeUtf8Lenient (BS.take 1024 response.body)]+ else pure Image {contentType = maybe "" decodeUtf8Lenient (header "content-type" response), bytes = response.body}++-- | The bounds of a fetch.+data ImageLimits = ImageLimits+ { microseconds :: Int+ -- ^ For each wait: for the connection to open, and for the server to go+ -- on once it is.+ , maxBytes :: Int+ -- ^ For the image.+ }+ deriving stock (Eq, Show)++-- | Thirty seconds and 32 MiB.+defaultImageLimits :: ImageLimits+defaultImageLimits = ImageLimits {microseconds = 30_000_000, maxBytes = 32 * 1024 * 1024}++-- | Reach the Roon Server for its images: in clear, one connection for+-- each image, within limits.+--+-- Throws 'ConnectFailed' when the connection fails, 'TimedOut' when the+-- server takes too long, and 'ImageFailed' when it answers something that+-- is not HTTP or sends too large an image.+runImageHttp :: (IOE :> es, Error RoonError :> es) => ImageLimits -> Eff (Http : es) a -> Eff es a+runImageHttp limits action =+ runErrorNoCallStack (runHttpClear bounds (inject action)) >>= either (throwError . failure) pure+ where+ bounds =+ defaultLimits+ { connectTimeout = Just limits.microseconds+ , idleTimeout = Just limits.microseconds+ , maxBodySize = Just limits.maxBytes+ }+ failure :: HttpFailure -> RoonError+ failure = \case+ H.ConnectFailed cause -> ConnectFailed cause+ H.RequestFailed ConnectTimedOut -> TimedOut "image"+ H.RequestFailed ResponseTimedOut -> TimedOut "image"+ H.RequestFailed (BodyTooLarge limit) -> ImageFailed ("the image is larger than " <> T.pack (show limit) <> " bytes")+ H.RequestFailed problem -> ImageFailed (T.pack (show problem))+ other -> ImageFailed (T.pack (show other))
+ src/Roon/Moo/Message.hs view
@@ -0,0 +1,251 @@+-- |+-- Module : Roon.Moo.Message+-- Description : The MOO message format used by the Roon extension API+-- License : BSD-3-Clause+--+-- MOO is the request and response protocol that a Roon Server and its+-- extensions speak over a WebSocket. Each WebSocket binary frame carries+-- exactly one message:+--+-- > MOO/1 REQUEST com.roonlabs.registry:1/info+-- > Request-Id: 0+-- > Content-Length: 2+-- > Content-Type: application/json+-- >+-- > {}+--+-- The first line gives the protocol version, a 'Verb' and a name. Header+-- lines follow, then an empty line, then an optional body whose size is+-- given by @Content-Length@. Lines end with a single line feed.+module Roon.Moo.Message+ ( -- * Messages+ MooMessage (..)+ , Verb (..)+ , RequestId (..)+ , Body (..)++ -- * Encoding and parsing+ , encode+ , parse+ , MooParseError (..)++ -- * Helpers+ , requestIdFromWord+ , splitServiceMethod+ ) where++import Control.Monad (when)+import Data.Aeson (Value, eitherDecodeStrict)+import Data.Aeson qualified as J (encode)+import Data.ByteString (ByteString, breakSubstring, empty)+import Data.ByteString qualified as BS (drop, length, null, take)+import Data.ByteString.Builder (Builder, intDec, toLazyByteString)+import Data.ByteString.Builder qualified as BSB (byteString)+import Data.ByteString.Lazy (toStrict)+import Data.Map.Strict (Map, delete, foldMapWithKey, fromList)+import Data.Map.Strict qualified as M (lookup)+import Data.Text (Text, breakOn, pack, stripPrefix, unpack)+import Data.Text qualified as T (null)+import Data.Text.Encoding (decodeUtf8', encodeUtf8)+import Data.Word (Word64)+import FlatParse.Basic (Parser, Pos (Pos), Result (Err, Fail, OK), anyWord8,+ byteStringOf, cut, eof, failed, fails, getPos, many,+ runParser, skipMany, skipSatisfyAscii, skipSome, word8)+import FlatParse.Basic qualified as FB (byteString)+import Text.Read (readMaybe)++-- | The kind of a MOO message.+data Verb+ = -- | Opens an exchange. The message name is @service/method@.+ Request+ | -- | An intermediate reply; more will follow for the same request.+ Continue+ | -- | The final reply to a request.+ Complete+ deriving stock (Eq, Ord, Show, Enum, Bounded)++-- | Identifies an exchange. Replies carry the identifier of the request+-- they answer. Roon uses decimal counters, but nothing in the protocol+-- requires it, so the identifier is kept as received.+newtype RequestId = RequestId Text+ deriving stock (Eq, Ord, Show)++-- | The identifier for the n-th request sent on a connection.+requestIdFromWord :: Word64 -> RequestId+requestIdFromWord = RequestId . pack . show++-- | The payload of a message.+data Body+ = NoBody+ | -- | Sent and recognised with the @application/json@ content type.+ JsonBody Value+ | -- | Any other content type, with its bytes. Never empty: an empty+ -- payload is 'NoBody'.+ RawBody Text ByteString+ deriving stock (Eq, Show)++-- | One MOO message.+data MooMessage = MooMessage+ { verb :: Verb+ , name :: Text+ -- ^ @service/method@ for a 'Request'; a status such as @Success@ for+ -- 'Continue' and 'Complete'.+ , requestId :: RequestId+ , headers :: Map Text Text+ -- ^ Headers other than @Request-Id@, @Content-Length@ and+ -- @Content-Type@, which are represented by the other fields.+ , body :: Body+ }+ deriving stock (Eq, Show)++-- | Why a frame is not a valid MOO message.+data MooParseError+ = -- | No empty line ends the header block.+ MissingHeaderEnd+ | -- | The header block is malformed, at this byte offset.+ MalformedHeader Int String+ | UnknownVerb Text+ | MissingRequestId+ | InvalidContentLength Text+ | -- | A @Content-Type@ without a @Content-Length@.+ ContentTypeWithoutLength+ | -- | A body without a @Content-Type@.+ MissingContentType+ | -- | Bytes after the headers although no @Content-Length@ announced+ -- them.+ UnexpectedBody+ | -- | Fewer body bytes than announced: expected, then received.+ TruncatedBody Int Int+ | InvalidJson String+ deriving stock (Eq, Show)++-- | Split the name of a 'Request' into its service and its method, at the+-- first slash.+--+-- >>> splitServiceMethod "com.roonlabs.ping:1/ping"+-- Just ("com.roonlabs.ping:1","ping")+splitServiceMethod :: Text -> Maybe (Text, Text)+splitServiceMethod full = case breakOn "/" full of+ (service, rest)+ | not (T.null service), Just method <- stripPrefix "/" rest ->+ Just (service, method)+ _ -> Nothing++-- | Serialise a message into the bytes of one WebSocket binary frame.+encode :: MooMessage -> ByteString+encode msg =+ toStrict . toLazyByteString $+ mconcat+ [ "MOO/1 "+ , verbBuilder msg.verb+ , " "+ , text msg.name+ , "\n"+ , header "Request-Id" (let RequestId rid = msg.requestId in rid)+ , foldMapWithKey header msg.headers+ , contentHeaders+ , "\n"+ , BSB.byteString payload+ ]+ where+ text = BSB.byteString . encodeUtf8+ header key value = text key <> ": " <> text value <> "\n"+ (contentType, payload) = case msg.body of+ NoBody -> (Nothing, empty)+ JsonBody value -> (Just jsonContentType, toStrict (J.encode value))+ RawBody ctype bytes -> (Just ctype, bytes)+ contentHeaders = case contentType of+ Nothing -> mempty+ Just ctype ->+ "Content-Length: "+ <> intDec (BS.length payload)+ <> "\n"+ <> header "Content-Type" ctype++verbBuilder :: Verb -> Builder+verbBuilder = \case+ Request -> "REQUEST"+ Continue -> "CONTINUE"+ Complete -> "COMPLETE"++jsonContentType :: Text+jsonContentType = "application/json"++-- | Parse the bytes of one WebSocket frame.+--+-- Like the reference implementation, this ignores bytes beyond+-- @Content-Length@ and keeps the last occurrence of a repeated header.+parse :: ByteString -> Either MooParseError MooMessage+parse frame = do+ let (headerBlock, rest) = breakSubstring "\n\n" frame+ when (BS.null rest) (Left MissingHeaderEnd)+ let payload = BS.drop 2 rest+ -- Keep the line feed that ends the last header line, so that the block+ -- is a sequence of terminated lines.+ let headerLines = BS.take (BS.length headerBlock + 1) frame+ (verbName, name, headerList) <-+ case runParser headerBlockParser headerLines of+ OK parsed _ -> Right parsed+ -- The position of an error is counted from the end of the input.+ Err (Pos fromEnd, reason) -> Left (MalformedHeader (BS.length headerLines - fromEnd) reason)+ Fail -> Left (MalformedHeader 0 "not a MOO header block")+ verb <- case verbName of+ "REQUEST" -> Right Request+ "CONTINUE" -> Right Continue+ "COMPLETE" -> Right Complete+ other -> Left (UnknownVerb other)+ let allHeaders = fromList headerList+ headers = foldr delete allHeaders ["Request-Id", "Content-Length", "Content-Type"]+ contentType = M.lookup "Content-Type" allHeaders+ requestId <- maybe (Left MissingRequestId) (Right . RequestId) (M.lookup "Request-Id" allHeaders)+ contentLength <- case M.lookup "Content-Length" allHeaders of+ Nothing -> Right Nothing+ Just raw -> case readMaybe (unpack raw) of+ Just n | n >= 0 -> Right (Just n)+ _ -> Left (InvalidContentLength raw)+ body <- case (contentLength, contentType) of+ (Nothing, Just _) -> Left ContentTypeWithoutLength+ (Nothing, Nothing)+ | BS.null payload -> Right NoBody+ | otherwise -> Left UnexpectedBody+ (Just 0, _) -> Right NoBody+ (Just _, Nothing) -> Left MissingContentType+ (Just n, Just ctype)+ | BS.length payload < n -> Left (TruncatedBody n (BS.length payload))+ | ctype == jsonContentType ->+ either (Left . InvalidJson) (Right . JsonBody) (eitherDecodeStrict (BS.take n payload))+ | otherwise -> Right (RawBody ctype (BS.take n payload))+ pure MooMessage {verb, name, requestId, headers, body}++-- | The first line and the header lines, each ended by a line feed.+-- Yields the verb, the name and the headers in order. A line that is not+-- what it should be is an error, with the position where it starts.+headerBlockParser :: Parser (Pos, String) (Text, Text, [(Text, Text)])+headerBlockParser = do+ (verbName, name) <- wholeLine "the first line is not MOO/1, a verb in capitals and a name" $ do+ FB.byteString "MOO/1 "+ verbName <- utf8 (byteStringOf (skipSome (skipSatisfyAscii (\char -> char >= 'A' && char <= 'Z'))))+ word8 space+ name <- restOfLine+ pure (verbName, name)+ headerList <- many (fails eof *> wholeLine "a header line is not a key, a colon and a value" headerLine)+ eof+ pure (verbName, name, headerList)+ where+ -- @Key: value@. The spaces after the colon are optional.+ headerLine = do+ key <- utf8 (byteStringOf (skipSome (notByte colon)))+ word8 colon+ skipMany (word8 space)+ value <- restOfLine+ pure (key, value)+ restOfLine = utf8 (byteStringOf (skipMany (notByte lineFeed))) <* word8 lineFeed+ -- A line, or an error that names what is wrong and where it starts.+ wholeLine problem content = do+ start <- getPos+ content `cut` (start, problem)+ utf8 bytesParser = bytesParser >>= either (const failed) pure . decodeUtf8'+ notByte excluded = anyWord8 >>= \byte -> if byte == excluded || byte == lineFeed then failed else pure ()+ space = 32+ colon = 58+ lineFeed = 10
+ src/Roon/Registry.hs view
@@ -0,0 +1,148 @@+-- |+-- Module : Roon.Registry+-- Description : Introducing an extension to a Roon Server+-- License : BSD-3-Clause+--+-- The registry service is the first thing an extension talks to. It tells+-- which server this is, then registers the extension. When the extension+-- asks for services and the server does not know it yet, the server only+-- answers the registration once the user has enabled the extension, in+-- Roon under Settings, Extensions. An extension that asks for no service+-- is registered at once.+module Roon.Registry+ ( -- * Describing the extension+ ExtensionInfo (..)++ -- * Describing the server+ , CoreInfo (..)+ , Registration (..)++ -- * Requests+ , info+ , register+ , registerWithin+ , registryService+ ) where++import Data.Aeson (FromJSON (..), Value, object, withObject, (.:), (.:?), (.=))+import Data.Maybe (catMaybes, fromMaybe)+import Data.Text (Text)+import Effectful (Eff, type (:>))+import Effectful.Error.Static (Error, throwError)+import Effectful.Exception (finally)+import Roon.Effect.Moo (Exchange, Moo, Reply, closeExchange, nextReply,+ nextReplyWithin, openExchange, request)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (..))+import Roon.Service (expect)++-- | What an extension tells the server about itself. Roon shows the+-- display name, the version and the publisher to the user.+data ExtensionInfo = ExtensionInfo+ { extensionId :: Text+ -- ^ A stable, unique identifier, such as @com.example.my-extension@.+ -- The server ties its authorisation to it.+ , displayName :: Text+ , displayVersion :: Text+ , publisher :: Text+ , email :: Text+ , website :: Maybe Text+ , requiredServices :: [Text]+ -- ^ Services the server must offer, such as+ -- @com.roonlabs.transport:2@.+ , optionalServices :: [Text]+ , providedServices :: [Text]+ -- ^ Services the extension offers to the server.+ }+ deriving stock (Eq, Show)++-- | The identity of a Roon Server.+data CoreInfo = CoreInfo+ { coreId :: Text+ , displayName :: Text+ , displayVersion :: Text+ }+ deriving stock (Eq, Show)++instance FromJSON CoreInfo where+ parseJSON = withObject "CoreInfo" $ \fields ->+ CoreInfo <$> fields .: "core_id" <*> fields .: "display_name" <*> fields .: "display_version"++-- | What the server answers to a successful registration.+data Registration = Registration+ { core :: CoreInfo+ , token :: Text+ -- ^ To present on later connections.+ , grantedServices :: [Text]+ -- ^ The services the server grants, among those asked for.+ }+ deriving stock (Eq, Show)++instance FromJSON Registration where+ parseJSON value =+ withObject+ "Registration"+ ( \fields ->+ Registration+ <$> parseJSON value+ <*> fields .: "token"+ <*> (fromMaybe [] <$> fields .:? "provided_services")+ )+ value++-- | The name of the registry service, version included.+registryService :: Text+registryService = "com.roonlabs.registry:1"++-- | Ask the server who it is. Works before registration.+info :: (Moo :> es, Error RoonError :> es) => Eff es CoreInfo+info = do+ reply <- request name NoBody+ expect name "Success" reply+ where+ name = registryService <> "/info"++-- | Register the extension, with the token from an earlier registration+-- if there is one.+--+-- Without a valid token for the services asked for, this waits until the+-- user enables the extension in Roon.+register :: (Moo :> es, Error RoonError :> es) => ExtensionInfo -> Maybe Text -> Eff es Registration+register = registerWith nextReply++-- | 'register', waiting at most a number of microseconds for the server,+-- and so for the user. Throws 'TimedOut' when the time is up.+registerWithin :: (Moo :> es, Error RoonError :> es) => Int -> ExtensionInfo -> Maybe Text -> Eff es Registration+registerWithin limit = registerWith (nextReplyWithin limit)++registerWith+ :: (Moo :> es, Error RoonError :> es)+ => (Exchange -> Eff es (Maybe Reply))+ -> ExtensionInfo+ -> Maybe Text+ -> Eff es Registration+registerWith wait extension token = do+ -- The server answers with a first reply and may keep the exchange open;+ -- only that first reply matters here.+ exchange <- openExchange name (JsonBody (registrationRequest extension token))+ reply <- wait exchange `finally` closeExchange exchange+ maybe (throwError ConnectionLost) (expect name "Registered") reply+ where+ name = registryService <> "/register"++registrationRequest :: ExtensionInfo -> Maybe Text -> Value+registrationRequest extension token =+ object $+ [ "extension_id" .= extension.extensionId+ , "display_name" .= extension.displayName+ , "display_version" .= extension.displayVersion+ , "publisher" .= extension.publisher+ , "email" .= extension.email+ , "required_services" .= extension.requiredServices+ , "optional_services" .= extension.optionalServices+ , "provided_services" .= extension.providedServices+ ]+ <> catMaybes+ [ ("website" .=) <$> extension.website+ , ("token" .=) <$> token+ ]
+ src/Roon/Service.hs view
@@ -0,0 +1,111 @@+-- |+-- Module : Roon.Service+-- Description : Building blocks for the services of a Roon Server+-- License : BSD-3-Clause+--+-- What the service modules share: checking the status of a reply,+-- decoding its body, and the subscription convention of Roon services.+module Roon.Service+ ( -- * Replies+ expect+ , expectSuccess+ , call++ -- * Subscriptions+ , subscribe+ , subscriptionUpdates+ ) where++import Data.Aeson (FromJSON (..), Value (..), object, (.=))+import Data.Aeson.KeyMap (empty)+import Data.Aeson.Types (Pair, parseEither)+import Data.Text (Text, pack)+import Effectful (Eff, type (:>))+import Effectful.Error.Static (Error, catchError, throwError)+import Effectful.Exception (finally)+import Roon.Effect.Moo (Moo, Reply (..), closeExchange, newSubscriptionKey,+ nextReply, openExchange, request)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (..))+import Streamly.Data.Stream (Stream, mapMaybeM, unfoldrM)++-- | Check the status of a reply and decode its JSON body. Takes the+-- request name, for the error, and the expected status.+expect :: (FromJSON a, Error RoonError :> es) => Text -> Text -> Reply -> Eff es a+expect requestName status reply+ | reply.name /= status = throwError (UnexpectedReply requestName reply.name)+ | otherwise = case reply.body of+ JsonBody value -> decodeBody requestName value+ _ -> throwError (UnexpectedReplyBody requestName "not a JSON body")++-- | Check that a reply says @Success@, whatever its body.+expectSuccess :: Error RoonError :> es => Text -> Reply -> Eff es ()+expectSuccess requestName reply+ | reply.name /= "Success" = throwError (UnexpectedReply requestName reply.name)+ | otherwise = pure ()++-- | Send a request that only answers @Success@ or a failure.+call :: (Moo :> es, Error RoonError :> es) => Text -> Value -> Eff es ()+call name body = request name (JsonBody body) >>= expectSuccess name++decodeBody :: (FromJSON a, Error RoonError :> es) => Text -> Value -> Eff es a+decodeBody requestName = either (throwError . UnexpectedReplyBody requestName . pack) pure . parseEither parseJSON++-- | Subscribe to a topic of a service, such as the zones of+-- @com.roonlabs.transport:2@, and consume the replies.+--+-- The request is @service/subscribe_topic@, its body the arguments with a+-- @subscription_key@ added. The server answers @Subscribed@, then+-- @Changed@ as often as needed, and @Unsubscribed@ as the final reply+-- once the subscription ends. When the consumer returns, this sends+-- @service/unsubscribe_topic@ with the same key, without waiting for the+-- answer; a connection already lost is not an error at that point.+subscribe+ :: (Moo :> es, Error RoonError :> es)+ => Text+ -- ^ The service.+ -> Text+ -- ^ The topic.+ -> [Pair]+ -- ^ The arguments.+ -> (Stream (Eff es) Reply -> Eff es a)+ -> Eff es a+subscribe service topic arguments consume = do+ key <- newSubscriptionKey+ let withKey = object (("subscription_key" .= key) : arguments)+ exchange <- openExchange (service <> "/subscribe_" <> topic) (JsonBody withKey)+ consume (unfoldrM (const (fmap (,()) <$> nextReply exchange)) ())+ `finally` (unsubscribe key >> closeExchange exchange)+ where+ unsubscribe key =+ ( do+ stop <- openExchange (service <> "/unsubscribe_" <> topic) (JsonBody (object ["subscription_key" .= key]))+ closeExchange stop+ )+ `catchError` \_ (_ :: RoonError) -> pure ()++-- | Decode the replies of a subscription. The first argument decodes the+-- body of @Subscribed@, the second that of @Changed@. The stream ends with+-- @Unsubscribed@, the final reply; any other status is an error.+subscriptionUpdates+ :: (FromJSON initial, FromJSON change, Error RoonError :> es)+ => Text+ -- ^ The request name, for errors.+ -> (initial -> update)+ -> (change -> update)+ -> Stream (Eff es) Reply+ -> Stream (Eff es) update+subscriptionUpdates requestName fromInitial fromChange = mapMaybeM decode+ where+ decode reply = case reply.name of+ "Subscribed" -> Just . fromInitial <$> replyBody requestName reply+ "Changed" -> Just . fromChange <$> replyBody requestName reply+ "Unsubscribed" -> pure Nothing+ other -> throwError (UnexpectedReply requestName other)++-- | Decode the body of a reply; a missing body reads as an empty object.+replyBody :: (FromJSON a, Error RoonError :> es) => Text -> Reply -> Eff es a+replyBody requestName reply = case reply.body of+ JsonBody value -> decodeBody requestName value+ NoBody -> decodeBody requestName (Object empty)+ _ -> throwError (UnexpectedReplyBody requestName "not a JSON body")
+ src/Roon/Transport.hs view
@@ -0,0 +1,686 @@+{-# LANGUAGE RecordWildCards #-}++-- |+-- Module : Roon.Transport+-- Description : Zones, outputs and playback control+-- License : BSD-3-Clause+--+-- The transport service, @com.roonlabs.transport:2@: what each zone plays,+-- its queue, and the controls on playback, volume and zone settings.+--+-- A zone plays one queue through one or more outputs, grouped. Requests+-- that act on a zone also accept one of its outputs ('ZoneOrOutput').+module Roon.Transport+ ( transportService++ -- * Identifiers+ , ZoneId (..)+ , OutputId (..)+ , ZoneOrOutput (..)++ -- * Zones and outputs+ , Zone (..)+ , PlaybackState (..)+ , ZoneSettings (..)+ , Loop (..)+ , NowPlaying (..)+ , DisplayLines (..)+ , Output (..)+ , Volume (..)+ , VolumeType (..)+ , SourceControl (..)+ , SourceControlStatus (..)+ , getZones+ , getOutputs++ -- * Following the zones+ , ZoneEvent (..)+ , ZoneChanges (..)+ , SeekChange (..)+ , subscribeZones+ , applyZoneEvent+ , zones+ , zoneViews+ , zoneViewsEvery++ -- * The queue+ , QueueItem (..)+ , QueueEvent (..)+ , QueueChange (..)+ , subscribeQueue+ , applyQueueEvent+ , queue++ -- * Following zones and queues together+ , TransportEvent (..)+ , subscribeTransport+ , playFromHere++ -- * Controls+ , Control (..)+ , control+ , pauseAll+ , Seek (..)+ , seek+ , SettingsChange (..)+ , LoopChange (..)+ , noSettingsChange+ , changeSettings+ , VolumeChange (..)+ , changeVolume+ , mute+ , muteAll+ , transferZone+ ) where++import Data.Aeson (FromJSON (..), ToJSON (..), Value, object, withObject,+ withText, (.!=), (.:), (.:?), (.=))+import Data.Aeson.Types (Pair)+import Data.Map.Strict (Map, adjust, delete, empty, fromList, union)+import Data.Maybe (catMaybes)+import Data.Text (Text)+import Effectful (Eff, IOE, MonadIO (..), type (:>))+import Effectful.Error.Static (Error)+import Effectful.Streamly.Stream (parList)+import GHC.Clock (getMonotonicTime)+import Roon.Effect.Moo (Moo, request)+import Roon.Error (RoonError)+import Roon.Moo.Message (Body (..))+import Roon.Service (call, expect, subscribe, subscriptionUpdates)+import Streamly.Data.Fold (Fold)+import Streamly.Data.Fold qualified as F (foldl')+import Streamly.Data.Scanl (mkScanl, mkScanlM)+import Streamly.Data.Stream (Stream, mapMaybe, postscanl)++-- | The name of the transport service, version included.+transportService :: Text+transportService = "com.roonlabs.transport:2"++-- Identifiers++-- | What names a zone in Roon.+newtype ZoneId = ZoneId Text+ deriving stock (Show)+ deriving newtype (Eq, Ord, FromJSON, ToJSON)++-- | What names an output in Roon.+newtype OutputId = OutputId Text+ deriving stock (Show)+ deriving newtype (Eq, Ord, FromJSON, ToJSON)++-- | What requests that act on a zone accept: the zone, or one of its+-- outputs.+class ZoneOrOutput a where+ zoneOrOutputId :: a -> Text++instance ZoneOrOutput ZoneId where+ zoneOrOutputId (ZoneId zoneId) = zoneId++instance ZoneOrOutput OutputId where+ zoneOrOutputId (OutputId outputId) = outputId++-- Zones and outputs++-- | Where music plays: one output, or several grouped together.+data Zone = Zone+ { zoneId :: ZoneId+ , displayName :: Text+ , outputs :: [Output]+ , state :: PlaybackState+ , isPreviousAllowed :: Bool+ , isNextAllowed :: Bool+ , isPauseAllowed :: Bool+ , isPlayAllowed :: Bool+ , isSeekAllowed :: Bool+ , queueItemsRemaining :: Maybe Int+ , queueTimeRemaining :: Maybe Int+ -- ^ In seconds.+ , settings :: Maybe ZoneSettings+ , nowPlaying :: Maybe NowPlaying+ -- ^ Absent when nothing is loaded.+ }+ deriving stock (Eq, Show)++instance FromJSON Zone where+ parseJSON = withObject "Zone" $ \fields ->+ Zone+ <$> fields .: "zone_id"+ <*> fields .: "display_name"+ <*> fields .:? "outputs" .!= []+ <*> fields .: "state"+ <*> fields .:? "is_previous_allowed" .!= False+ <*> fields .:? "is_next_allowed" .!= False+ <*> fields .:? "is_pause_allowed" .!= False+ <*> fields .:? "is_play_allowed" .!= False+ <*> fields .:? "is_seek_allowed" .!= False+ <*> fields .:? "queue_items_remaining"+ <*> fields .:? "queue_time_remaining"+ <*> fields .:? "settings"+ <*> fields .:? "now_playing"++-- | Unknown states are kept as they are named.+data PlaybackState = Playing | Paused | Loading | Stopped | OtherState Text+ deriving stock (Eq, Show)++instance FromJSON PlaybackState where+ parseJSON = withText "PlaybackState" $ \case+ "playing" -> pure Playing+ "paused" -> pure Paused+ "loading" -> pure Loading+ "stopped" -> pure Stopped+ other -> pure (OtherState other)++-- | The playback options of a zone.+data ZoneSettings = ZoneSettings+ { loop :: Loop+ , shuffle :: Bool+ , autoRadio :: Bool+ }+ deriving stock (Eq, Show)++instance FromJSON ZoneSettings where+ parseJSON = withObject "ZoneSettings" $ \fields ->+ ZoneSettings <$> fields .: "loop" <*> fields .: "shuffle" <*> fields .: "auto_radio"++-- | Whether playback repeats: the whole queue, the current track, or+-- nothing. 'OtherLoop' keeps a value this library does not know.+data Loop = LoopQueue | LoopOne | LoopDisabled | OtherLoop Text+ deriving stock (Eq, Show)++instance FromJSON Loop where+ parseJSON = withText "Loop" $ \case+ "loop" -> pure LoopQueue+ "loop_one" -> pure LoopOne+ "disabled" -> pure LoopDisabled+ other -> pure (OtherLoop other)++-- | What a zone is playing.+data NowPlaying = NowPlaying+ { seekPosition :: Maybe Int+ -- ^ In seconds.+ , length :: Maybe Int+ -- ^ In seconds.+ , imageKey :: Maybe Text+ , artistImageKeys :: [Text]+ , oneLine :: DisplayLines+ , twoLine :: DisplayLines+ , threeLine :: DisplayLines+ -- ^ For three lines, Roon gives the title, the artists and the album.+ }+ deriving stock (Eq, Show)++instance FromJSON NowPlaying where+ parseJSON = withObject "NowPlaying" $ \fields ->+ NowPlaying+ <$> fields .:? "seek_position"+ <*> fields .:? "length"+ <*> fields .:? "image_key"+ <*> fields .:? "artist_image_keys" .!= []+ <*> fields .: "one_line"+ <*> fields .: "two_line"+ <*> fields .: "three_line"++-- | The text Roon prepares for displays of one, two or three lines.+data DisplayLines = DisplayLines+ { line1 :: Text+ , line2 :: Maybe Text+ , line3 :: Maybe Text+ }+ deriving stock (Eq, Show)++instance FromJSON DisplayLines where+ parseJSON = withObject "DisplayLines" $ \fields ->+ DisplayLines <$> fields .: "line1" <*> fields .:? "line2" <*> fields .:? "line3"++-- | A device, or an endpoint, that plays the audio of a zone.+data Output = Output+ { outputId :: OutputId+ , zoneId :: ZoneId+ , displayName :: Text+ , volume :: Maybe Volume+ -- ^ Absent when Roon does not control the volume of this output.+ , sourceControls :: [SourceControl]+ , canGroupWithOutputIds :: [OutputId]+ }+ deriving stock (Eq, Show)++instance FromJSON Output where+ parseJSON = withObject "Output" $ \fields ->+ Output+ <$> fields .: "output_id"+ <*> fields .: "zone_id"+ <*> fields .: "display_name"+ <*> fields .:? "volume"+ <*> fields .:? "source_controls" .!= []+ <*> fields .:? "can_group_with_output_ids" .!= []++-- | Volume values are not integers, and their range may extend on both+-- sides of zero. An incremental control only has the type: it is driven+-- by steps of one, up or down ('RelativeStep').+data Volume = Volume+ { volumeType :: VolumeType+ , minimum :: Maybe Double+ , maximum :: Maybe Double+ , value :: Maybe Double+ , step :: Maybe Double+ , isMuted :: Maybe Bool+ }+ deriving stock (Eq, Show)++instance FromJSON Volume where+ parseJSON = withObject "Volume" $ \fields ->+ Volume+ <$> fields .:? "type" .!= VolumeNumber+ <*> fields .:? "min"+ <*> fields .:? "max"+ <*> fields .:? "value"+ <*> fields .:? "step"+ <*> fields .:? "is_muted"++-- | The reference documentation asks to treat an unknown type like a+-- number; it is kept here as named.+data VolumeType = VolumeDecibel | VolumeNumber | VolumeIncremental | OtherVolumeType Text+ deriving stock (Eq, Show)++instance FromJSON VolumeType where+ parseJSON = withText "VolumeType" $ \case+ "db" -> pure VolumeDecibel+ "number" -> pure VolumeNumber+ "incremental" -> pure VolumeIncremental+ other -> pure (OtherVolumeType other)++-- | A device that Roon can switch on, off or to its input, such as an+-- amplifier.+data SourceControl = SourceControl+ { controlKey :: Text+ , displayName :: Text+ , status :: SourceControlStatus+ , supportsStandby :: Bool+ }+ deriving stock (Eq, Show)++instance FromJSON SourceControl where+ parseJSON = withObject "SourceControl" $ \fields ->+ SourceControl+ <$> fields .: "control_key"+ <*> fields .: "display_name"+ <*> fields .: "status"+ <*> fields .:? "supports_standby" .!= False++-- | The state of a source control. 'OtherStatus' keeps a value this+-- library does not know.+data SourceControlStatus = Selected | Deselected | Standby | Indeterminate | OtherStatus Text+ deriving stock (Eq, Show)++instance FromJSON SourceControlStatus where+ parseJSON = withText "SourceControlStatus" $ \case+ "selected" -> pure Selected+ "deselected" -> pure Deselected+ "standby" -> pure Standby+ "indeterminate" -> pure Indeterminate+ other -> pure (OtherStatus other)++newtype ZoneList = ZoneList [Zone]++instance FromJSON ZoneList where+ parseJSON = withObject "zones" $ \fields -> ZoneList <$> fields .:? "zones" .!= []++newtype OutputList = OutputList [Output]++instance FromJSON OutputList where+ parseJSON = withObject "outputs" $ \fields -> OutputList <$> fields .:? "outputs" .!= []++-- | The zones, as they are now.+getZones :: (Moo :> es, Error RoonError :> es) => Eff es [Zone]+getZones = (\(ZoneList list) -> list) <$> (request name NoBody >>= expect name "Success")+ where+ name = method "get_zones"++-- | The outputs, as they are now.+getOutputs :: (Moo :> es, Error RoonError :> es) => Eff es [Output]+getOutputs = (\(OutputList list) -> list) <$> (request name NoBody >>= expect name "Success")+ where+ name = method "get_outputs"++-- Following the zones++-- | What a zone subscription reports: every zone first, then changes.+data ZoneEvent+ = ZonesSubscribed [Zone]+ | ZonesChanged ZoneChanges+ deriving stock (Eq, Show)++-- | What changed since the last message of a subscription to the zones.+data ZoneChanges = ZoneChanges+ { removed :: [ZoneId]+ , added :: [Zone]+ , changed :: [Zone]+ -- ^ Complete zones, which replace the previous ones.+ , seekChanged :: [SeekChange]+ -- ^ Sent every second while a zone plays.+ }+ deriving stock (Eq, Show)++instance FromJSON ZoneChanges where+ parseJSON = withObject "ZoneChanges" $ \fields ->+ ZoneChanges+ <$> fields .:? "zones_removed" .!= []+ <*> fields .:? "zones_added" .!= []+ <*> fields .:? "zones_changed" .!= []+ <*> fields .:? "zones_seek_changed" .!= []++-- | The new position of a zone that plays, in seconds, and the time+-- its queue still holds.+data SeekChange = SeekChange+ { zoneId :: ZoneId+ , seekPosition :: Maybe Int+ , queueTimeRemaining :: Maybe Int+ }+ deriving stock (Eq, Show)++instance FromJSON SeekChange where+ parseJSON = withObject "SeekChange" $ \fields ->+ SeekChange <$> fields .: "zone_id" <*> fields .:? "seek_position" <*> fields .:? "queue_time_remaining"++-- | Follow the zones. The stream ends if the server ends the+-- subscription; returning from the consumer ends it.+subscribeZones+ :: (Moo :> es, Error RoonError :> es)+ => (Stream (Eff es) ZoneEvent -> Eff es a)+ -> Eff es a+subscribeZones consume =+ subscribe transportService "zones" [] $+ consume . subscriptionUpdates (method "subscribe_zones") (\(ZoneList list) -> ZonesSubscribed list) ZonesChanged++-- | Bring a view of the zones up to date.+applyZoneEvent :: ZoneEvent -> Map ZoneId Zone -> Map ZoneId Zone+applyZoneEvent = \case+ ZonesSubscribed list -> const (byId list)+ ZonesChanged changes ->+ flip (foldr applySeek) changes.seekChanged+ . union (byId (changes.changed <> changes.added))+ . flip (foldr delete) changes.removed+ where+ byId list = fromList [(zone.zoneId, zone) | zone <- list]+ applySeek change = adjust (seekTo change) change.zoneId+ -- Built with the constructors: the field names are shared with+ -- 'SeekChange', which makes record updates ambiguous.+ seekTo change Zone {..} =+ Zone {nowPlaying = atSeek change.seekPosition <$> nowPlaying, queueTimeRemaining = change.queueTimeRemaining, ..}+ atSeek position (NowPlaying _ len image artists one two three) = NowPlaying position len image artists one two three++-- | The zones as the events describe them, at the end of the stream.+zones :: Monad m => Fold m ZoneEvent (Map ZoneId Zone)+zones = F.foldl' (flip applyZoneEvent) empty++-- | The zones after each event.+zoneViews :: Monad m => Stream m ZoneEvent -> Stream m (Map ZoneId Zone)+zoneViews = postscanl (mkScanl (flip applyZoneEvent) empty)++-- | The zones after each event, except that events which only move the+-- seek position give a view at most once per interval, in seconds. A+-- zone that plays reports its position every second; other changes, such+-- as a new track or a pause, always give a view at once, which includes+-- the positions not reported until then.+zoneViewsEvery :: MonadIO m => Double -> Stream m ZoneEvent -> Stream m (Map ZoneId Zone)+zoneViewsEvery interval =+ mapMaybe (\(_, _, view) -> view) . postscanl (mkScanlM step (pure (empty, Nothing, Nothing)))+ where+ step (current, lastShown, _) event = do+ now <- liftIO getMonotonicTime+ let updated = applyZoneEvent event current+ due = maybe True (\shown -> now - shown >= interval) lastShown+ pure $+ if seekOnly event && not due+ then (updated, lastShown, Nothing)+ else (updated, Just now, Just updated)+ seekOnly = \case+ ZonesChanged ZoneChanges {removed = [], added = [], changed = []} -> True+ _ -> False++-- The queue++-- | An item of the queue of a zone.+data QueueItem = QueueItem+ { queueItemId :: Int+ , length :: Maybe Int+ -- ^ In seconds.+ , imageKey :: Maybe Text+ , oneLine :: DisplayLines+ , twoLine :: DisplayLines+ , threeLine :: DisplayLines+ }+ deriving stock (Eq, Show)++instance FromJSON QueueItem where+ parseJSON = withObject "QueueItem" $ \fields ->+ QueueItem+ <$> fields .: "queue_item_id"+ <*> fields .:? "length"+ <*> fields .:? "image_key"+ <*> fields .: "one_line"+ <*> fields .: "two_line"+ <*> fields .: "three_line"++-- | What a queue subscription reports: the first items, then changes.+data QueueEvent+ = QueueSubscribed [QueueItem]+ | QueueChanged [QueueChange]+ deriving stock (Eq, Show)++-- | One change to the items of a queue, at a position counted from zero.+-- When a track ends, Roon removes the items it reported and inserts the+-- new ones.+data QueueChange+ = QueueRemove {index :: Int, count :: Int}+ | QueueInsert {index :: Int, items :: [QueueItem]}+ | -- | An operation not seen so far, kept as it came.+ OtherQueueChange Value+ deriving stock (Eq, Show)++instance FromJSON QueueChange where+ parseJSON value = flip (withObject "QueueChange") value $ \fields ->+ fields .: "operation" >>= \case+ ("remove" :: Text) -> QueueRemove <$> fields .: "index" <*> fields .: "count"+ "insert" -> QueueInsert <$> fields .: "index" <*> fields .: "items"+ _ -> pure (OtherQueueChange value)++newtype QueueChanges = QueueChanges [QueueChange]++instance FromJSON QueueChanges where+ parseJSON = withObject "QueueChanges" $ \fields -> QueueChanges <$> fields .:? "changes" .!= []++newtype QueueItems = QueueItems [QueueItem]++instance FromJSON QueueItems where+ parseJSON = withObject "queue" $ \fields -> QueueItems <$> fields .:? "items" .!= []++-- | Follow the queue of a zone, up to a number of items.+subscribeQueue+ :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es)+ => target+ -> Int+ -- ^ The most items to report.+ -> (Stream (Eff es) QueueEvent -> Eff es a)+ -> Eff es a+subscribeQueue target maxItems consume =+ subscribe transportService "queue" ["zone_or_output_id" .= zoneOrOutputId target, "max_item_count" .= maxItems] $+ consume . subscriptionUpdates (method "subscribe_queue") (\(QueueItems items) -> QueueSubscribed items) (\(QueueChanges changes) -> QueueChanged changes)++-- | Bring a view of the queue up to date. An 'OtherQueueChange' leaves the+-- items as they are, and the view may then be wrong.+applyQueueEvent :: QueueEvent -> [QueueItem] -> [QueueItem]+applyQueueEvent = \case+ QueueSubscribed items -> const items+ QueueChanged changes -> \items -> foldl (flip applyChange) items changes+ where+ applyChange = \case+ QueueRemove {index, count} -> \items -> take index items <> drop (index + count) items+ QueueInsert {index, items = inserted} -> \items -> take index items <> inserted <> drop index items+ OtherQueueChange _ -> id++-- | The items as the events describe them.+queue :: Monad m => Fold m QueueEvent [QueueItem]+queue = F.foldl' (flip applyQueueEvent) []++-- | An event of one of the subscriptions of 'subscribeTransport'.+data TransportEvent+ = ZoneUpdate ZoneEvent+ | QueueUpdate ZoneId QueueEvent+ deriving stock (Eq, Show)++-- | Follow the zones and the queues of some of them, as one stream. The+-- events of each subscription keep their order; those of different+-- subscriptions are interleaved as they come. Returning from the consumer+-- ends every subscription.+subscribeTransport+ :: (IOE :> es, Moo :> es, Error RoonError :> es)+ => [ZoneId]+ -- ^ The zones whose queue to follow.+ -> Int+ -- ^ The most items to report for each queue.+ -> (Stream (Eff es) TransportEvent -> Eff es a)+ -> Eff es a+subscribeTransport queueZones maxItems consume =+ subscribeZones $ \zoneEvents -> withQueues queueZones [ZoneUpdate <$> zoneEvents]+ where+ withQueues [] streams = consume (parList id streams)+ withQueues (zoneId : rest) streams =+ subscribeQueue zoneId maxItems $ \queueEvents -> withQueues rest ((QueueUpdate zoneId <$> queueEvents) : streams)++-- | Play the queue from one of its items.+playFromHere :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es) => target -> Int -> Eff es ()+playFromHere target queueItemId =+ call (method "play_from_here") $+ object ["zone_or_output_id" .= zoneOrOutputId target, "queue_item_id" .= queueItemId]++-- Controls++-- | What to tell a zone about its playback.+data Control+ = -- | Start playback if paused or stopped.+ Play+ | -- | Pause playback if playing or loading.+ Pause+ | -- | Play if paused or stopped, pause otherwise.+ PlayPause+ | -- | Stop playback and release the audio device.+ Stop+ | -- | Go to the start of the track, or to the previous one.+ Previous+ | Next+ deriving stock (Eq, Show, Enum, Bounded)++controlName :: Control -> Text+controlName = \case+ Play -> "play"+ Pause -> "pause"+ PlayPause -> "playpause"+ Stop -> "stop"+ Previous -> "previous"+ Next -> "next"++-- | Operate a zone. Check the matching @is…Allowed@ field of the zone+-- first.+control :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es) => target -> Control -> Eff es ()+control target which =+ call (method "control") $+ object ["zone_or_output_id" .= zoneOrOutputId target, "control" .= controlName which]++-- | Pause every zone.+pauseAll :: (Moo :> es, Error RoonError :> es) => Eff es ()+pauseAll = call (method "pause_all") (object [])++-- | A seek position, in seconds.+data Seek = SeekTo Int | SeekBy Int+ deriving stock (Eq, Show)++-- | Move within the current track.+seek :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es) => target -> Seek -> Eff es ()+seek target position =+ call (method "seek") . object $+ ("zone_or_output_id" .= zoneOrOutputId target) : case position of+ SeekTo seconds -> ["how" .= ("absolute" :: Text), "seconds" .= seconds]+ SeekBy seconds -> ["how" .= ("relative" :: Text), "seconds" .= seconds]++-- | The settings to change; 'Nothing' leaves one as it is.+data SettingsChange = SettingsChange+ { setShuffle :: Maybe Bool+ , setAutoRadio :: Maybe Bool+ , setLoop :: Maybe LoopChange+ }+ deriving stock (Eq, Show)++-- | Set the loop mode, or go to the next one in Roon's order.+data LoopChange = SetLoop Loop | NextLoop+ deriving stock (Eq, Show)++-- | Change nothing: the value to update with the settings to change.+noSettingsChange :: SettingsChange+noSettingsChange = SettingsChange {setShuffle = Nothing, setAutoRadio = Nothing, setLoop = Nothing}++-- | Change the playback options of a zone.+changeSettings :: (ZoneOrOutput target, Moo :> es, Error RoonError :> es) => target -> SettingsChange -> Eff es ()+changeSettings target change =+ call (method "change_settings") . object $+ ("zone_or_output_id" .= zoneOrOutputId target)+ : catMaybes+ [ ("shuffle" .=) <$> change.setShuffle+ , ("auto_radio" .=) <$> change.setAutoRadio+ , ("loop" .=) . loopName <$> change.setLoop+ ]+ where+ loopName :: LoopChange -> Text+ loopName = \case+ NextLoop -> "next"+ SetLoop LoopQueue -> "loop"+ SetLoop LoopOne -> "loop_one"+ SetLoop LoopDisabled -> "disabled"+ SetLoop (OtherLoop name) -> name++-- | How to change the volume of an output.+data VolumeChange+ = -- | Set the volume, in the units of the output.+ VolumeTo Double+ | -- | Move the volume, in the units of the output.+ VolumeBy Double+ | -- | Move the volume by steps of the output.+ RelativeStep Int+ deriving stock (Eq, Show)++-- | Change the volume of an output. Only for the outputs whose volume+-- Roon controls: the others have no @volume@.+changeVolume :: (Moo :> es, Error RoonError :> es) => OutputId -> VolumeChange -> Eff es ()+changeVolume outputId change =+ call (method "change_volume") . object $+ ("output_id" .= outputId) : case change of+ VolumeTo level -> how "absolute" level+ VolumeBy level -> how "relative" level+ RelativeStep steps -> how "relative_step" steps+ where+ how :: ToJSON a => Text -> a -> [Pair]+ how name level = ["how" .= name, "value" .= level]++-- | Mute ('True') or unmute an output.+mute :: (Moo :> es, Error RoonError :> es) => OutputId -> Bool -> Eff es ()+mute outputId muted = call (method "mute") (object ["output_id" .= outputId, "how" .= muteName muted])++-- | Mute ('True') or unmute every output that can be.+muteAll :: (Moo :> es, Error RoonError :> es) => Bool -> Eff es ()+muteAll muted = call (method "mute_all") (object ["how" .= muteName muted])++muteName :: Bool -> Text+muteName muted = if muted then "mute" else "unmute"++-- | Move the queue of a zone to another zone.+transferZone+ :: (ZoneOrOutput from, ZoneOrOutput to, Moo :> es, Error RoonError :> es)+ => from+ -> to+ -> Eff es ()+transferZone from to =+ call (method "transfer_zone") $+ object ["from_zone_or_output_id" .= zoneOrOutputId from, "to_zone_or_output_id" .= zoneOrOutputId to]++method :: Text -> Text+method name = transportService <> "/" <> name
+ test/Main.hs view
@@ -0,0 +1,26 @@+module Main (main) where++import Roon.BrowseSpec qualified as BrowseSpec+import Roon.ConnectionSpec qualified as ConnectionSpec+import Roon.DiscoverySpec qualified as DiscoverySpec+import Roon.Effect.TokenStoreSpec qualified as TokenStoreSpec+import Roon.Effect.WebSocketSpec qualified as WebSocketSpec+import Roon.ImageSpec qualified as ImageSpec+import Roon.Moo.MessageSpec qualified as MessageSpec+import Roon.TransportSpec qualified as TransportSpec+import Test.Tasty (defaultMain, testGroup)++main :: IO ()+main =+ defaultMain $+ testGroup+ "roon-api"+ [ MessageSpec.tests+ , TokenStoreSpec.tests+ , ConnectionSpec.tests+ , WebSocketSpec.tests+ , TransportSpec.tests+ , BrowseSpec.tests+ , DiscoverySpec.tests+ , ImageSpec.tests+ ]
+ test/Roon/BrowseSpec.hs view
@@ -0,0 +1,243 @@+-- | The browse service, against a scripted server. The load fixtures are+-- answers of a real Roon Server 2.75 to a search, without image keys.+module Roon.BrowseSpec (tests) where++import Control.Monad (replicateM_)+import Data.Aeson (Value (..), decodeStrictText, object, (.=))+import Data.Map.Strict (empty)+import Data.Maybe (fromJust)+import Data.Text (Text)+import Roon.Browse (Candidate (..), Hierarchy (Albums, Search),+ Item (Item, hint, imageKey, inputPrompt, itemKey, subtitle, title),+ ItemHint (ActionList, ListItem), Session (Session),+ TrackAction (AddNext, PlayNow, Queue), defaultSearchOptions,+ performAction, performTrackAction, searchTracks,+ searchTracksConcurrently, session, trackActionTitle)+import Roon.Effect.Moo (defaultRequestHandler, runMoo)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (JsonBody, NoBody), MooMessage (body, name),+ Verb (Complete))+import Roon.Test.Server (Wire, answer, expectRequest, field, receiveFromClient,+ withServer)+import Roon.Transport (ZoneId (..))+import Test.Tasty (TestTree, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++tests :: TestTree+tests =+ localOption (mkTimeout 5_000_000) $+ testGroup+ "Roon.Browse"+ [ testCase "searches for tracks in a session" $ do+ let searchSession = Session Search (Just "s")+ client = runMoo defaultRequestHandler (searchTracks defaultSearchOptions searchSession "The Example Band Second Song")+ (outcome, ()) <- withServer empty client $ \wire -> do+ search <- expectRequest wire "com.roonlabs.browse:1/browse"+ search.body+ @?= JsonBody+ ( object+ [ "hierarchy" .= ("search" :: Text)+ , "multi_session_key" .= ("s" :: Text)+ , "pop_all" .= True+ , "input" .= ("The Example Band Second Song" :: Text)+ ]+ )+ answer wire search Complete "Success" listAction+ top <- expectRequest wire "com.roonlabs.browse:1/load"+ field "multi_session_key" top @?= Just (String "s")+ answer wire top Complete "Success" (JsonBody searchLevel)+ open <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" open @?= Just (String "1:1")+ answer wire open Complete "Success" listAction+ tracks <- expectRequest wire "com.roonlabs.browse:1/load"+ field "count" tracks @?= Just (Number 10)+ answer wire tracks Complete "Success" (JsonBody tracksLevel)+ fmap (map (\candidate -> (candidate.item.title, candidate.item.itemKey, candidate.session)) . fst) outcome+ @?= Right [("Second Song", Just "2:0", searchSession)]+ , testCase "finds no track without a category of tracks" $ do+ let client = runMoo defaultRequestHandler (searchTracks defaultSearchOptions (session Search) "nothing")+ (outcome, ()) <- withServer empty client $ \wire -> do+ search <- expectRequest wire "com.roonlabs.browse:1/browse"+ answer wire search Complete "Success" listAction+ top <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire top Complete "Success" . JsonBody $+ object ["list" .= object ["title" .= ("Search" :: Text), "count" .= (0 :: Int), "level" .= (0 :: Int)], "offset" .= (0 :: Int), "items" .= ([] :: [Value])]+ fmap fst outcome @?= Right []+ , testCase "opens a track down to its actions and queues it" $ do+ let client = runMoo defaultRequestHandler (performTrackAction livingRoom (trackActionTitle Queue) secondSong)+ (outcome, ()) <- withServer empty client $ \wire -> do+ openTrack <- expectRequest wire "com.roonlabs.browse:1/browse"+ (field "item_key" openTrack, field "zone_or_output_id" openTrack) @?= (Just (String "2:0"), Just (String "zone-1"))+ answer wire openTrack Complete "Success" listAction+ trackLevel' <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire trackLevel' Complete "Success" (JsonBody trackLevel)+ openActions <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" openActions @?= Just (String "3:0")+ answer wire openActions Complete "Success" listAction+ actions <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire actions Complete "Success" (JsonBody actionLevel)+ queue <- expectRequest wire "com.roonlabs.browse:1/browse"+ (field "item_key" queue, field "zone_or_output_id" queue) @?= (Just (String "4:2"), Just (String "zone-1"))+ -- What Roon Server 2.75 answered: it goes back to the level of+ -- the track.+ answer wire queue Complete "Success" (JsonBody queuedReply)+ fmap fst outcome @?= Right ()+ , testCase "plays an album through the item that plays the whole of it" $ do+ let album = Candidate {session = Session Albums (Just "s"), item = Item {title = "An Album", subtitle = Nothing, imageKey = Nothing, itemKey = Just "1:5", hint = Just ListItem, inputPrompt = Nothing}}+ client = runMoo defaultRequestHandler (performAction livingRoom (trackActionTitle AddNext) album)+ (outcome, ()) <- withServer empty client $ \wire -> do+ openAlbum <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" openAlbum @?= Just (String "1:5")+ answer wire openAlbum Complete "Success" listAction+ tracks <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire tracks Complete "Success" (JsonBody albumLevel)+ openPlay <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" openPlay @?= Just (String "2:0")+ answer wire openPlay Complete "Success" listAction+ actions <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire actions Complete "Success" (JsonBody actionLevel)+ addNext <- expectRequest wire "com.roonlabs.browse:1/browse"+ (field "item_key" addNext, field "zone_or_output_id" addNext) @?= (Just (String "4:1"), Just (String "zone-1"))+ answer wire addNext Complete "Success" (JsonBody queuedReply)+ fmap fst outcome @?= Right ()+ , testCase "plays an album found by a search, which first opens on itself" $ do+ let album = Candidate {session = Session Search (Just "s"), item = Item {title = "An Album", subtitle = Nothing, imageKey = Nothing, itemKey = Just "1:0", hint = Just ListItem, inputPrompt = Nothing}}+ client = runMoo defaultRequestHandler (performAction livingRoom (trackActionTitle Queue) album)+ (outcome, ()) <- withServer empty client $ \wire -> do+ openHit <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" openHit @?= Just (String "1:0")+ answer wire openHit Complete "Success" listAction+ itself <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire itself Complete "Success" (JsonBody albumItselfLevel)+ openAlbum <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" openAlbum @?= Just (String "5:0")+ answer wire openAlbum Complete "Success" listAction+ tracks <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire tracks Complete "Success" (JsonBody albumLevel)+ openPlay <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" openPlay @?= Just (String "2:0")+ answer wire openPlay Complete "Success" listAction+ actions <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire actions Complete "Success" (JsonBody actionLevel)+ queue <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" queue @?= Just (String "4:2")+ answer wire queue Complete "Success" (JsonBody queuedReply)+ fmap fst outcome @?= Right ()+ , testCase "does not guess among several items that are not the whole" $ do+ let album = Candidate {session = Session Albums (Just "s"), item = Item {title = "Tracks", subtitle = Nothing, imageKey = Nothing, itemKey = Just "1:5", hint = Just ListItem, inputPrompt = Nothing}}+ client = runMoo defaultRequestHandler (performAction livingRoom (trackActionTitle Queue) album)+ (outcome, ()) <- withServer empty client $ \wire -> do+ open <- expectRequest wire "com.roonlabs.browse:1/browse"+ answer wire open Complete "Success" listAction+ level <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire level Complete "Success" (JsonBody twoTracksLevel)+ fmap fst outcome @?= Left (BrowseItemMissing "Queue for Tracks")+ , testCase "reports an error message from Roon" $ do+ let client = runMoo defaultRequestHandler (performTrackAction livingRoom (trackActionTitle PlayNow) secondSong)+ (outcome, ()) <- withServer empty client $ \wire -> do+ serveActions wire+ play <- expectRequest wire "com.roonlabs.browse:1/browse"+ field "item_key" play @?= Just (String "4:0")+ answer wire play Complete "Success" . JsonBody $+ object ["action" .= ("message" :: Text), "message" .= ("Zone is not available" :: Text), "is_error" .= True]+ fmap fst outcome @?= Left (BrowseFailed "Zone is not available")+ , testCase "reports an action that is not offered" $ do+ let client = runMoo defaultRequestHandler (performTrackAction livingRoom "Shuffle" secondSong)+ (outcome, ()) <- withServer empty client serveActions+ fmap fst outcome @?= Left (BrowseItemMissing "Shuffle for Second Song")+ , testCase "searches concurrently and reports each query" $ do+ let client = runMoo defaultRequestHandler (searchTracksConcurrently defaultSearchOptions "q-" ["Second Song", "broken"])+ (outcome, ()) <- withServer empty client $ \wire ->+ -- Four requests for the first search, one for the second, in+ -- any order: answer by session.+ replicateM_ 5 $ do+ message <- receiveFromClient wire+ case (field "multi_session_key" message, message.name, field "item_key" message) of+ (Just (String "q-1"), _, _) -> answer wire message Complete "InvalidRequest" NoBody+ (_, "com.roonlabs.browse:1/browse", _) -> answer wire message Complete "Success" listAction+ (_, _, _) -> do+ -- The first load reads the search, the second the tracks.+ let level = if field "count" message == Just (Number 100) then searchLevel else tracksLevel+ answer wire message Complete "Success" (JsonBody level)+ fmap (map (fmap (fmap (map (.item.title)))) . fst) outcome+ @?= Right [("Second Song", Right ["Second Song"]), ("broken", Left (UnexpectedReply "com.roonlabs.browse:1/browse" "InvalidRequest"))]+ ]++livingRoom :: ZoneId+livingRoom = ZoneId "zone-1"++secondSong :: Candidate+secondSong =+ Candidate+ { session = Session Search (Just "s")+ , item = Item {title = "Second Song", subtitle = Nothing, imageKey = Nothing, itemKey = Just "2:0", hint = Just ActionList, inputPrompt = Nothing}+ }++-- | Answer the four requests that lead from 'secondSong' to its actions.+serveActions :: Wire -> IO ()+serveActions wire = do+ openTrack <- expectRequest wire "com.roonlabs.browse:1/browse"+ answer wire openTrack Complete "Success" listAction+ trackLevel' <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire trackLevel' Complete "Success" (JsonBody trackLevel)+ openActions <- expectRequest wire "com.roonlabs.browse:1/browse"+ answer wire openActions Complete "Success" listAction+ actions <- expectRequest wire "com.roonlabs.browse:1/load"+ answer wire actions Complete "Success" (JsonBody actionLevel)++-- | What browse answers when it moves to a list; its content does not+-- matter to the client.+listAction :: Body+listAction =+ JsonBody . object $+ ["action" .= ("list" :: Text), "list" .= object ["title" .= ("Search" :: Text), "count" .= (2 :: Int), "level" .= (0 :: Int)]]++-- Real answers++searchLevel :: Value+searchLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"action_list\",\"item_key\":\"1:0\",\"subtitle\":\"The Example Band, Ann Writer, Bob Writer\",\"title\":\"Second Song\"},\+ \{\"hint\":\"list\",\"item_key\":\"1:1\",\"subtitle\":\"1 Result\",\"title\":\"Tracks\"}],\+ \\"list\":{\"count\":2,\"display_offset\":null,\"level\":0,\"subtitle\":\"The Example Band Second Song\",\"title\":\"Search\"},\"offset\":0}"++tracksLevel :: Value+tracksLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"action_list\",\"item_key\":\"2:0\",\"subtitle\":\"The Example Band, Ann Writer, Bob Writer\",\"title\":\"Second Song\"}],\+ \\"list\":{\"count\":1,\"display_offset\":null,\"level\":1,\"subtitle\":\"1 Result\",\"title\":\"Tracks\"},\"offset\":0}"++trackLevel :: Value+trackLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"action_list\",\"item_key\":\"3:0\",\"subtitle\":\"The Example Band, Ann Writer, Bob Writer\",\"title\":\"Second Song\"}],\+ \\"list\":{\"count\":1,\"display_offset\":null,\"level\":2,\"subtitle\":\"The Example Band, Ann Writer, Bob Writer\",\"title\":\"Second Song\"},\"offset\":0}"++-- | An album, as Roon Server 2.75 lists it (titles changed).+albumLevel :: Value+albumLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"action_list\",\"item_key\":\"2:0\",\"subtitle\":null,\"title\":\"Play Album\"},\+ \{\"hint\":\"action_list\",\"item_key\":\"2:1\",\"subtitle\":\"The Example Band\",\"title\":\"1. First Song\"},\+ \{\"hint\":\"action_list\",\"item_key\":\"2:2\",\"subtitle\":\"The Example Band\",\"title\":\"2. Second Song\"}],\+ \\"list\":{\"count\":3,\"display_offset\":null,\"level\":1,\"subtitle\":\"The Example Band\",\"title\":\"An Album\"},\"offset\":0}"++-- | What an album found by a search opens on with Roon Server 2.75: a+-- level that holds only itself (titles changed).+albumItselfLevel :: Value+albumItselfLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"list\",\"item_key\":\"5:0\",\"subtitle\":\"The Example Band\",\"title\":\"An Album\"}],\+ \\"list\":{\"count\":1,\"display_offset\":null,\"level\":1,\"subtitle\":\"The Example Band\",\"title\":\"An Album\"},\"offset\":0}"++twoTracksLevel :: Value+twoTracksLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"action_list\",\"item_key\":\"2:1\",\"subtitle\":\"The Example Band\",\"title\":\"First Song\"},\+ \{\"hint\":\"action_list\",\"item_key\":\"2:2\",\"subtitle\":\"The Example Band\",\"title\":\"Second Song\"}],\+ \\"list\":{\"count\":2,\"display_offset\":null,\"level\":1,\"subtitle\":\"2 Results\",\"title\":\"Tracks\"},\"offset\":0}"++actionLevel :: Value+actionLevel = fromJust . decodeStrictText $+ "{\"items\":[{\"hint\":\"action\",\"item_key\":\"4:0\",\"subtitle\":null,\"title\":\"Play Now\"},{\"hint\":\"action\",\"item_key\":\"4:1\",\"subtitle\":null,\"title\":\"Add Next\"},\+ \{\"hint\":\"action\",\"item_key\":\"4:2\",\"subtitle\":null,\"title\":\"Queue\"},{\"hint\":\"action\",\"item_key\":\"4:3\",\"subtitle\":null,\"title\":\"Start Radio\"}],\+ \\"list\":{\"count\":4,\"display_offset\":null,\"hint\":\"action_list\",\"level\":3,\"subtitle\":\"The Example Band, Ann Writer, Bob Writer\",\"title\":\"Second Song\"},\"offset\":0}"++queuedReply :: Value+queuedReply = fromJust . decodeStrictText $+ "{\"action\":\"list\",\"list\":{\"count\":1,\"display_offset\":null,\"image_key\":\"album-image-0001\",\"level\":2,\+ \\"subtitle\":\"The Example Band, Ann Writer, Bob Writer\",\"title\":\"Second Song\"}}"
+ test/Roon/ConnectionSpec.hs view
@@ -0,0 +1,214 @@+-- | The connection logic, exercised against a scripted server over an+-- in-memory transport.+module Roon.ConnectionSpec (tests) where++import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)+import Control.Concurrent.STM (atomically, writeTQueue)+import Data.Aeson (Value (..), object, (.=))+import Data.IORef (atomicModifyIORef', modifyIORef', newIORef, readIORef)+import Data.Map.Strict (empty, singleton)+import Data.Text (Text)+import Effectful (Eff, IOE, liftIO, runEff)+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Error.Static (Error, runErrorNoCallStack, throwError)+import Roon.Connection (Reconnect (..), reconnecting, runRoon, runRoonWithin)+import Roon.Effect.Moo (Reply (name), defaultRequestHandler, nextReply,+ openExchange, request, requestWithin, runMoo,+ withSubscription)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (JsonBody, NoBody),+ MooMessage (name, requestId, verb),+ RequestId (RequestId), Verb (Complete, Continue))+import Roon.Registry (Registration (Registration, core, grantedServices, token),+ info, registerWithin)+import Roon.Test.Server (Wire (toClient), answer, closeConnection, coreBody,+ expectRequest, extension, field, receiveFromClient,+ registered, sendToClient, serveInfo, serverRequest,+ testCore, withServer)+import Streamly.Data.Fold (toList)+import Streamly.Data.Stream (fold)+import Test.Tasty (TestTree, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ localOption (mkTimeout 5_000_000) $+ testGroup+ "Roon.Connection"+ [ testCase "registers, answers a ping and stores the token" $ do+ (outcome, ()) <- withServer empty (runRoon extension pure) $ \wire -> do+ registerRequest <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ field "extension_id" registerRequest @?= Just (String "test.extension")+ field "token" registerRequest @?= Nothing+ field "provided_services" registerRequest @?= Just (toJSONList ["com.roonlabs.ping:1"])+ -- The server pings while the registration is pending.+ sendToClient wire (serverRequest "41" "com.roonlabs.ping:1/ping")+ pong <- receiveFromClient wire+ (pong.verb, pong.name, pong.requestId) @?= (Complete, "Success", RequestId "41")+ answer wire registerRequest Continue "Registered" (registered "tok-1")+ outcome+ @?= Right+ ( Registration+ { core = testCore+ , token = "tok-1"+ , grantedServices = ["com.roonlabs.transport:2"]+ }+ , singleton "core-1" "tok-1"+ )+ , testCase "presents the stored token and replaces it" $ do+ (outcome, ()) <- withServer (singleton "core-1" "old") (runRoon extension pure) $ \wire -> do+ registerRequest <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ field "token" registerRequest @?= Just (String "old")+ answer wire registerRequest Continue "Registered" (registered "new")+ fmap snd outcome @?= Right (singleton "core-1" "new")+ , testCase "gives up when the extension is not enabled in time" $ do+ (outcome, ()) <- withServer empty (runRoonWithin (Just 50_000) extension pure) $ \wire -> do+ _ <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ pure ()+ fmap fst outcome @?= Left (TimedOut "com.roonlabs.registry:1/register")+ , testCase "rejects a request for a service it does not provide" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler info) $ \wire -> do+ infoRequest <- expectRequest wire "com.roonlabs.registry:1/info"+ sendToClient wire (serverRequest "7" "com.example.unknown:1/anything")+ rejection <- receiveFromClient wire+ (rejection.verb, rejection.name, rejection.requestId) @?= (Complete, "InvalidRequest", RequestId "7")+ answer wire infoRequest Complete "Success" coreBody+ fmap fst outcome @?= Right testCore+ , testGroup+ "reconnecting"+ [ testCase "tries again until the action succeeds" $ do+ (attempts, outcome) <- runAttempts (Just 5) [failWith ConnectionLost, failWith (ConnectFailed "refused"), const (pure "done")]+ (attempts, outcome) @?= (3, Right "done")+ , testCase "gives up after the last attempt" $ do+ (attempts, outcome) <- runAttempts (Just 3) (repeat (failWith (ConnectFailed "refused")))+ (attempts, outcome) @?= (3, Left (ConnectFailed "refused"))+ , testCase "does not try again after another failure" $ do+ (attempts, outcome) <- runAttempts (Just 5) (repeat (failWith (TimedOut "svc:1/slow")))+ (attempts, outcome) @?= (1, Left (TimedOut "svc:1/slow"))+ , testCase "counts again once an attempt has connected" $ do+ let connectThenFail markConnected = markConnected >> throwError ConnectionLost+ -- The second attempt connects: its loss starts a new series,+ -- which the third attempt ends. Without the reset, the+ -- second attempt would be the last.+ (attempts, outcome) <- runAttempts (Just 2) (failWith ConnectionLost : connectThenFail : repeat (failWith ConnectionLost))+ (attempts, outcome) @?= (3, Left ConnectionLost)+ ]+ , testCase "routes replies while the server's request is being answered" $ do+ (gate, answered) <- (,) <$> newEmptyMVar <*> newEmptyMVar+ -- The answer to the server waits until the client has its reply.+ let handler service method body = case (service, method) of+ ("svc:1", "slow") -> liftIO (takeMVar gate) >> pure ("Success", NoBody)+ _ -> defaultRequestHandler service method body+ client = runMoo handler $ do+ reply <- request "svc:1/question" NoBody+ liftIO (putMVar gate ())+ -- Stay connected until the server has the answer.+ liftIO (takeMVar answered)+ pure reply.name+ (outcome, ()) <- withServer empty client $ \wire -> do+ question <- expectRequest wire "svc:1/question"+ sendToClient wire (serverRequest "9" "svc:1/slow")+ answer wire question Complete "Answer" NoBody+ slow <- receiveFromClient wire+ (slow.verb, slow.name, slow.requestId) @?= (Complete, "Success", RequestId "9")+ putMVar answered ()+ fmap fst outcome @?= Right "Answer"+ , testCase "routes replies to the exchange they answer" $ do+ let client = runMoo defaultRequestHandler $ do+ first <- openExchange "svc:1/first" NoBody+ second <- openExchange "svc:1/second" NoBody+ (,) <$> nextReply first <*> nextReply second+ (outcome, ()) <- withServer empty client $ \wire -> do+ first <- expectRequest wire "svc:1/first"+ second <- expectRequest wire "svc:1/second"+ answer wire second Complete "Second" NoBody+ answer wire first Complete "First" NoBody+ fmap (both (fmap (.name)) . fst) outcome @?= Right (Just "First", Just "Second")+ , testCase "streams the replies of a subscription until the final one" $ do+ let client =+ runMoo defaultRequestHandler $+ withSubscription "svc:1/subscribe_things" NoBody (fold toList . fmap (.name))+ (outcome, ()) <- withServer empty client $ \wire -> do+ subscription <- expectRequest wire "svc:1/subscribe_things"+ answer wire subscription Continue "Subscribed" NoBody+ answer wire subscription Continue "Changed" NoBody+ answer wire subscription Complete "Unsubscribed" NoBody+ fmap fst outcome @?= Right ["Subscribed", "Changed", "Unsubscribed"]+ , testCase "fails pending requests when the connection closes" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler info) $ \wire -> do+ _ <- expectRequest wire "com.roonlabs.registry:1/info"+ closeConnection wire+ fmap fst outcome @?= Left ConnectionLost+ , testCase "refuses new requests once the connection is closed" $ do+ -- Both failures reach the handler of the caller, not the one+ -- around runMoo.+ let client = runMoo defaultRequestHandler $ do+ first <- runErrorNoCallStack @RoonError info+ second <- runErrorNoCallStack @RoonError info+ pure (first, second)+ (outcome, ()) <- withServer empty client $ \wire -> do+ _ <- expectRequest wire "com.roonlabs.registry:1/info"+ closeConnection wire+ fmap fst outcome @?= Right (Left ConnectionLost, Left ConnectionLost)+ , testCase "reports a frame that is not a MOO message" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler info) $ \wire -> do+ _ <- expectRequest wire "com.roonlabs.registry:1/info"+ atomically (writeTQueue wire.toClient (Just "HTTP/1.1 400 Bad Request\n\n"))+ case fmap fst outcome of+ Left (ProtocolViolation _) -> pure ()+ other -> assertFailure ("unexpected outcome: " <> show other)+ , testCase "gives up on a request that gets no reply in time" $ do+ let client = runMoo defaultRequestHandler $ do+ late <- runErrorNoCallStack @RoonError (requestWithin (Just 50_000) "svc:1/slow" NoBody)+ next <- request "svc:1/fast" NoBody+ pure (late, next.name)+ (outcome, ()) <- withServer empty client $ \wire -> do+ slow <- expectRequest wire "svc:1/slow"+ fast <- expectRequest wire "svc:1/fast"+ -- Too late: the client has stopped waiting, and drops it.+ answer wire slow Complete "Late" NoBody+ answer wire fast Complete "Fast" NoBody+ fmap fst outcome @?= Right (Left (TimedOut "svc:1/slow"), "Fast")+ , testCase "gives up on a registration that is not enabled in time" $ do+ let client = runMoo defaultRequestHandler (registerWithin 50_000 extension Nothing)+ (outcome, ()) <- withServer empty client $ \wire -> do+ _ <- expectRequest wire "com.roonlabs.registry:1/register"+ pure ()+ fmap fst outcome @?= Left (TimedOut "com.roonlabs.registry:1/register")+ , testCase "reports an unexpected status" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler info) $ \wire -> do+ infoRequest <- expectRequest wire "com.roonlabs.registry:1/info"+ answer wire infoRequest Complete "NotAvailable" NoBody+ fmap fst outcome @?= Left (UnexpectedReply "com.roonlabs.registry:1/info" "NotAvailable")+ , testCase "reports an unexpected body" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler info) $ \wire -> do+ infoRequest <- expectRequest wire "com.roonlabs.registry:1/info"+ answer wire infoRequest Complete "Success" (JsonBody (object ["core_id" .= ("core-1" :: Text)]))+ case fmap fst outcome of+ Left (UnexpectedReplyBody "com.roonlabs.registry:1/info" _) -> pure ()+ other -> assertFailure ("unexpected outcome: " <> show other)+ ]+ where+ both f (a, b) = (f a, f b)+ toJSONList = Array . foldMap (pure . String)++-- | Run 'reconnecting' over a list of attempts, with short delays. Returns+-- how many attempts ran, and the outcome.+runAttempts+ :: Maybe Int+ -> [Eff '[Error RoonError, Concurrent, IOE] () -> Eff '[Error RoonError, Concurrent, IOE] Text]+ -> IO (Int, Either RoonError Text)+runAttempts maxAttempts attempts = do+ remaining <- newIORef attempts+ count <- newIORef (0 :: Int)+ let next markConnected = do+ liftIO (modifyIORef' count (+ 1))+ liftIO (atomicModifyIORef' remaining (\list -> (drop 1 list, take 1 list))) >>= \case+ [current] -> current markConnected+ _ -> error "runAttempts: no attempt left"+ policy = Reconnect {firstDelay = 1_000, maxDelay = 4_000, maxAttempts}+ outcome <- runEff . runConcurrent . runErrorNoCallStack $ reconnecting policy next+ (,outcome) <$> readIORef count++failWith :: RoonError -> Eff '[Error RoonError, Concurrent, IOE] () -> Eff '[Error RoonError, Concurrent, IOE] Text+failWith failure _ = throwError failure
+ test/Roon/DiscoverySpec.hs view
@@ -0,0 +1,106 @@+-- | SOOD: the format, and a discovery against a fake server on loopback.+module Roon.DiscoverySpec (tests) where++import Control.Concurrent.Async (withAsync)+import Control.Exception (bracket)+import Control.Monad (void)+import Data.ByteString qualified as BS (length, take)+import Effectful (runEff)+import Network.Socket (Family (AF_INET), HostAddress, PortNumber,+ SockAddr (SockAddrInet), SocketType (Datagram), bind,+ close, defaultProtocol, socketPort, tupleToHostAddress)+import Network.Socket qualified as N (socket)+import Network.Socket.ByteString (recvFrom, sendTo)+import Roon.Discovery (Core (address, name, uniqueId),+ DiscoveryOptions (DiscoveryOptions, targets, wait),+ SoodMessage (SoodMessage, kind, properties),+ coreFromAnswer, decodeSood, discover, encodeSood,+ roonServiceId)+import Roon.Effect.WebSocket (ServerAddress (..))+import Test.Tasty (TestTree, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++tests :: TestTree+tests =+ localOption (mkTimeout 10_000_000) $+ testGroup+ "Roon.Discovery"+ [ testCase "encodes a query" $+ encodeSood SoodMessage {kind = 'Q', properties = [("a", Just "bc"), ("d", Nothing)]}+ @?= "SOOD\2Q\1a\0\2bc\1d\255\255"+ , testCase "decodes what it encodes" $ do+ let message = SoodMessage {kind = 'R', properties = [("name", Just "Test Core"), ("empty", Just ""), ("none", Nothing)]}+ decodeSood (encodeSood message) @?= Just message+ , testCase "rejects what is not SOOD version 2" $ do+ decodeSood "SOOP\2Q" @?= Nothing+ decodeSood "SOOD\1Q" @?= Nothing+ , testCase "rejects a datagram cut inside a property" $ do+ let name = ("name", Just "Test Core")+ first = SoodMessage {kind = 'R', properties = [name]}+ full = encodeSood SoodMessage {kind = 'R', properties = [name, ("port", Just "9330")]}+ boundary = BS.length (encodeSood first)+ -- Every prefix that ends inside a property is refused; the one that+ -- ends between the two properties is the first one alone.+ [decodeSood (BS.take n full) | n <- [7 .. BS.length full - 1], n /= boundary]+ @?= replicate (BS.length full - 8) Nothing+ decodeSood (BS.take boundary full) @?= Just first+ , testCase "reads a server from an answer" $+ fmap (\core -> (core.uniqueId, core.name, core.address)) (coreFromAnswer "192.0.2.7" (answer []))+ @?= Just ("core-1", Just "Test Core", ServerAddress {host = "192.0.2.7", port = 9330})+ , testCase "uses the reply address of the answer" $+ fmap (.address) (coreFromAnswer "192.0.2.7" (answer [("_replyaddr", Just "192.0.2.8")]))+ @?= Just ServerAddress {host = "192.0.2.8", port = 9330}+ , testCase "ignores answers for other services" $+ coreFromAnswer "192.0.2.7" SoodMessage {kind = 'R', properties = [("service_id", Just "other"), ("unique_id", Just "x"), ("http_port", Just "1")]}+ @?= Nothing+ , testCase "finds a server that answers, once" $+ withFakeServer $ \port -> do+ cores <- runEff (discover DiscoveryOptions {targets = [(loopback, port)], wait = 300_000})+ map (\core -> (core.uniqueId, core.address)) cores @?= [("core-1", ServerAddress {host = "127.0.0.1", port = 9330})]+ , testCase "finds it again: each query has a transaction id of its own" $+ withFakeServer $ \port -> do+ let options = DiscoveryOptions {targets = [(loopback, port)], wait = 300_000}+ first <- runEff (discover options)+ second <- runEff (discover options)+ (length first, length second) @?= (1, 1)+ ]+ where+ answer extra =+ SoodMessage+ { kind = 'R'+ , properties =+ [ ("name", Just "Test Core")+ , ("unique_id", Just "core-1")+ , ("service_id", Just roonServiceId)+ , ("http_port", Just "9330")+ ]+ <> extra+ }++loopback :: HostAddress+loopback = tupleToHostAddress (127, 0, 0, 1)++-- | A server on a free loopback port that answers every query three+-- times, as Roon answers several times, and, like Roon, ignores a query+-- with the transaction id of the previous one, or without any.+withFakeServer :: (PortNumber -> IO a) -> IO a+withFakeServer run =+ bracket (N.socket AF_INET Datagram defaultProtocol) close $ \socket -> do+ bind socket (SockAddrInet 0 loopback)+ port <- socketPort socket+ let reply =+ encodeSood+ SoodMessage+ { kind = 'R'+ , properties = [("unique_id", Just "core-1"), ("service_id", Just roonServiceId), ("http_port", Just "9330")]+ }+ serve previous = do+ (query, sender) <- recvFrom socket 65535+ case decodeSood query of+ Just SoodMessage {kind = 'Q', properties}+ | Just (Just transaction) <- lookup "_tid" properties+ , Just transaction /= previous -> do+ mapM_ (const (void (sendTo socket reply sender))) [1 .. 3 :: Int]+ serve (Just transaction)+ _ -> serve previous+ withAsync (serve Nothing) (const (run port))
+ test/Roon/Effect/TokenStoreSpec.hs view
@@ -0,0 +1,51 @@+module Roon.Effect.TokenStoreSpec (tests) where++import Data.Bits ((.&.))+import Data.Map.Strict (fromList, singleton)+import Effectful (runEff, runPureEff)+import Effectful.FileSystem (runFileSystem)+import Roon.Effect.TokenStore (loadToken, runTokenStoreFile, runTokenStorePure,+ saveToken)+import System.Directory (listDirectory)+import System.FilePath ((</>))+import System.IO.Temp (withSystemTempDirectory)+import System.Posix.Files (fileMode, getFileStatus)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++tests :: TestTree+tests =+ testGroup+ "Roon.Effect.TokenStore"+ [ testCase "the pure store returns what was saved" $ do+ let (loaded, final) = runPureEff . runTokenStorePure (singleton "a" "1") $ do+ saveToken "b" "2"+ (,,) <$> loadToken "a" <*> loadToken "b" <*> loadToken "c"+ loaded @?= (Just "1", Just "2", Nothing)+ final @?= fromList [("a", "1"), ("b", "2")]+ , testCase "the file store has no token before the file exists" $+ withSystemTempDirectory "roon-api-test" $ \directory -> do+ loaded <- runEff . runFileSystem . runTokenStoreFile (directory </> "missing" </> "tokens.json") $ loadToken "a"+ loaded @?= Nothing+ , testCase "the file store keeps tokens across runs, one per core" $+ withSystemTempDirectory "roon-api-test" $ \directory -> do+ let path = directory </> "nested" </> "tokens.json"+ runEff . runFileSystem . runTokenStoreFile path $ saveToken "a" "1" >> saveToken "b" "2" >> saveToken "a" "3"+ loaded <- runEff . runFileSystem . runTokenStoreFile path $ (,,) <$> loadToken "a" <*> loadToken "b" <*> loadToken "c"+ loaded @?= (Just "3", Just "2", Nothing)+ , testCase "the file is private and no temporary file is left behind" $+ withSystemTempDirectory "roon-api-test" $ \directory -> do+ let path = directory </> "tokens.json"+ runEff . runFileSystem . runTokenStoreFile path $ saveToken "a" "1" >> saveToken "a" "2"+ status <- getFileStatus path+ fileMode status .&. 0o077 @?= 0+ listDirectory directory >>= (@?= ["tokens.json"])+ , testCase "an unreadable file counts as empty and is replaced" $+ withSystemTempDirectory "roon-api-test" $ \directory -> do+ let path = directory </> "tokens.json"+ writeFile path "not json"+ loaded <- runEff . runFileSystem . runTokenStoreFile path $ loadToken "a" <* saveToken "a" "1"+ loaded @?= Nothing+ reloaded <- runEff . runFileSystem . runTokenStoreFile path $ loadToken "a"+ reloaded @?= Just "1"+ ]
+ test/Roon/Effect/WebSocketSpec.hs view
@@ -0,0 +1,165 @@+-- | The real WebSocket transport, against a scripted server listening on+-- the loopback interface.+module Roon.Effect.WebSocketSpec (tests) where++import Control.Concurrent.Async (race_, wait, withAsync)+import Control.Concurrent.STM (atomically, readTQueue, writeTQueue)+import Control.Exception (bracket)+import Data.Aeson (Value (..), object, (.=))+import Data.IORef (atomicModifyIORef', modifyIORef', newIORef, readIORef)+import Data.Map.Strict (Map, empty, singleton)+import Data.Text (Text, isPrefixOf, isSuffixOf)+import Data.Text.Encoding (encodeUtf8)+import Effectful (Eff, IOE, MonadIO (liftIO), runEff)+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Error.Static (Error, runErrorNoCallStack)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet),+ SocketType (Stream), bind, defaultProtocol, socketPort,+ tupleToHostAddress)+import Network.Socket qualified as N (close, socket)+import Roon.Connection (Reconnect (..), withRoon, withRoonReconnecting)+import Roon.Effect.Moo (Reply (..), request)+import Roon.Effect.TokenStore (TokenStore, runTokenStorePure)+import Roon.Effect.WebSocket (ServerAddress (..), describeFrame, frames,+ runWebSocketWith, sendFrame, traceFrames)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (JsonBody, NoBody, RawBody),+ MooMessage (MooMessage, body, headers, name, requestId, verb),+ RequestId (RequestId),+ Verb (Complete, Continue, Request), encode)+import Roon.Registry (Registration (token))+import Roon.Test.Server (Wire (toClient, toServer), answer, closeConnection,+ expectRequest, extension, field, newWire,+ receiveFromClient, registered, sendToClient, serveInfo,+ serverRequest)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold, toList)+import Streamly.External.Network.WebSocket.Server (Connection,+ Message (BinaryMessage, TextMessage),+ defaultServerOptions, listen,+ messages, send, serveSocket)+import Streamly.External.Network.WebSocket.Server qualified as WSS (close)+import Test.Tasty (TestTree, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ localOption (mkTimeout 10_000_000) $+ testGroup+ "Roon.Effect.WebSocket"+ [ testGroup+ "tracing"+ [ testCase "describes each kind of frame" $ do+ let frame verb name requestId body = encode MooMessage {verb, name, requestId = RequestId requestId, headers = empty, body}+ describeFrame 20 "" @?= "empty frame"+ describeFrame 40 (frame Request "svc:1/get" "3" (JsonBody (object ["a" .= (1 :: Int)])))+ @?= "REQUEST svc:1/get [3] {\"a\":1}"+ describeFrame 10 (frame Complete "Success" "3" (JsonBody (object ["long" .= ("abcdefghij" :: Text)])))+ @?= "COMPLETE Success [3] {\"long\":\"a... (21 characters)"+ describeFrame 20 (frame Continue "Changed" "4" NoBody) @?= "CONTINUE Changed [4]"+ describeFrame 20 (frame Complete "Success" "5" (RawBody "image/jpeg" "\255\216\255"))+ @?= "COMPLETE Success [5] image/jpeg, 3 bytes"+ let unreadable = describeFrame 80 "HTTP/1.1 400 Bad Request\n\n"+ assertBool (show unreadable) $+ "not a MOO message (" `isPrefixOf` unreadable && "): HTTP/1.1 400 Bad Request\\n\\n" `isSuffixOf` unreadable+ , testCase "reports the frames of a connection" $ do+ lines' <- newIORef []+ let reply = encode MooMessage {verb = Complete, name = "Success", requestId = RequestId "0", headers = empty, body = NoBody}+ inbox <- newIORef [Just reply, Nothing]+ _ <- runEff . runWebSocketWith (\_ -> pure True) (liftIO (atomicModifyIORef' inbox (\case (x : rest) -> (rest, x); [] -> ([], Nothing)))) $+ traceFrames 80 (\line -> liftIO (modifyIORef' lines' (line :))) $+ sendFrame "MOO/1 REQUEST svc:1/ask\nRequest-Id: 0\n\n" >> toList frames+ reverse <$> readIORef lines' >>= (@?= ["-> REQUEST svc:1/ask [0]", "<- COMPLETE Success [0]", "<- connection closed"])+ ]+ , testCase "registers over a real WebSocket" $ do+ (outcome, ()) <- withLoopbackServer empty (withRoon' pure) $ \wire -> do+ registerRequest <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ sendToClient wire (serverRequest "0" "com.roonlabs.ping:1/ping")+ pong <- receiveFromClient wire+ (pong.verb, pong.name) @?= (Complete, "Success")+ answer wire registerRequest Continue "Registered" (registered "tok-1")+ fmap ((.token) . fst) outcome @?= Right "tok-1"+ fmap snd outcome @?= Right (singleton "core-1" "tok-1")+ , testCase "carries a body larger than one network packet" $ do+ let large = RawBody "application/octet-stream" (mconcat (replicate 20_000 "0123456789"))+ client address = withRoon address extension $ \_ -> request "svc:1/echo" large+ (outcome, ()) <- withLoopbackServer (singleton "core-1" "tok") client $ \wire -> do+ registerRequest <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ answer wire registerRequest Continue "Registered" (registered "tok")+ echo <- expectRequest wire "svc:1/echo"+ answer wire echo Complete "Success" echo.body+ fmap ((.body) . fst) outcome @?= Right large+ , testCase "connects again after losing the connection" $ do+ let policy = Reconnect {firstDelay = 1_000, maxDelay = 10_000, maxAttempts = Just 5}+ client address = withRoonReconnecting policy address extension $ \_ -> (.name) <$> request "svc:1/echo" NoBody+ (outcome, ()) <- withLoopbackServer empty client $ \wire -> do+ -- The first connection is lost while the request waits.+ registerRequest <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ answer wire registerRequest Continue "Registered" (registered "tok-1")+ _ <- expectRequest wire "svc:1/echo"+ closeConnection wire+ -- The second one answers.+ again <- serveInfo wire >> expectRequest wire "com.roonlabs.registry:1/register"+ field "token" again @?= Just (String "tok-1")+ answer wire again Continue "Registered" (registered "tok-1")+ echo <- expectRequest wire "svc:1/echo"+ answer wire echo Complete "Again" NoBody+ fmap fst outcome @?= Right "Again"+ , testCase "reports the loss when the server closes the connection" $ do+ (outcome, ()) <- withLoopbackServer empty (withRoon' pure) $ \wire -> do+ _ <- expectRequest wire "com.roonlabs.registry:1/info"+ closeConnection wire+ fmap fst outcome @?= Left ConnectionLost+ , testCase "reports a refused connection" $ do+ port <- freePort+ outcome <- runClient empty (withRoon' pure ServerAddress {host = "127.0.0.1", port})+ case outcome of+ Left (ConnectFailed _) -> pure ()+ other -> assertFailure ("unexpected outcome: " <> show (fmap fst other))+ ]+ where+ withRoon' action address = withRoon address extension action++type ClientEffects = '[TokenStore, Error RoonError, Concurrent, IOE]++runClient :: Map Text Text -> Eff ClientEffects a -> IO (Either RoonError (a, Map Text Text))+runClient tokens = runEff . runConcurrent . runErrorNoCallStack . runTokenStorePure tokens++-- | Run a client against a server script, over a WebSocket on a free+-- loopback port.+withLoopbackServer+ :: Map Text Text+ -> (ServerAddress -> Eff ClientEffects a)+ -> (Wire -> IO b)+ -> IO (Either RoonError (a, Map Text Text), b)+withLoopbackServer tokens client script = do+ wire <- newWire+ bracket (listen "127.0.0.1" 0) N.close $ \listener -> do+ port <- fromIntegral <$> socketPort listener+ withAsync (serveSocket listener defaultServerOptions (const (bridge wire))) $ \_ ->+ withAsync (script wire) $ \scriptThread -> do+ outcome <- runClient tokens (client ServerAddress {host = "127.0.0.1", port})+ result <- wait scriptThread+ pure (outcome, result)++-- | Serve one connection by moving frames between it and the wire.+bridge :: Wire -> Connection -> IO ()+bridge wire connection =+ race_+ (fold (drainMapM (atomically . writeTQueue wire.toServer . bytesOf)) (messages connection))+ forward+ where+ bytesOf = \case+ BinaryMessage bytes -> bytes+ TextMessage text -> encodeUtf8 text+ forward =+ atomically (readTQueue wire.toClient) >>= \case+ Just frame -> send connection (BinaryMessage frame) >> forward+ Nothing -> WSS.close connection++-- | A port that was free a moment ago.+freePort :: IO Int+freePort =+ bracket (N.socket AF_INET Stream defaultProtocol) N.close $ \socket -> do+ bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ fromIntegral <$> socketPort socket
+ test/Roon/ImageSpec.hs view
@@ -0,0 +1,153 @@+-- | Image requests, and fetching against a fake HTTP server on loopback.+module Roon.ImageSpec (tests) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (wait, withAsync)+import Control.Exception (bracket)+import Data.ByteString (ByteString, isInfixOf)+import Data.ByteString qualified as BS (length, null, pack, replicate,+ takeWhile)+import Data.ByteString.Char8 qualified as BS8 (pack)+import Data.Text qualified as T (replicate)+import Effectful (runEff)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.HTTP (Request (..), Response (..), runHttpWith)+import Network.Socket (Family (AF_INET), SockAddr (SockAddrInet), Socket,+ SocketOption (ReuseAddr), SocketType (Stream), accept,+ bind, close, defaultProtocol, setSocketOption,+ socketPort, tupleToHostAddress)+import Network.Socket qualified as N (listen, socket)+import Network.Socket.ByteString (recv, sendAll)+import Roon.Effect.WebSocket (ServerAddress (..))+import Roon.Error (RoonError (..))+import Roon.Image (Image (Image, bytes, contentType), ImageFormat (Jpeg, Png),+ ImageLimits (maxBytes, microseconds),+ ImageOptions (ImageOptions, format, size),+ ImageSize (Original, Scaled), Scale (Fill, Stretch),+ defaultImageLimits, fetchImage, fitWithin, imageTarget,+ originalImage, runImageHttp)+import Test.Tasty (TestTree, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++tests :: TestTree+tests =+ localOption (mkTimeout 10_000_000) $+ testGroup+ "Roon.Image"+ [ testCase "asks for the stored image without a query" $+ imageTarget "846a4ef9" originalImage @?= "/api/image/846a4ef9"+ , testCase "asks for a size and a format" $ do+ imageTarget "k" (fitWithin 300) @?= "/api/image/k?scale=fit&width=300&height=300"+ imageTarget "k" ImageOptions {size = Scaled Fill 640 480, format = Just Jpeg}+ @?= "/api/image/k?scale=fill&width=640&height=480&format=image/jpeg"+ imageTarget "k" ImageOptions {size = Scaled Stretch 1 2, format = Just Png}+ @?= "/api/image/k?scale=stretch&width=1&height=2&format=image/png"+ imageTarget "k" ImageOptions {size = Original, format = Just Png} @?= "/api/image/k?format=image/png"+ , testCase "encodes a key that would change the request" $+ imageTarget "a/b?c d\n\233" originalImage @?= "/api/image/a%2Fb%3Fc%20d%0A%C3%A9"+ , testCase "asks in clear for the target of the key, on the port of the server" $ do+ let echo scheme request = Response {status = 200, reason = "OK", headers = [("content-type", "image/png")], body = BS8.pack (show scheme <> " " <> request.host <> " " <> show request.port <> " ") <> request.method <> " " <> request.target}+ outcome <- answered echo (fetchImage ServerAddress {host = "192.0.2.7", port = 9330} "k" (fitWithin 64))+ outcome @?= Right Image {contentType = "image/png", bytes = "Http 192.0.2.7 9330 GET /api/image/k?scale=fit&width=64&height=64"}+ , testCase "a refusal answered from a function, with at most 1024 bytes of explanation" $ do+ let refuse _ _ = Response {status = 400, reason = "Bad Request", headers = [], body = BS.replicate 5000 120}+ outcome <- answered refuse (fetchImage ServerAddress {host = "192.0.2.7", port = 9330} "k" originalImage)+ outcome @?= Left (ImageFailed ("400 Bad Request " <> T.replicate 1024 "x"))+ , testCase "fetches an image" $ do+ let jpeg = BS.pack (take 70_000 (cycle [255, 216, 255, 224, 0, 16]))+ (request, outcome) <- withServer (ok "image/jpeg" jpeg) $ \address ->+ fetch address "key" (fitWithin 300)+ BS.takeWhile (/= 13) request @?= "GET /api/image/key?scale=fit&width=300&height=300 HTTP/1.1"+ outcome @?= Right Image {contentType = "image/jpeg", bytes = jpeg}+ , testCase "reports a refusal with the explanation of the server" $ do+ (_, unknown) <- withServer ["HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"] $ \address ->+ fetch address "nope" originalImage+ unknown @?= Left (ImageFailed "404 Not Found")+ (_, invalid) <- withServer ["HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: 20\r\n\r\nInvalid Scale: bogus"] $ \address ->+ fetch address "key" originalImage+ invalid @?= Left (ImageFailed "400 Bad Request Invalid Scale: bogus")+ , testCase "refuses an image larger than the limit, accepts one that reaches it" $ do+ let limits = defaultImageLimits {maxBytes = 1000}+ (_, tooLarge) <- withServer (ok "image/png" (BS.replicate 1001 7)) $ \address ->+ fetchWithin limits address+ tooLarge @?= Left (ImageFailed "the image is larger than 1000 bytes")+ (_, exact) <- withServer (ok "image/png" (BS.replicate 1000 7)) $ \address ->+ fetchWithin limits address+ fmap (BS.length . (.bytes)) exact @?= Right 1000+ , testCase "reports what is not HTTP, and a body cut short" $ do+ (_, notHttp) <- withServer ["MOO/1 COMPLETE Success\n\n"] $ \address -> fetch address "key" originalImage+ case notHttp of+ Left (ImageFailed _) -> pure ()+ other -> assertFailure ("expected ImageFailed, got " <> show other)+ (_, cut) <- withServer ["HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc"] $ \address -> fetch address "key" originalImage+ cut @?= Left (ImageFailed "TruncatedBody 7")+ , testCase "times out on a server that does not answer" $ do+ let limits = defaultImageLimits {microseconds = 100_000}+ outcome <- withSilentServer $ \address ->+ fetchWithin limits address+ outcome @?= Left (TimedOut "image")+ , testCase "reports a refused connection" $ do+ port <- closedPort+ outcome <- fetch ServerAddress {host = "127.0.0.1", port} "key" originalImage+ case outcome of+ Left (ConnectFailed _) -> pure ()+ other -> assertFailure ("expected ConnectFailed, got " <> show other)+ ]+ where+ fetchWithin limits address = runEff (runErrorNoCallStack @RoonError (runImageHttp limits (fetchImage address "key" originalImage)))+ fetch address key options = runEff (runErrorNoCallStack @RoonError (runImageHttp defaultImageLimits (fetchImage address key options)))+ -- The effect answered from a function: what is asked, without a server.+ answered response = runEff . runErrorNoCallStack @RoonError . runHttpWith (\scheme request -> pure (response scheme request))+ ok contentType content =+ [ "HTTP/1.1 200 OK\r\nContent-Type: " <> contentType <> "\r\nContent-Length: " <> BS8.pack (show (BS.length content)) <> "\r\n\r\n"+ , content+ ]++listen :: IO Socket+listen = do+ listener <- N.socket AF_INET Stream defaultProtocol+ setSocketOption listener ReuseAddr 1+ bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ N.listen listener 1+ pure listener++addressOf :: Socket -> IO ServerAddress+addressOf listener = do+ port <- socketPort listener+ pure ServerAddress {host = "127.0.0.1", port = fromIntegral port}++-- | Run a server that answers one connection: it reads the request head,+-- sends the answer and closes. Returns the request with the result.+withServer :: [ByteString] -> (ServerAddress -> IO a) -> IO (ByteString, a)+withServer answer action =+ bracket listen close $ \listener -> do+ address <- addressOf listener+ withAsync (serve listener) $ \server -> do+ result <- action address+ request <- wait server+ pure (request, result)+ where+ serve listener =+ bracket (fst <$> accept listener) close $ \peer -> do+ request <- readHead peer ""+ mapM_ (sendAll peer) answer+ pure request+ readHead peer seen+ | "\r\n\r\n" `isInfixOf` seen = pure seen+ | otherwise = do+ more <- recv peer 4096+ if BS.null more then pure seen else readHead peer (seen <> more)++-- | Run a server that accepts one connection and says nothing.+withSilentServer :: (ServerAddress -> IO a) -> IO a+withSilentServer action =+ bracket listen close $ \listener -> do+ address <- addressOf listener+ withAsync (bracket (fst <$> accept listener) close (\_ -> threadDelay 5_000_000)) $ \_ ->+ action address++-- | A port that was free a moment ago: bound, then closed.+closedPort :: IO Int+closedPort = bracket (N.socket AF_INET Stream defaultProtocol) close $ \socket -> do+ bind socket (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+ fromIntegral <$> socketPort socket
+ test/Roon/Moo/MessageSpec.hs view
@@ -0,0 +1,163 @@+module Roon.Moo.MessageSpec (tests) where++import Data.Aeson (Value, object, (.=))+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS (pack)+import Data.Map.Strict (empty, fromList, singleton)+import Data.Text (Text)+import Data.Text qualified as T (dropWhile, pack)+import Roon.Moo.Message (Body (..), MooMessage (..),+ MooParseError (ContentTypeWithoutLength, InvalidContentLength, InvalidJson, MalformedHeader, MissingContentType, MissingHeaderEnd, MissingRequestId, TruncatedBody, UnexpectedBody, UnknownVerb),+ RequestId (RequestId), Verb (..), encode, parse,+ splitServiceMethod)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.QuickCheck (Gen, arbitrary, chooseInt, counterexample,+ elements, forAll, frequency, listOf, listOf1,+ oneof, suchThat, testProperty, vectorOf, (===))++tests :: TestTree+tests =+ testGroup+ "Roon.Moo.Message"+ [ testGroup "encode" encodeTests+ , testGroup "parse" parseTests+ , testGroup "parse rejects" rejectTests+ , testProperty "parse . encode == Right" $+ forAll genMessage $ \msg ->+ counterexample (show (encode msg)) (parse (encode msg) === Right msg)+ , testCase "splitServiceMethod splits at the first slash" $ do+ splitServiceMethod "com.roonlabs.ping:1/ping" @?= Just ("com.roonlabs.ping:1", "ping")+ splitServiceMethod "service/a/b" @?= Just ("service", "a/b")+ splitServiceMethod "noslash" @?= Nothing+ splitServiceMethod "/method" @?= Nothing+ ]++encodeTests :: [TestTree]+encodeTests =+ [ testCase "request without body" $+ encode (message Request "com.roonlabs.registry:1/info" "0" NoBody)+ @?= "MOO/1 REQUEST com.roonlabs.registry:1/info\nRequest-Id: 0\n\n"+ , testCase "request with a JSON body" $+ encode (message Request "svc:1/method" "7" (JsonBody (object ["a" .= (1 :: Int)])))+ @?= "MOO/1 REQUEST svc:1/method\nRequest-Id: 7\nContent-Length: 7\nContent-Type: application/json\n\n{\"a\":1}"+ , testCase "reply with a raw body" $+ encode (message Complete "Success" "3" (RawBody "image/jpeg" "\255\216\255"))+ @?= "MOO/1 COMPLETE Success\nRequest-Id: 3\nContent-Length: 3\nContent-Type: image/jpeg\n\n\255\216\255"+ ]++parseTests :: [TestTree]+parseTests =+ [ testCase "reply without body" $+ parse "MOO/1 COMPLETE Success\nRequest-Id: 12\n\n"+ @?= Right (message Complete "Success" "12" NoBody)+ , testCase "reply with a JSON body" $+ parse "MOO/1 CONTINUE Registered\nRequest-Id: 1\nContent-Length: 17\nContent-Type: application/json\n\n{\"core_id\":\"abc\"}"+ @?= Right (message Continue "Registered" "1" (JsonBody (object ["core_id" .= ("abc" :: Text)])))+ , testCase "extra headers are kept, the three known ones are not" $+ parse "MOO/1 REQUEST com.roonlabs.ping:1/ping\nRequest-Id: 4\nLogging: quiet\n\n"+ @?= Right (message Request "com.roonlabs.ping:1/ping" "4" NoBody) {headers = singleton "Logging" "quiet"}+ , testCase "header values may omit the space after the colon" $+ parse "MOO/1 COMPLETE Success\nRequest-Id:5\n\n"+ @?= Right (message Complete "Success" "5" NoBody)+ , testCase "a zero Content-Length means no body" $+ parse "MOO/1 COMPLETE Success\nRequest-Id: 5\nContent-Length: 0\n\n"+ @?= Right (message Complete "Success" "5" NoBody)+ , testCase "bytes beyond Content-Length are ignored" $+ parse "MOO/1 COMPLETE Success\nRequest-Id: 5\nContent-Length: 2\nContent-Type: text/plain\n\nabcdef"+ @?= Right (message Complete "Success" "5" (RawBody "text/plain" "ab"))+ , testCase "a body may itself contain an empty line" $+ parse "MOO/1 COMPLETE Success\nRequest-Id: 5\nContent-Length: 4\nContent-Type: text/plain\n\na\n\nb"+ @?= Right (message Complete "Success" "5" (RawBody "text/plain" "a\n\nb"))+ ]++rejectTests :: [TestTree]+rejectTests =+ [ rejects "an empty frame" "" (== MissingHeaderEnd)+ , rejects "a frame without the empty line" "MOO/1 COMPLETE Success\nRequest-Id: 1\n" (== MissingHeaderEnd)+ , rejects "another protocol version" "MOO/2 COMPLETE Success\nRequest-Id: 1\n\n" isMalformedHeader+ , rejects "a header line without a colon" "MOO/1 COMPLETE Success\nRequest-Id 1\n\n" isMalformedHeader+ , rejects "an unknown verb" "MOO/1 FROBNICATE Success\nRequest-Id: 1\n\n" (== UnknownVerb "FROBNICATE")+ , rejects "a missing Request-Id" "MOO/1 COMPLETE Success\nLogging: quiet\n\n" (== MissingRequestId)+ , rejects+ "a Content-Type without a Content-Length"+ "MOO/1 COMPLETE Success\nRequest-Id: 1\nContent-Type: application/json\n\n"+ (== ContentTypeWithoutLength)+ , rejects+ "a body without a Content-Type"+ "MOO/1 COMPLETE Success\nRequest-Id: 1\nContent-Length: 2\n\n{}"+ (== MissingContentType)+ , rejects "an unannounced body" "MOO/1 COMPLETE Success\nRequest-Id: 1\n\n{}" (== UnexpectedBody)+ , rejects+ "a truncated body"+ "MOO/1 COMPLETE Success\nRequest-Id: 1\nContent-Length: 10\nContent-Type: text/plain\n\nabc"+ (== TruncatedBody 10 3)+ , rejects+ "a non-numeric Content-Length"+ "MOO/1 COMPLETE Success\nRequest-Id: 1\nContent-Length: two\nContent-Type: text/plain\n\nab"+ (== InvalidContentLength "two")+ , rejects+ "invalid JSON"+ "MOO/1 COMPLETE Success\nRequest-Id: 1\nContent-Length: 1\nContent-Type: application/json\n\n{"+ isInvalidJson+ ]+ where+ rejects label frame expected = testCase label $ case parse frame of+ Left err+ | expected err -> pure ()+ | otherwise -> assertFailure ("unexpected error: " <> show err)+ Right msg -> assertFailure ("unexpectedly parsed: " <> show msg)+ isMalformedHeader = \case+ MalformedHeader _ _ -> True+ _ -> False+ isInvalidJson = \case+ InvalidJson _ -> True+ _ -> False++message :: Verb -> Text -> Text -> Body -> MooMessage+message verb name rid body =+ MooMessage {verb, name, requestId = RequestId rid, headers = empty, body}++-- Generators. They only produce messages that the format can represent:+-- no line feed in a line, no leading space in a header value, a non-empty+-- raw body whose content type is not the JSON one.++genMessage :: Gen MooMessage+genMessage = do+ verb <- elements [minBound .. maxBound]+ name <- genLine+ requestId <- RequestId <$> genToken+ headers <- fromList <$> listOf ((,) <$> genHeaderName <*> genHeaderValue)+ body <- genBody+ pure MooMessage {verb, name, requestId, headers, body}++genBody :: Gen Body+genBody =+ frequency+ [ (1, pure NoBody)+ , (3, JsonBody <$> (arbitrary :: Gen Value))+ , (1, RawBody <$> elements ["image/jpeg", "image/png", "text/plain"] <*> genBytes)+ ]++genBytes :: Gen ByteString+genBytes = do+ size <- chooseInt (1, 64)+ BS.pack <$> vectorOf size arbitrary++-- | Any text that fits on a line.+genLine :: Gen Text+genLine = T.pack <$> listOf (genChar `suchThat` (/= '\n'))++genToken :: Gen Text+genToken = T.pack <$> listOf1 (elements (['a' .. 'z'] <> ['0' .. '9']))++genHeaderName :: Gen Text+genHeaderName = genName `suchThat` (`notElem` ["Request-Id", "Content-Length", "Content-Type"])+ where+ genName = T.pack <$> listOf1 (elements (['A' .. 'Z'] <> ['a' .. 'z'] <> "-"))++genHeaderValue :: Gen Text+genHeaderValue = T.dropWhile (== ' ') <$> genLine++genChar :: Gen Char+genChar = oneof [elements (['a' .. 'z'] <> " :/.-_{}\""), elements "éß→音", arbitrary `suchThat` (\c -> c < '\xD800' || c > '\xDFFF')]
+ test/Roon/Test/Server.hs view
@@ -0,0 +1,159 @@+-- | A scripted Roon Server for the tests: fixtures, the queues that stand+-- for the connection, and the steps a script is made of.+module Roon.Test.Server+ ( -- * Fixtures+ extension+ , testCore+ , coreBody+ , registered++ -- * The wire+ , Wire (..)+ , newWire+ , withServer++ -- * Script steps+ , receiveFromClient+ , sendToClient+ , closeConnection+ , expectRequest+ , answer+ , serverRequest+ , serveInfo+ , field+ ) where++import Control.Concurrent.Async (wait, withAsync)+import Control.Concurrent.STM (TQueue, atomically, newTQueueIO, readTQueue,+ writeTQueue)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.Key (fromText)+import Data.Aeson.KeyMap qualified as JK (lookup)+import Data.ByteString (ByteString)+import Data.Map.Strict (Map, empty)+import Data.Text (Text)+import Effectful (Eff, IOE, MonadIO (liftIO), runEff)+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Error.Static (Error, runErrorNoCallStack)+import Roon.Effect.TokenStore (TokenStore, runTokenStorePure)+import Roon.Effect.WebSocket (WebSocket, runWebSocketWith)+import Roon.Error (RoonError)+import Roon.Moo.Message (Body (JsonBody, NoBody), MooMessage (..),+ RequestId (RequestId), Verb (Complete, Request),+ encode, parse)+import Roon.Registry (CoreInfo (..), ExtensionInfo (..))+import Test.Tasty.HUnit (assertBool, assertFailure, (@?=))++-- Fixtures++extension :: ExtensionInfo+extension =+ ExtensionInfo+ { extensionId = "test.extension"+ , displayName = "Test extension"+ , displayVersion = "0.0.1"+ , publisher = "roon-api tests"+ , email = "nobody@example.invalid"+ , website = Nothing+ , requiredServices = ["com.roonlabs.transport:2"]+ , optionalServices = []+ , providedServices = []+ }++testCore :: CoreInfo+testCore = CoreInfo {coreId = "core-1", displayName = "Test Core", displayVersion = "2.0 (build 1)"}++coreBody :: Body+coreBody =+ JsonBody . object $+ [ "core_id" .= ("core-1" :: Text)+ , "display_name" .= ("Test Core" :: Text)+ , "display_version" .= ("2.0 (build 1)" :: Text)+ ]++registered :: Text -> Body+registered token =+ JsonBody . object $+ [ "core_id" .= ("core-1" :: Text)+ , "display_name" .= ("Test Core" :: Text)+ , "display_version" .= ("2.0 (build 1)" :: Text)+ , "token" .= token+ , "provided_services" .= ["com.roonlabs.transport:2" :: Text]+ , "http_port" .= (9330 :: Int)+ ]++-- The connection, as seen from the server++data Wire = Wire+ { toServer :: TQueue ByteString+ , toClient :: TQueue (Maybe ByteString)+ -- ^ 'Nothing' closes the connection.+ }++newWire :: IO Wire+newWire = Wire <$> newTQueueIO <*> newTQueueIO++-- The in-memory transport++type ClientEffects = '[WebSocket, TokenStore, Error RoonError, Concurrent, IOE]++-- | Run a client against a server script. Returns what the client+-- produced, with the tokens it holds at the end, and what the script+-- returned.+withServer+ :: Map Text Text+ -> Eff ClientEffects a+ -> (Wire -> IO b)+ -> IO (Either RoonError (a, Map Text Text), b)+withServer tokens client server = do+ wire <- newWire+ let sendAction frame = liftIO (True <$ atomically (writeTQueue wire.toServer frame))+ receiveAction = liftIO (atomically (readTQueue wire.toClient))+ runClient =+ runEff . runConcurrent . runErrorNoCallStack . runTokenStorePure tokens $+ runWebSocketWith sendAction receiveAction client+ withAsync (server wire) $ \serverThread -> do+ outcome <- runClient+ result <- wait serverThread+ pure (outcome, result)++receiveFromClient :: Wire -> IO MooMessage+receiveFromClient wire = do+ frame <- atomically (readTQueue wire.toServer)+ either (\err -> assertFailure ("the client sent a malformed frame: " <> show err)) pure (parse frame)++sendToClient :: Wire -> MooMessage -> IO ()+sendToClient wire = atomically . writeTQueue wire.toClient . Just . encode++closeConnection :: Wire -> IO ()+closeConnection wire = atomically (writeTQueue wire.toClient Nothing)++-- | Wait for a request and check its name.+expectRequest :: Wire -> Text -> IO MooMessage+expectRequest wire name = do+ message <- receiveFromClient wire+ (message.verb, message.name) @?= (Request, name)+ pure message++-- | Reply to a request of the client.+answer :: Wire -> MooMessage -> Verb -> Text -> Body -> IO ()+answer wire to verb name body =+ sendToClient wire MooMessage {verb, name, requestId = to.requestId, headers = empty, body}++-- | A request made by the server.+serverRequest :: Text -> Text -> MooMessage+serverRequest requestId name =+ MooMessage {verb = Request, name, requestId = RequestId requestId, headers = empty, body = NoBody}++-- | Answer the info request that opens every registration.+serveInfo :: Wire -> IO ()+serveInfo wire = do+ infoRequest <- expectRequest wire "com.roonlabs.registry:1/info"+ assertBool "info carries no body" (infoRequest.body == NoBody)+ answer wire infoRequest Complete "Success" coreBody++-- | A field of the JSON body of a message.+field :: Text -> MooMessage -> Maybe Value+field key message = case message.body of+ JsonBody (Object fields) -> JK.lookup (fromText key) fields+ _ -> Nothing
+ test/Roon/TransportSpec.hs view
@@ -0,0 +1,301 @@+{-# LANGUAGE RecordWildCards #-}++-- | The transport service, against a scripted server. The zone and output+-- fixtures are answers of a real Roon Server 2.75.+module Roon.TransportSpec (tests) where++import Data.Aeson (Value (..), decodeStrictText, object, (.=))+import Data.List (sort, sortOn)+import Data.Map.Strict (empty, keys, singleton)+import Data.Map.Strict qualified as M (lookup)+import Data.Maybe (fromJust)+import Data.Text (Text)+import Roon.Effect.Moo (defaultRequestHandler, runMoo)+import Roon.Error (RoonError (..))+import Roon.Moo.Message (Body (JsonBody, NoBody), MooMessage (body, name),+ Verb (Complete, Continue))+import Roon.Test.Server (answer, expectRequest, field, receiveFromClient,+ withServer)+import Roon.Transport (Control (Next, Play), DisplayLines (DisplayLines),+ Loop (LoopDisabled), LoopChange (NextLoop),+ NowPlaying (..), Output (..), OutputId (OutputId),+ PlaybackState (Paused), QueueChange (OtherQueueChange),+ QueueEvent (QueueChanged, QueueSubscribed),+ QueueItem (..),+ SeekChange (SeekChange, queueTimeRemaining, seekPosition, zoneId),+ SettingsChange (setLoop, setShuffle),+ SourceControl (SourceControl, controlKey, displayName, status, supportsStandby),+ SourceControlStatus (Indeterminate),+ TransportEvent (QueueUpdate, ZoneUpdate), Zone (..),+ ZoneChanges (ZoneChanges, added, changed, removed, seekChanged),+ ZoneEvent (..), ZoneId (..),+ ZoneSettings (ZoneSettings, autoRadio, loop, shuffle),+ applyQueueEvent, changeSettings, control, getOutputs,+ getZones, noSettingsChange, queue, subscribeQueue,+ subscribeTransport, subscribeZones, zoneViews,+ zoneViewsEvery, zones)+import Streamly.Data.Fold (drain)+import Streamly.Data.Fold qualified as F (length, one)+import Streamly.Data.Stream (fold, fromList, toList)+import Streamly.Data.Stream qualified as S (take)+import Test.Tasty (TestTree, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++tests :: TestTree+tests =+ localOption (mkTimeout 5_000_000) $+ testGroup+ "Roon.Transport"+ [ testCase "decodes the zones of a real server" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler getZones) $ \wire -> do+ question <- expectRequest wire "com.roonlabs.transport:2/get_zones"+ answer wire question Complete "Success" (JsonBody realZones)+ fmap fst outcome @?= Right [livingRoom]+ , testCase "decodes the outputs of a real server" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler getOutputs) $ \wire -> do+ question <- expectRequest wire "com.roonlabs.transport:2/get_outputs"+ answer wire question Complete "Success" (JsonBody (object ["outputs" .= [realOutput]]))+ fmap fst outcome @?= Right [livingRoomOutput]+ , testCase "operates a zone" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler (control livingRoom.zoneId Next)) $ \wire -> do+ question <- expectRequest wire "com.roonlabs.transport:2/control"+ field "zone_or_output_id" question @?= Just (String "zone-0001")+ field "control" question @?= Just (String "next")+ answer wire question Complete "Success" NoBody+ fmap fst outcome @?= Right ()+ , testCase "reports a refused control" $ do+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler (control livingRoomOutput.outputId Play)) $ \wire -> do+ question <- expectRequest wire "com.roonlabs.transport:2/control"+ field "zone_or_output_id" question @?= Just (String "output-0001")+ answer wire question Complete "InvalidRequest" NoBody+ fmap fst outcome @?= Left (UnexpectedReply "com.roonlabs.transport:2/control" "InvalidRequest")+ , testCase "changes only the settings asked for" $ do+ let change = noSettingsChange {setShuffle = Just True, setLoop = Just NextLoop}+ (outcome, ()) <- withServer empty (runMoo defaultRequestHandler (changeSettings livingRoom.zoneId change)) $ \wire -> do+ question <- expectRequest wire "com.roonlabs.transport:2/change_settings"+ question.body+ @?= JsonBody+ ( object+ [ "zone_or_output_id" .= ("zone-0001" :: Text)+ , "shuffle" .= True+ , "loop" .= ("next" :: Text)+ ]+ )+ answer wire question Complete "Success" NoBody+ fmap fst outcome @?= Right ()+ , testCase "follows the zones, then unsubscribes with the same key" $ do+ let client = runMoo defaultRequestHandler (subscribeZones (fold zones . S.take 3))+ (outcome, ()) <- withServer empty client $ \wire -> do+ subscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_zones"+ let key = field "subscription_key" subscription+ key @?= Just (Number 0)+ answer wire subscription Continue "Subscribed" (JsonBody realZones)+ answer wire subscription Continue "Changed" . JsonBody $+ object+ [ "zones_added" .= [object ["zone_id" .= ("kitchen" :: Text), "display_name" .= ("Kitchen" :: Text), "state" .= ("stopped" :: Text)]]+ , "zones_seek_changed" .= [object ["zone_id" .= livingRoom.zoneId, "seek_position" .= (100 :: Int), "queue_time_remaining" .= (2152 :: Int)]]+ ]+ answer wire subscription Continue "Changed" (JsonBody (object ["zones_removed" .= ["kitchen" :: Text]]))+ unsubscription <- expectRequest wire "com.roonlabs.transport:2/unsubscribe_zones"+ field "subscription_key" unsubscription @?= key+ answer wire unsubscription Complete "Success" NoBody+ let seeked = let Zone {..} = livingRoom in Zone {nowPlaying = atSeek 100 <$> nowPlaying, queueTimeRemaining = Just 2152, ..}+ fmap fst outcome @?= Right (singleton livingRoom.zoneId seeked)+ , testCase "gives a view of the zones after each event" $ do+ views <- toList (zoneViews (fromList zoneScript))+ map keys views @?= [[livingRoom.zoneId], [livingRoom.zoneId], [livingRoom.zoneId], [livingRoom.zoneId, kitchen], [livingRoom.zoneId, kitchen]]+ , testCase "holds back views that only move the seek position" $ do+ views <- toList (zoneViewsEvery 3600 (fromList zoneScript))+ -- The subscription, then the new zone, which carries the+ -- positions held back.+ map keys views @?= [[livingRoom.zoneId], [livingRoom.zoneId, kitchen]]+ fmap (.nowPlaying) (M.lookup livingRoom.zoneId (last views)) @?= Just (atSeek 120 <$> livingRoom.nowPlaying)+ , testCase "gives every view when the interval is zero" $ do+ views <- toList (zoneViewsEvery 0 (fromList zoneScript))+ length views @?= length zoneScript+ , testCase "ends the stream when the server ends the subscription" $ do+ let client = runMoo defaultRequestHandler (subscribeZones (fold F.length))+ (outcome, ()) <- withServer empty client $ \wire -> do+ subscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_zones"+ answer wire subscription Continue "Subscribed" (JsonBody realZones)+ answer wire subscription Complete "Unsubscribed" NoBody+ _ <- expectRequest wire "com.roonlabs.transport:2/unsubscribe_zones"+ pure ()+ fmap fst outcome @?= Right 1+ , testCase "reports an unexpected subscription status" $ do+ let client = runMoo defaultRequestHandler (subscribeZones (fold drain))+ (outcome, ()) <- withServer empty client $ \wire -> do+ subscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_zones"+ answer wire subscription Complete "NotAllowed" NoBody+ _ <- expectRequest wire "com.roonlabs.transport:2/unsubscribe_zones"+ pure ()+ fmap fst outcome @?= Left (UnexpectedReply "com.roonlabs.transport:2/subscribe_zones" "NotAllowed")+ , testCase "follows zones and queues as one stream" $ do+ let client = runMoo defaultRequestHandler (subscribeTransport [livingRoom.zoneId] 2 (toList . S.take 2))+ (outcome, ()) <- withServer empty client $ \wire -> do+ zoneSubscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_zones"+ queueSubscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_queue"+ answer wire queueSubscription Continue "Subscribed" (JsonBody realQueue)+ answer wire zoneSubscription Continue "Subscribed" (JsonBody realZones)+ ends <- (,) <$> receiveFromClient wire <*> receiveFromClient wire+ let names = [(fst ends).name, (snd ends).name]+ sort names @?= ["com.roonlabs.transport:2/unsubscribe_queue", "com.roonlabs.transport:2/unsubscribe_zones"]+ fmap (sortOn show . fst) outcome+ @?= Right (sortOn show [QueueUpdate livingRoom.zoneId (QueueSubscribed [firstSong, secondSong]), ZoneUpdate (ZonesSubscribed [livingRoom])])+ , testCase "reads the first items of a queue" $ do+ let client = runMoo defaultRequestHandler (subscribeQueue livingRoom.zoneId 2 (fold F.one))+ (outcome, ()) <- withServer empty client $ \wire -> do+ subscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_queue"+ field "zone_or_output_id" subscription @?= Just (String "zone-0001")+ field "max_item_count" subscription @?= Just (Number 2)+ answer wire subscription Continue "Subscribed" (JsonBody realQueue)+ _ <- expectRequest wire "com.roonlabs.transport:2/unsubscribe_queue"+ pure ()+ fmap fst outcome @?= Right (Just (QueueSubscribed [firstSong, secondSong]))+ , testCase "follows a queue through a real change" $ do+ let client = runMoo defaultRequestHandler (subscribeQueue livingRoom.zoneId 5 (fold queue . S.take 2))+ (outcome, ()) <- withServer empty client $ \wire -> do+ subscription <- expectRequest wire "com.roonlabs.transport:2/subscribe_queue"+ answer wire subscription Continue "Subscribed" (JsonBody capturedQueue)+ answer wire subscription Continue "Changed" (JsonBody capturedQueueChange)+ _ <- expectRequest wire "com.roonlabs.transport:2/unsubscribe_queue"+ pure ()+ fmap (map (.queueItemId) . fst) outcome @?= Right [1002, 1003, 1004, 1005, 1006]+ , testCase "keeps a queue operation it does not know" $+ applyQueueEvent (QueueChanged [OtherQueueChange (object ["operation" .= ("move" :: Text)])]) [firstSong]+ @?= [firstSong]+ ]++atSeek :: Int -> NowPlaying -> NowPlaying+atSeek position (NowPlaying _ len image artists one two three) = NowPlaying (Just position) len image artists one two three++kitchen :: ZoneId+kitchen = ZoneId "zone-0002"++-- | A subscription, two seek moves, a new zone, another seek move.+zoneScript :: [ZoneEvent]+zoneScript =+ [ ZonesSubscribed [livingRoom]+ , seekTo 110+ , seekTo 120+ , ZonesChanged noChanges {added = [kitchenZone]}+ , seekTo 130+ ]+ where+ seekTo position = ZonesChanged noChanges {seekChanged = [SeekChange {zoneId = livingRoom.zoneId, seekPosition = Just position, queueTimeRemaining = Nothing}]}+ noChanges = ZoneChanges {removed = [], added = [], changed = [], seekChanged = []}+ kitchenZone = let Zone {..} = livingRoom in Zone {zoneId = kitchen, displayName = "Kitchen", outputs = [], nowPlaying = Nothing, ..}++-- Fixtures++realZones :: Value+realZones = fromJust . decodeStrictText $+ "{\"zones\":[{\"display_name\":\"Living Room\",\"is_next_allowed\":true,\"is_pause_allowed\":false,\"is_play_allowed\":true,\+ \\"is_previous_allowed\":true,\"is_seek_allowed\":true,\"now_playing\":{\"artist_image_keys\":[\"artist-image-0001\"],\+ \\"image_key\":\"album-image-0001\",\"length\":306,\"one_line\":{\"line1\":\"First Song - The Example Band\"},\+ \\"seek_position\":82,\"three_line\":{\"line1\":\"First Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\+ \\"two_line\":{\"line1\":\"First Song\",\"line2\":\"The Example Band\"}},\+ \\"outputs\":[{\"can_group_with_output_ids\":[\"output-0001\"],\"display_name\":\"Living Room\",\+ \\"output_id\":\"output-0001\",\+ \\"source_controls\":[{\"control_key\":\"1\",\"display_name\":\"Amplifier\",\"status\":\"indeterminate\",\"supports_standby\":false}],\+ \\"zone_id\":\"zone-0001\"}],\+ \\"queue_items_remaining\":11,\"queue_time_remaining\":2170,\+ \\"settings\":{\"auto_radio\":true,\"loop\":\"disabled\",\"shuffle\":false},\"state\":\"paused\",\"zone_id\":\"zone-0001\"}]}"++realOutputText :: Text+realOutputText =+ "{\"can_group_with_output_ids\":[\"output-0001\"],\"display_name\":\"Living Room\",\+ \\"output_id\":\"output-0001\",\+ \\"source_controls\":[{\"control_key\":\"1\",\"display_name\":\"Amplifier\",\"status\":\"indeterminate\",\"supports_standby\":false}],\+ \\"zone_id\":\"zone-0001\"}"++realOutput :: Value+realOutput = fromJust (decodeStrictText realOutputText)++realQueue :: Value+realQueue = fromJust . decodeStrictText $+ "{\"items\":[{\"image_key\":\"album-image-0001\",\"length\":306,\"one_line\":{\"line1\":\"First Song - The Example Band\"},\+ \\"queue_item_id\":1001,\"three_line\":{\"line1\":\"First Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\+ \\"two_line\":{\"line1\":\"First Song\",\"line2\":\"The Example Band\"}},\+ \{\"image_key\":\"album-image-0001\",\"length\":159,\"one_line\":{\"line1\":\"Second Song - The Example Band\"},\+ \\"queue_item_id\":1002,\"three_line\":{\"line1\":\"Second Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\+ \\"two_line\":{\"line1\":\"Second Song\",\"line2\":\"The Example Band\"}}]}"++-- | A queue of five items, as Roon reported it while Living Room played.+capturedQueue :: Value+capturedQueue = fromJust . decodeStrictText $+ "{\"items\":[{\"image_key\":\"album-image-0001\",\"length\":306,\"one_line\":{\"line1\":\"First Song - The Example Band\"},\"queue_item_id\":1001,\"three_line\":{\"line1\":\"First Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"First Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":159,\"one_line\":{\"line1\":\"Second Song - The Example Band\"},\"queue_item_id\":1002,\"three_line\":{\"line1\":\"Second Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Second Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":179,\"one_line\":{\"line1\":\"Third Song - The Example Band\"},\"queue_item_id\":1003,\"three_line\":{\"line1\":\"Third Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Third Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":242,\"one_line\":{\"line1\":\"Fourth Song - The Example Band\"},\"queue_item_id\":1004,\"three_line\":{\"line1\":\"Fourth Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Fourth Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":137,\"one_line\":{\"line1\":\"Fifth Song - The Example Band\"},\"queue_item_id\":1005,\"three_line\":{\"line1\":\"Fifth Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Fifth Song\",\"line2\":\"The Example Band\"}}]}"++-- | What Roon sent for that queue when the first track ended.+capturedQueueChange :: Value+capturedQueueChange = fromJust . decodeStrictText $+ "{\"changes\":[{\"count\":5,\"index\":0,\"operation\":\"remove\"},{\"index\":0,\"items\":[{\"image_key\":\"album-image-0001\",\"length\":159,\"one_line\":{\"line1\":\"Second Song - The Example Band\"},\"queue_item_id\":1002,\"three_line\":{\"line1\":\"Second Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Second Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":179,\"one_line\":{\"line1\":\"Third Song - The Example Band\"},\"queue_item_id\":1003,\"three_line\":{\"line1\":\"Third Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Third Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":242,\"one_line\":{\"line1\":\"Fourth Song - The Example Band\"},\"queue_item_id\":1004,\"three_line\":{\"line1\":\"Fourth Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Fourth Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":137,\"one_line\":{\"line1\":\"Fifth Song - The Example Band\"},\"queue_item_id\":1005,\"three_line\":{\"line1\":\"Fifth Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Fifth Song\",\"line2\":\"The Example Band\"}},\+ \ {\"image_key\":\"album-image-0001\",\"length\":181,\"one_line\":{\"line1\":\"Sixth Song - The Example Band\"},\"queue_item_id\":1006,\"three_line\":{\"line1\":\"Sixth Song\",\"line2\":\"The Example Band\",\"line3\":\"Example Album\"},\"two_line\":{\"line1\":\"Sixth Song\",\"line2\":\"The Example Band\"}}],\"operation\":\"insert\"}]}"++livingRoom :: Zone+livingRoom =+ Zone+ { zoneId = ZoneId "zone-0001"+ , displayName = "Living Room"+ , outputs = [livingRoomOutput]+ , state = Paused+ , isPreviousAllowed = True+ , isNextAllowed = True+ , isPauseAllowed = False+ , isPlayAllowed = True+ , isSeekAllowed = True+ , queueItemsRemaining = Just 11+ , queueTimeRemaining = Just 2170+ , settings = Just ZoneSettings {loop = LoopDisabled, shuffle = False, autoRadio = True}+ , nowPlaying =+ Just+ NowPlaying+ { seekPosition = Just 82+ , length = Just 306+ , imageKey = Just "album-image-0001"+ , artistImageKeys = ["artist-image-0001"]+ , oneLine = DisplayLines "First Song - The Example Band" Nothing Nothing+ , twoLine = DisplayLines "First Song" (Just "The Example Band") Nothing+ , threeLine = DisplayLines "First Song" (Just "The Example Band") (Just "Example Album")+ }+ }++livingRoomOutput :: Output+livingRoomOutput =+ Output+ { outputId = OutputId "output-0001"+ , zoneId = ZoneId "zone-0001"+ , displayName = "Living Room"+ , volume = Nothing+ , sourceControls = [SourceControl {controlKey = "1", displayName = "Amplifier", status = Indeterminate, supportsStandby = False}]+ , canGroupWithOutputIds = [OutputId "output-0001"]+ }++firstSong :: QueueItem+firstSong =+ QueueItem+ { queueItemId = 1001+ , length = Just 306+ , imageKey = Just "album-image-0001"+ , oneLine = DisplayLines "First Song - The Example Band" Nothing Nothing+ , twoLine = DisplayLines "First Song" (Just "The Example Band") Nothing+ , threeLine = DisplayLines "First Song" (Just "The Example Band") (Just "Example Album")+ }++secondSong :: QueueItem+secondSong =+ QueueItem+ { queueItemId = 1002+ , length = Just 159+ , imageKey = Just "album-image-0001"+ , oneLine = DisplayLines "Second Song - The Example Band" Nothing Nothing+ , twoLine = DisplayLines "Second Song" (Just "The Example Band") Nothing+ , threeLine = DisplayLines "Second Song" (Just "The Example Band") (Just "Example Album")+ }