code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# htermination elemFM :: (Ord a, Ord k) => (Either a k) -> FiniteMap (Either a k) b -> Bool #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_elemFM_10.hs | mit | 115 | 0 | 3 | 23 | 5 | 3 | 2 | 1 | 0 |
module Test.Smoke.Spec.PathGenerator
( genAbsoluteFilePath,
genRelativeDir,
genRelativeFile,
genRelativeFilePath,
genNamedSegment,
)
where
import qualified Data.List as List
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import qualified System.FilePath as FilePath
import Test.Smoke.Paths
import Test.Smoke.Spec.RootDirectory
data FilePathSegment
= Current
| Parent
| Named String
genRelativeDir :: Range Int -> Gen (RelativePath Dir)
genRelativeDir segmentRange = parseDir <$> genRelativeFilePath segmentRange
genRelativeFile :: Range Int -> Gen (RelativePath File)
genRelativeFile segmentRange = parseFile <$> genRelativeFilePath segmentRange
genAbsoluteFilePath :: Range Int -> Gen FilePath
genAbsoluteFilePath segmentRange =
FilePath.joinDrive rootDirectory <$> genRelativeFilePath segmentRange
genRelativeFilePath :: Range Int -> Gen FilePath
genRelativeFilePath segmentRange = do
segments <-
Gen.filter segmentsAreNotSubtractive $ Gen.list segmentRange genSegment
let joined =
List.intercalate [FilePath.pathSeparator] $ map segmentString segments
return $ dropWhile (== FilePath.pathSeparator) joined
genSegment :: Gen FilePathSegment
genSegment =
Gen.frequency
[ (2, Gen.constant Current),
(1, Gen.constant Parent),
(5, Named <$> genNamedSegment)
]
genNamedSegment :: Gen FilePath
genNamedSegment = do
name <- Gen.string (Range.linear 1 100) Gen.alphaNum
trailingSeparators <-
Gen.string (Range.linear 0 3) $ Gen.constant FilePath.pathSeparator
return $ name <> trailingSeparators
segmentsAreNotSubtractive :: [FilePathSegment] -> Bool
segmentsAreNotSubtractive = (>= 0) . countSegments
countSegment :: FilePathSegment -> Int
countSegment Current = 0
countSegment Parent = -1
countSegment (Named _) = 1
countSegments :: [FilePathSegment] -> Int
countSegments = sum . map countSegment
segmentString :: FilePathSegment -> String
segmentString Current = "."
segmentString Parent = ".."
segmentString (Named value) = value
| SamirTalwar/Smoke | src/test/Test/Smoke/Spec/PathGenerator.hs | mit | 2,065 | 0 | 13 | 319 | 559 | 296 | 263 | 55 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Main
Description : Main module running the GMM
Copyright : (c) Julian Kopka Larsen, 2015
Stability : experimental
-}
module Main (
main
) where
import Control.Monad (forM, unless)
import Data.List (transpose, (\\))
import FileParsing
import GHC.Arr (range)
import Graphics.EasyPlot
import Numeric.LinearAlgebra
-- import Numeric.Statistics.PCA
import System.CPUTime
import System.Exit (exitFailure)
import System.IO (readFile)
import Text.Printf
import System.Random (mkStdGen)
import Debug.Trace
import MCMC
import Partition
import Math
import Distributions (lNormW, dlNormW,lnormalInvWishartSS)
list2Touple (a:b:_) = (a,b)
list2Touple _ = (0,0)
toTouples :: Num a => [[a]] -> [(a,a)]
toTouples = map list2Touple
--to2D = toTouples . toLists
plotClusters :: X -> Partition -> [Graph2D Double Double]
plotClusters x p = map toplot $ range (0,((k p)-1))
where toplot i = Data2D [Title "d"] [] (toTouples $ map toList $ select x p i)
qtr x = trace ("value: " ++ show x) x
data State = State (Partition,[Sstat]) deriving Show
instance Sampleable State X where
condMove x g (State (p,s)) = State (newPar, update)
where newPar = move g p
update = ss' x p s newPar
llikelihood _ (State (_,s)) = sum $ map (\(i,m,v) -> lnormalInvWishartSS i m v) s
llikDiff _ (State (_,s')) (State (_,s))
= f s' - f s
where f s = sum $ map (\(i,m,v) -> lnormalInvWishartSS i m v) s
ss :: X -> Partition -> [Sstat]
ss x part = zip3 csizes scatters means
where csizes = componentSizes part
scatters = map scatterMatrix xs
means = map meanv xs
xs = groups x part
ss' :: X -> Partition -> [Sstat] -> Partition -> [Sstat]
ss' x par s npar = map go $ zip3 (p par) s (p npar)
where go (c1, s, c2)
| c1 == c2 = s
| otherwise = updateSstat x c1 s c2
ssComponent :: X -> [Int] -> Sstat
ssComponent x []= (0, konst 0 (d,d), konst 0 d)
where d = dim $ head x
ssComponent x c = (length c, scatterMatrix xs, meanv xs)
where xs = group x c
updateSstat :: X -> [Int] -> Sstat -> [Int] -> Sstat
updateSstat x c1 s c2 = (s <-> removed) <+> added
where removed = (ssComponent x (c1\\c2))
added = (ssComponent x (c2\\c1))
gmmElement :: X -> Int -> Int -> Int -> Partition
gmmElement x seed k num = p
where State (p,_) = getElement gen x start num
gen = mkStdGen seed
start = State (startP, ss x startP)
startP = naiveFromNk n k
n = length x
time :: IO t -> IO t
time a = do
start <- getCPUTime
v <- a
end <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.3f sec\n" (diff :: Double)
return v
-- Main
main = do
--contents <- readFile "../../Data/AccidentData.csv"
--contents <- readFile "../../Data/2Clusters.csv"
--contents <- readFile "../../Data/synthetic.6clust.csv"
contents <- readFile "../../Data/synth2c2d.csv"
let num_Components = 2
num_Samples = 4000
stdData = p2NormList contents
result = gmmElement stdData 1 num_Components
p a = plot X11 $ plotClusters stdData a
--Plot Data
putStrLn "Starting..."
time $ p (result num_Samples)
putStrLn "Done."
| juliankopkalarsen/FpStats | GMM/src/Main.hs | mit | 3,730 | 0 | 14 | 1,232 | 1,267 | 669 | 598 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_robot_simulator (
version,
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [1,0,0,3] []
bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/bin"
libdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/lib/x86_64-osx-ghc-8.0.2/robot-simulator-1.0.0.3-KwygUXUpzGA9nJtpp5aRKY"
dynlibdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/lib/x86_64-osx-ghc-8.0.2"
datadir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/share/x86_64-osx-ghc-8.0.2/robot-simulator-1.0.0.3"
libexecdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/libexec"
sysconfdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/etc"
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "robot_simulator_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "robot_simulator_libdir") (\_ -> return libdir)
getDynLibDir = catchIO (getEnv "robot_simulator_dynlibdir") (\_ -> return dynlibdir)
getDataDir = catchIO (getEnv "robot_simulator_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "robot_simulator_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "robot_simulator_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| c19/Exercism-Haskell | robot-simulator/.stack-work/dist/x86_64-osx/Cabal-1.24.2.0/build/autogen/Paths_robot_simulator.hs | mit | 2,476 | 0 | 10 | 239 | 410 | 238 | 172 | 33 | 1 |
module Nauva.CSS
( module X
) where
import Nauva.CSS.Helpers as X
import Nauva.CSS.Terms as X
import Nauva.CSS.Typeface as X
import Nauva.CSS.Types as X
| wereHamster/nauva | pkg/hs/nauva-css/src/Nauva/CSS.hs | mit | 169 | 0 | 4 | 39 | 44 | 32 | 12 | 6 | 0 |
module Main where
import qualified Graphics.UI.SDL as SDL
import Reactive.Banana
import Reactive.Banana.Frameworks (actuate)
import Reactive.Banana.SDL
import Hage.Graphics
import Hage.Game.Arkanoid.EventNetwork
main :: IO ()
main = do
sdlES <- getSDLEventSource
gd <- initGraphics
network <- compile $ setupNetwork sdlES gd
actuate network
runCappedSDLPump 60 sdlES
SDL.quit
| Hinidu/Arkanoid | src/Hage/Game/Arkanoid.hs | mit | 403 | 0 | 9 | 72 | 111 | 60 | 51 | 15 | 1 |
{-# LANGUAGE NoImplicitPrelude, PackageImports #-}
module Test where
import "base-compat-batteries" Data.Ratio.Compat
| haskell-compat/base-compat | check/check-hs/Data.Ratio.Compat.check.hs | mit | 118 | 0 | 4 | 11 | 12 | 9 | 3 | 3 | 0 |
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
That line was so long
Phew | ke00n/alabno | backend/linter/testFiles/longLineFile.hs | mit | 156 | 0 | 5 | 6 | 19 | 7 | 12 | -1 | -1 |
-- Converts .lhs (literary Haskell files) to .hs (plain Haskell files)
-- Keeps only the statements which are normally compiled, plus blank lines.
-- To use:
-- ghc --make lhs2hs.hs
-- to get an executable file lhs2hs.
-- Then
-- lhs2hs filename
-- will open filename.lhs and save the converted file in filename.hs
-- by Scot Drysdale on 7/28/07, based on SOE program on p. 241
module Main where
import System.IO
import System.Environment -- to allow getArgs
-- Opens a file, given name and mode
openGivenFile :: String -> IOMode -> IO Handle
openGivenFile name mode
= do handle <- openFile name mode
return handle
main = do args <- getArgs
fromHandle <- openGivenFile (args !! 0 ++ ".lhs") ReadMode
toHandle <- openGivenFile (args !! 0 ++ ".hs") WriteMode
convertFile fromHandle toHandle
hClose fromHandle
hClose toHandle
-- Converts all the lines in a file
convertFile :: Handle -> Handle -> IO ()
convertFile fromHandle toHandle
= do line <- hGetLine fromHandle
case line of
('>' : ' ' : rest) -> hPutStrLn toHandle rest
('>' : rest) -> hPutStrLn toHandle rest
('\n' : rest) -> hPutStrLn toHandle line
('\r' : rest) -> hPutStrLn toHandle line
_ -> return ()
convertFile fromHandle toHandle | AlexMckey/FP101x-ItFP_Haskell | Sources/lhs2hs_.hs | cc0-1.0 | 1,360 | 0 | 12 | 369 | 288 | 143 | 145 | 23 | 5 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Network.SockMock (
Handler
, Application
, HostPreference(..)
, pipeHandler
, logMessage
, remoteAddress
, tcpServer
, tcpServer'
, tlsServer
, tlsServer'
, run
) where
import Control.Monad
import Control.Applicative (Applicative)
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad.Reader.Class (MonadReader)
import Control.Monad.Trans.Reader (ReaderT(runReaderT))
import Control.Exception (finally)
import Control.Lens (makeLenses, view)
import Data.Typeable (Typeable)
import Data.ByteString (ByteString)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T (hPutStrLn)
import System.IO (stderr)
import Pipes
import Pipes.Safe (Base, MonadSafe, runSafeT)
import Pipes.Network.TCP (HostPreference, ServiceName, SockAddr)
import qualified Pipes.Network.TCP as PN
import qualified Pipes.Network.TCP.Safe as PNS
import Network.Simple.TCP.TLS (ServerSettings)
import qualified Pipes.Network.TCP.TLS as PNT
import qualified Pipes.Network.TCP.TLS.Safe as PNTS
data HandlerState = HandlerState { _remoteAddress :: !SockAddr
, _enableLogging :: !Bool
}
deriving (Show, Eq, Typeable)
makeLenses ''HandlerState
newtype Handler r = Handler { runHandler :: ReaderT HandlerState IO r }
deriving (Functor, Applicative, Monad, MonadReader HandlerState, MonadIO)
type Application = Producer ByteString IO () -> Consumer ByteString IO () -> Handler ()
data Server = TCPServer HostPreference ServiceName (Maybe Int) (Maybe Int) Application
| TLSServer ServerSettings HostPreference ServiceName (Maybe Int) (Maybe Int) Application
logMessage :: Text -> Handler ()
logMessage msg = do
verbose <- view enableLogging
when verbose $ do
addr <- view remoteAddress
liftIO $ T.hPutStrLn stderr $ buildMessage addr
where
buildMessage addr = T.concat [ "["
, T.pack $ show addr
, "] "
, msg
]
bufferSize :: Int
bufferSize = 4096
pipeHandler :: Pipe ByteString ByteString IO () -> Application
pipeHandler p = \prod cons -> liftIO $ runEffect $ prod >-> p >-> cons
runApp :: Application
-> SockAddr
-> Bool
-> Producer ByteString IO ()
-> Consumer ByteString IO ()
-> IO ()
runApp app addr verbose prod cons = do
finally
(flip runReaderT state $ runHandler $ do
logMessage "Connected"
app prod cons)
(flip runReaderT state $ runHandler $ logMessage "Disconnected")
where
state = HandlerState { _remoteAddress = addr
, _enableLogging = verbose
}
runTCP :: MonadSafe m
=> HostPreference
-> ServiceName
-> Maybe Int
-> Maybe Int
-> Bool
-> Application
-> m ()
runTCP host service readTimeout sendTimeout verbose app =
PNS.serve host service $ \(sock, addr) -> do
let prod = maybe PN.fromSocket PN.fromSocketTimeout readTimeout sock bufferSize
cons = maybe PN.toSocket PN.toSocketTimeout sendTimeout sock
runApp app addr verbose prod cons
runTLS :: (MonadSafe m, Base m ~ IO)
=> ServerSettings
-> HostPreference
-> ServiceName
-> Maybe Int
-> Maybe Int
-> Bool
-> Application
-> m ()
runTLS config host service readTimeout sendTimeout verbose app =
PNTS.serve config host service $ \(ctx, addr) -> do
let prod = maybe PNT.fromContext PNT.fromContextTimeout readTimeout ctx
cons = maybe PNT.toContext PNT.toContextTimeout sendTimeout ctx
runApp app addr verbose prod cons
tcpServer :: ServiceName -> Application -> Server
tcpServer n = TCPServer PNS.HostAny n Nothing Nothing
tcpServer' :: HostPreference
-> ServiceName
-> Maybe Int
-> Maybe Int
-> Application
-> Server
tcpServer' = TCPServer
tlsServer :: ServerSettings -> ServiceName -> Application -> Server
tlsServer c n = TLSServer c PNS.HostAny n Nothing Nothing
tlsServer' :: ServerSettings
-> HostPreference
-> ServiceName
-> Maybe Int
-> Maybe Int
-> Application
-> Server
tlsServer' = TLSServer
run :: Bool -> [Server] -> IO ()
run verbose servers = do
forM_ servers $ \case
TCPServer h s r w a -> fork (runTCP h s r w verbose a)
TLSServer c h s r w a -> fork (runTLS c h s r w verbose a)
forever $ threadDelay 1000000
where
fork = forkIO . runSafeT
| NicolasT/sockmock | src/Network/SockMock.hs | gpl-2.0 | 4,959 | 0 | 14 | 1,387 | 1,369 | 727 | 642 | 134 | 2 |
-- Orden.hs
-- Implementación de relaciones de orden del capítulo 1
-- Sevilla, 4 de Mayo de 2016
-- ---------------------------------------------------------------------
module Orden where
-- Referencias
-- ===========
-- + "On Multiset Orderings" http://bit.ly/1VXmgZO
-- + "Data.MultiSet Functions" http://bit.ly/1YitFkk
import Data.Ord()
import qualified Data.MultiSet as M
-- Funciones útiles
-- ================
-- | vacio es el multiconjunto vacío. Por ejemplo,
-- >>> vacio
-- fromOccurList []
vacio :: M.MultiSet a
vacio = M.empty
-- | (unitario x) es el multiconjunto cuyo único elemento es x. Por
-- ejemplo,
-- >>> unitario 5
-- fromOccurList [(5,1)]
unitario :: a -> M.MultiSet a
unitario = M.singleton
-- | (inserta x m) es el multiconjunto obtenido añadiendo el elemento x al
-- multiconjunto m. Por ejemplo,
-- λ> inserta 4 (unitario 5)
-- fromOccurList [(4,1),(5,1)]
-- λ> inserta 4 (inserta 4 (unitario 5))
-- fromOccurList [(4,2),(5,1)]
inserta :: Ord a => a -> M.MultiSet a -> M.MultiSet a
inserta = M.insert
-- | (lista2Multiconj xs) es el multiconjunto cuyos elementos son los de la
-- lista xs. Por ejemplo,
-- >>> lista2Multiconj [4,5,4]
-- fromOccurList [(4,2),(5,1)]
lista2Multiconj:: Ord a => [a] -> M.MultiSet a
lista2Multiconj = M.fromList
-- | (ordLex r xs ys) es el orden lexicográfico inducido por r sobre xs
-- e ys. Por ejemplo,
-- >>> ordLex compare [1,2] [1,5]
-- LT
-- >>> ordLex compare [1,2] [1,2]
-- EQ
-- >>> ordLex compare [3,1] [2,4]
-- GT
-- >>> ordLex compare [1] [1,3]
-- LT
-- >>> ordLex compare [1,3] [1]
-- GT
-- >>> let r x y = compare (abs x) (abs y)
-- >>> ordLex compare [-4,3] [2,5]
-- LT
-- >>> ordLex r [-4,3] [2,5]
-- GT
ordLex :: (a -> b -> Ordering) -> [a] -> [b] -> Ordering
ordLex _ [] [] = EQ
ordLex _ [] _ = LT
ordLex _ _ [] = GT
ordLex r (x:xs) (y:ys) =
case a of
EQ -> ordLex r xs ys
_ -> a
where a = r x y
-- | (borraelem a mult) es la lista obtenida eliminando el primer
-- elemento de xs igual a x. Por ejemplo,
-- >>> borraElem 2 (lista2Multiconj [3,2,5,2])
-- fromOccurList [(2,1),(3,1),(5,1)]
-- >>> borraElem 4 (lista2Multiconj [3,2,5,2])
-- fromOccurList [(2,2),(3,1),(5,1)]
borraElem :: Ord a => a -> M.MultiSet a -> M.MultiSet a
borraElem = M.delete
-- | (difMulticonj xs ys) es la diferencia de los multiconjuntos xs e ys
-- Por ejemplo,
-- >>> difMulticonj (lista2Multiconj [1,2,3,2,5]) (lista2Multiconj [2,7,5,7])
-- fromOccurList [(1,1),(2,1),(3,1)]
-- >>> difMulticonj (lista2Multiconj [2,7,5,7]) (lista2Multiconj [1,2,3,2,5])
-- fromOccurList [(7,2)]
difMulticonj :: Ord a => M.MultiSet a -> M.MultiSet a -> M.MultiSet a
difMulticonj = M.difference
-- Dado un orden > en un conjunto A, se define el orden >' sobre el
-- conjunto M(A) de los multiconjuntos de A como sigue:
-- M >' N syss existen X, Y ∈ M(A) tales que se cumplen las
-- siguientes condiciones
-- 1. ∅ ≠ X ⊆ M
-- 2. N = (M - X) ∪ Y
-- 3. (∀y∈Y)(∃x∈X)[x > y]
-- Por ejemplo, {5,3,1,1} >' {4,3,3,1} ya que si X = {5,1} e Y = {4,3}
-- entonces
-- 1. ∅ ≠ {5,1} ⊆ {5,3,1,1}
-- 2. {4,3,3,1} = ({5,3,1,1} - {5,1}) ∪ {4,3}
-- 3. (∀y∈{4,3})(∃x∈{5,1})[x > y]
-- | (ordenMulticonj ms ns) es la comparación de los multiconjuntos ms y ns.
-- Por ejemplo,
-- >>> let ms = lista2Multiconj [5,3,1,1]
-- >>> let ns = lista2Multiconj [4,3,3,1]
-- >>> ordenMulticonj ms ns
-- GT
ordenMulticonj :: Ord a => M.MultiSet a -> M.MultiSet a -> Ordering
ordenMulticonj ms ns
| ms == ns = EQ
| all (\y -> (any (\x -> x > y) xs)) ys = GT
| otherwise = LT
where xs = ms `difMulticonj` ns
ys = ns `difMulticonj` ms
-- Comprobación doctest
-- Examples: 18 Tried: 18 Errors: 0 Failures: 0
| migpornar/SRTenHaskell | Codigo_Haskell/Orden.hs | gpl-3.0 | 3,941 | 0 | 15 | 939 | 545 | 318 | 227 | 31 | 2 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE StandaloneDeriving #-}
module Experiment.Battlefield.Stage
( stageWireOnce
, stageWireLoop
, stageWireOnce'
, stageWireLoop'
) where
-- import Data.Foldable (foldl)
-- import Debug.Trace
-- import Utils.Wire.Debug
import Control.Monad.Fix
import Control.Wire as W
import Control.Wire.Unsafe.Event
import Data.Default
import Data.Map.Strict (Map)
import Data.Maybe (isNothing, catMaybes)
import Data.Traversable (mapAccumL)
import Experiment.Battlefield.Attack
import Experiment.Battlefield.Stats
import Experiment.Battlefield.Team
import Experiment.Battlefield.Types
import FRP.Netwire.Move
import Linear.Metric
import Linear.V3
import Linear.Vector
import Prelude hiding ((.),id,foldl)
import System.Random
import Utils.Helpers
import Utils.Wire.Misc
import Utils.Wire.Wrapped
import qualified Data.Map.Strict as M
type ArticleID = UUID
type SoldierID = UUID
stageWireOnce :: (MonadFix m, Monoid e, HasTime Double s)
=> (Double,Double)
-> TeamFlag
-> TeamFlag
-> StdGen
-> Wire s e m () Stage
stageWireOnce dim t1fl t2fl gen = arr fst . stageWireOnce' def dim t1fl t2fl gen
stageWireLoop :: (MonadFix m, Monoid e, HasTime Double s)
=> (Double,Double)
-> TeamFlag
-> TeamFlag
-> StdGen
-> Wire s e m () Stage
stageWireLoop = stageWireLoop' def
stageWireLoop' :: (MonadFix m, Monoid e, HasTime Double s)
=> StageScore
-> (Double,Double)
-> TeamFlag
-> TeamFlag
-> StdGen
-> Wire s e m () Stage
stageWireLoop' stgC dim t1fl t2fl gen = switch stgW
where
stgW = second (fmap makeStageWire) <$> stageWireOnce' stgC dim t1fl t2fl g1
makeStageWire stgC' = stageWireLoop' stgC' dim t1fl t2fl g2
(g1,g2) = split gen
stageWireOnce' :: (MonadFix m, Monoid e, HasTime Double s)
=> StageScore
-> (Double, Double)
-> TeamFlag
-> TeamFlag
-> StdGen
-> Wire s e m () (Stage, Event StageScore)
stageWireOnce' stgC dim@(w,h) t1fl t2fl gen = proc _ -> do
duration <- integral (stageScoreDuration stgC) -< 1
rec
-- manage teams
(team1@(Team _ t1ss _), t1Outs) <- t1w . delay (teamWireDelayer b0s) -< ((team2,bases), (t1bes, t1InAll))
(team2@(Team _ t2ss _), t2Outs) <- t2w . delay (teamWireDelayer b0s) -< ((team1,bases), (t2bes, t2InAll))
let t1ss' = M.elems t1ss
t2ss' = M.elems t2ss
t1asn = Event $ concatMap makeAttackWire (M.toList t1Outs)
t2asn = Event $ concatMap makeAttackWire (M.toList t2Outs)
-- manage arrows
t1as <- dWireMap NoEvent uuids -< (t1asn,t1aInAll)
t2as <- dWireMap NoEvent uuids -< (t2asn,t2aInAll)
let (t1as',(t2bhits,t1aIns')) = findWallHits t1as (Just t2fl) bases
(t2as',(t1bhits,t2aIns')) = findWallHits t2as (Just t1fl) bases
((t1Ins,t1aIns),t2hIns) = findHits t1as' t2ss
((t2Ins,t2aIns),t1hIns) = findHits t2as' t1ss
arts = map snd (M.elems t1as ++ M.elems t2as)
t1InAll = M.unionWith (<>) t1Ins t1hIns
t2InAll = M.unionWith (<>) t2Ins t2hIns
t1aInAll = M.unionWith (<>) t1aIns' t1aIns
t2aInAll = M.unionWith (<>) t2aIns' t2aIns
(bases,(t1bes,t2bes)) <- basesWire (t1fl,t2fl) b0s . delay (([],[]),repeat NoEvent) -< ((t1ss',t2ss'),zipWith (<>) t2bhits t1bhits)
let sldrs = t1ss' ++ t2ss'
victory <- never . W.when isNothing --> now -< winner bases
let newData = processVictory duration <$> victory
returnA -< (Stage dim (stgC { stageScoreDuration = duration }) sldrs arts bases, newData)
where
makeAttackWire (sId,Event es) = map (\d -> (sId,) <$> attackWire d) atkDatas
where
atkDatas = [ atkData | AttackEvent atkData <- es ]
makeAttackWire _ = []
findWallHits :: Map UUID (UUID, Article) -> Maybe TeamFlag -> [Base] -> (Map UUID (UUID, Article),([Event [Attack]], M.Map UUID (Event ())))
-- -- findWallHits as fl bs = if M.size bAtks > 0 then (M.elemAt 0 bAtks `traceShow` (leftoverArts, evts)) else (leftoverArts, evts)
-- findWallHits as fl bs = if M.size leftoverArts /= M.size atks then traceShow atks (leftoverArts, evts) else (leftoverArts, evts)
findWallHits as bsfl bs = (fst <$> leftoverArts, (evts, (Event () <$) artHits))
where
atks = fmap makeHit as
(artHits, leftoverArts) = M.partition (fst . snd) atks
evts = foldAcrossl (<>) NoEvent (snd . snd <$> atks)
makeHit ua@(_, art) = (ua, mapAccumL f False bs)
where
f :: Bool -> Base -> (Bool, Event [Attack])
f True _ = (True, NoEvent)
f False b
| baseTeamFlag b == bsfl && hittableHit b art = (True, Event [atk])
| otherwise = (False, NoEvent)
where
ArticleAttack atk = articleType art
findHits :: Map UUID (UUID, Article) -> Map UUID Soldier -> ((Map UUID SoldierInEvents,Map UUID (Event ())), Map UUID SoldierInEvents)
findHits as ss = ((sldrKillsEs, artHitEs), sldrHitEs)
where
(sldrKillsElms,sldrHitElms) = unzip (M.elems atks)
sldrHitEs :: Map UUID SoldierInEvents
sldrHitEs = M.unionsWith (<>) sldrHitElms
sldrKillsEs :: Map UUID SoldierInEvents
sldrKillsEs = M.fromList (catMaybes sldrKillsElms)
artHitEs :: M.Map UUID (Event ())
artHitEs = fmap ((() <$) . maybe NoEvent Event . fst) atks
atks :: Map ArticleID (Maybe (SoldierID,SoldierInEvents), Map SoldierID SoldierInEvents)
atks = fmap makeKill as
makeKill :: (SoldierID, Article) -> (Maybe (SoldierID, SoldierInEvents), Map SoldierID SoldierInEvents)
makeKill (sId,art) = M.mapAccum f Nothing ss
where
f :: Maybe (SoldierID, SoldierInEvents) -> Soldier -> (Maybe (SoldierID, SoldierInEvents), SoldierInEvents)
f ht@(Just _) _ = (ht, NoEvent)
f Nothing sldr
| norm (pa ^-^ ps) < hitRadius = (Just (sId, killedEvt), Event [AttackedEvent dmg o])
| otherwise = (Nothing, NoEvent)
where
ps = getPos sldr
pa = getPos art
killedEvt
| soldierFuncsWouldKill (soldierFuncs sldr) atk = Event [GotKillEvent sldr]
| otherwise = NoEvent
ArticleAttack atk@(Attack _ dmg o) = articleType art
(t1gen,t2gen) = split gen
t1w = teamWire b0s $ TeamData t1fl t1gen
t2w = teamWire b0s $ TeamData t2fl t2gen
-- b1s = makeBase t1fl <$> [V3 (w/6) (h/6) 0, V3 (w/6) (5*h/6) 0]
-- b2s = makeBase t2fl <$> [V3 (5*w/6) (h/6) 0, V3 (5*w/6) (5*h/6) 0]
-- bns = []
-- b1s = makeBase (Just t1fl) <$> [V3 (w/6) (h/6) 0, V3 (5*w/6) (5*h/6) 0]
-- b2s = makeBase (Just t2fl) <$> [V3 (5*w/6) (h/6) 0, V3 (w/6) (5*h/6) 0]
-- b1s = makeBase (Just t1fl) <$> [V3 (w/6) (h/6) 0, V3 (5*w/6) (h/6) 0]
-- b2s = makeBase (Just t2fl) <$> [V3 (w/6) (5*h/6) 0, V3 (5*w/6) (5*h/6) 0]
-- bns = makeBase Nothing <$> [V3 (w/2) (h/4) 0, V3 (w/2) (3*h/4) 0, V3 (w/4) (h/2) 0, V3 (3*w/4) (h/2) 0]
-- bns = makeBase Nothing <$> [V3 (5*w/6) (h/6) 0, V3 (w/2) (h/2) 0, V3 (w/6) (5*h/6) 0]
-- bns = makeBase Nothing <$> [V3 (w/3) (h/2) 0, V3 (2*w/3) (h/2) 0]
-- bns = makeBase Nothing <$> [V3 (w/2) (h/2) 0]
b1s = makeBase (Just t1fl) <$> [V3 (w/6) (h/6) 0]
b2s = makeBase (Just t2fl) <$> [V3 (5*w/6) (5*h/6) 0]
-- bns = makeBase Nothing <$> [V3 (w/2) (h/4) 0, V3 (w/2) (3*h/4) 0, V3 (w/4) (h/2) 0, V3 (3*w/4) (h/2) 0, V3 (5*w/6) (h/6) 0, V3 (w/2) (h/2) 0, V3 (w/6) (5*h/6) 0]
bns = makeBase Nothing <$> [ V3 (w/2) (h/4) 0
, V3 (w/2) (3*h/4) 0
, V3 (w/2) (h/2) 0
-- , V3 (w/3) (3*h/8) 0
-- , V3 (w/3) (5*h/8) 0
-- , V3 (2*w/3) (3*h/8) 0
-- , V3 (2*w/3) (5*h/8) 0
, V3 (w/3) (h/3) 0
, V3 (w/3) (2*h/3) 0
, V3 (2*w/3) (h/3) 0
, V3 (2*w/3) (2*h/3) 0
, V3 (5*w/6) (h/6) 0
, V3 (w/6) (5*h/6) 0
]
b0s = b1s ++ bns ++ b2s
makeBase fl pb = Base pb fl 1 Nothing Nothing
-- numBases = length b0s
winner bases | null t1bs = Just t2fl
| null t2bs = Just t1fl
| otherwise = Nothing
where
(t1bs,t2bs) = fst $ partition3 (fmap (== t1fl) . baseTeamFlag) bases
processVictory dur wnr = stgC { stageScoreScores = newScore
, stageScoreGameCount = gameCount + 1
, stageScoreDuration = dur
}
where
newScore = case wnr of
Just fl | fl == t1fl -> (first (+1)) scores
| fl == t2fl -> (second (+1)) scores
_ -> scores
(StageScore scores gameCount _) = stgC
basesWire :: (MonadFix m, Monoid e, HasTime Double s)
=> (TeamFlag, TeamFlag)
-> [Base]
-> Wire s e m (([Soldier],[Soldier]),[Event [Attack]]) ([Base],([BaseEvents],[BaseEvents]))
basesWire fls@(t1fl,_t2fl) b0s = proc (inp,atks) -> do
bEvts <- zipWires (map (baseWire fls) b0s) -< zip (repeat inp) atks
let
(bases,swaps) = unzip bEvts
evts = foldr sortEvts ([],[]) swaps
returnA -< (bases,evts)
where
sortEvts swaps (t1bes,t2bes) =
case swaps of
Event j@(Just fl) | fl == t1fl -> ( Event [GetBase] : t1bes, Event [LoseBase j] : t2bes )
| otherwise -> ( Event [LoseBase j] : t1bes, Event [GetBase] : t2bes )
Event _ -> ( Event [LoseBase Nothing] : t1bes, Event [LoseBase Nothing] : t2bes )
NoEvent -> ( NoEvent : t1bes, NoEvent : t2bes )
baseWire :: forall m e s. (MonadFix m, Monoid e, HasTime Double s)
=> (TeamFlag, TeamFlag)
-> Base
-> Wire s e m (([Soldier],[Soldier]), Event [Attack]) (Base,Event (Maybe TeamFlag))
baseWire (t1fl,t2fl) b0@(Base pb fl0 _ _ _) = proc ((t1s,t2s),atks) -> do
let
t1b = length $ filter inBase t1s
t2b = length $ filter inBase t2s
influence | t1b > t2b = Just t1fl
| t1b < t2b = Just t2fl
| otherwise = Nothing
rec
let newWire = ntBase <$> teamChange
(((security, leaning),wall), teamChange) <- drSwitch (ntBase fl0) -< ((influence, atks), newWire)
owner <- hold <|> pure fl0 -< teamChange
let newBase = b0 { baseTeamFlag = owner
, baseSecurity = security
, baseLeaning = leaning
, baseWall = wall
}
returnA -< (newBase, teamChange)
where
inBase = (< baseRadius) . norm . (^-^ pb) . getPos
ntBase :: Maybe TeamFlag -> Wire s e m (Maybe TeamFlag, Event [Attack]) (((Double, Maybe TeamFlag), Maybe Double), Event (Maybe TeamFlag))
ntBase = maybe neutralBase teamBase
neutralBase :: Wire s e m (Maybe TeamFlag, Event [Attack]) (((Double, Maybe TeamFlag), Maybe Double), Event (Maybe TeamFlag))
neutralBase = proc (infl,_) -> do
rec
let push =
case infl of
Just fl | fl == t1fl -> 1
| otherwise -> -1
Nothing -> -0.25 * signum sec
sec <- integral 0 -< push
let leaning | sec > 0 = Just t1fl
| sec < 0 = Just t2fl
| otherwise = Nothing
swap <- never . W.when ((< baseThreshold) . abs) --> now -< sec
returnA -< (((1 - (abs sec / baseThreshold),leaning), Nothing),leaning <$ swap)
wallMax = 1000
wallRates = [5,10,20,40,80]
teamBase :: TeamFlag -> Wire s e m (Maybe TeamFlag, Event [Attack]) (((Double, Maybe TeamFlag), Maybe Double), Event (Maybe TeamFlag))
teamBase fl = proc (infl,atks) -> do
rec
let push =
case infl of
Just fl' | fl' == fl -> 1
| otherwise -> -1
Nothing -> 0.1
sec <- integralWith (\_ s' -> (min s' baseThreshold)) baseThreshold -< (push,())
swap <- never . W.when (> 0) --> now -< sec
let
damageEvent = sum . map attackDamage <$> atks
wallHealth <- dSwitch wallPreparing -< damageEvent
returnA -< (((sec / baseThreshold,Nothing), wallHealth),Nothing <$ swap)
-- returnA -< atks `traceEvent'` (((sec / baseThreshold,Nothing), wallStrength),Nothing <$ swap)
where
wallPreparing :: Wire s e m (Event Double) (Maybe Double, Event (Wire s e m (Event Double) (Maybe Double)))
wallPreparing = proc _ -> do
survived <- W.at 10 -< dSwitch wallBuilding
returnA -< (Nothing, survived)
wallBuilding :: Wire s e m (Event Double) (Maybe Double, Event (Wire s e m (Event Double) (Maybe Double)))
wallBuilding = proc atk -> do
buildingRate <- hold . periodicList 20 wallRates -< ()
damaged <- hold . accumE (+) 0 <|> pure 0 -< atk
building <- integralWith (\d b -> min b d) 0 -< (buildingRate, wallMax + damaged)
let wallHealth = building - damaged
crumbled <- never . W.unless (< 0) --> now -< wallHealth
let nextPhase = dSwitch wallPreparing <$ crumbled
returnA -< (Just (wallHealth / wallMax), nextPhase)
| mstksg/netwire-experiments | src/Experiment/Battlefield/Stage.hs | gpl-3.0 | 13,703 | 7 | 21 | 4,357 | 4,648 | 2,451 | 2,197 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.BigtableAdmin.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.BigtableAdmin.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Immutable. The type of storage used by this cluster to serve its parent
-- instance\'s tables, unless explicitly overridden.
data ClusterDefaultStorageType
= StorageTypeUnspecified
-- ^ @STORAGE_TYPE_UNSPECIFIED@
-- The user did not specify a storage type.
| Ssd
-- ^ @SSD@
-- Flash (SSD) storage should be used.
| Hdd
-- ^ @HDD@
-- Magnetic drive (HDD) storage should be used.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ClusterDefaultStorageType
instance FromHttpApiData ClusterDefaultStorageType where
parseQueryParam = \case
"STORAGE_TYPE_UNSPECIFIED" -> Right StorageTypeUnspecified
"SSD" -> Right Ssd
"HDD" -> Right Hdd
x -> Left ("Unable to parse ClusterDefaultStorageType from: " <> x)
instance ToHttpApiData ClusterDefaultStorageType where
toQueryParam = \case
StorageTypeUnspecified -> "STORAGE_TYPE_UNSPECIFIED"
Ssd -> "SSD"
Hdd -> "HDD"
instance FromJSON ClusterDefaultStorageType where
parseJSON = parseJSONText "ClusterDefaultStorageType"
instance ToJSON ClusterDefaultStorageType where
toJSON = toJSONText
-- | The type of the restore source.
data RestoreInfoSourceType
= RISTRestoreSourceTypeUnspecified
-- ^ @RESTORE_SOURCE_TYPE_UNSPECIFIED@
-- No restore associated.
| RISTBackup
-- ^ @BACKUP@
-- A backup was used as the source of the restore.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RestoreInfoSourceType
instance FromHttpApiData RestoreInfoSourceType where
parseQueryParam = \case
"RESTORE_SOURCE_TYPE_UNSPECIFIED" -> Right RISTRestoreSourceTypeUnspecified
"BACKUP" -> Right RISTBackup
x -> Left ("Unable to parse RestoreInfoSourceType from: " <> x)
instance ToHttpApiData RestoreInfoSourceType where
toQueryParam = \case
RISTRestoreSourceTypeUnspecified -> "RESTORE_SOURCE_TYPE_UNSPECIFIED"
RISTBackup -> "BACKUP"
instance FromJSON RestoreInfoSourceType where
parseJSON = parseJSONText "RestoreInfoSourceType"
instance ToJSON RestoreInfoSourceType where
toJSON = toJSONText
-- | The view to be applied to the returned tables\' fields. Only NAME_ONLY
-- view (default) and REPLICATION_VIEW are supported.
data ProjectsInstancesTablesListView
= ViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Uses the default view for each method as documented in its request.
| NameOnly
-- ^ @NAME_ONLY@
-- Only populates \`name\`.
| SchemaView
-- ^ @SCHEMA_VIEW@
-- Only populates \`name\` and fields related to the table\'s schema.
| ReplicationView
-- ^ @REPLICATION_VIEW@
-- Only populates \`name\` and fields related to the table\'s replication
-- state.
| EncryptionView
-- ^ @ENCRYPTION_VIEW@
-- Only populates \`name\` and fields related to the table\'s encryption
-- state.
| Full
-- ^ @FULL@
-- Populates all fields.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsInstancesTablesListView
instance FromHttpApiData ProjectsInstancesTablesListView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right ViewUnspecified
"NAME_ONLY" -> Right NameOnly
"SCHEMA_VIEW" -> Right SchemaView
"REPLICATION_VIEW" -> Right ReplicationView
"ENCRYPTION_VIEW" -> Right EncryptionView
"FULL" -> Right Full
x -> Left ("Unable to parse ProjectsInstancesTablesListView from: " <> x)
instance ToHttpApiData ProjectsInstancesTablesListView where
toQueryParam = \case
ViewUnspecified -> "VIEW_UNSPECIFIED"
NameOnly -> "NAME_ONLY"
SchemaView -> "SCHEMA_VIEW"
ReplicationView -> "REPLICATION_VIEW"
EncryptionView -> "ENCRYPTION_VIEW"
Full -> "FULL"
instance FromJSON ProjectsInstancesTablesListView where
parseJSON = parseJSONText "ProjectsInstancesTablesListView"
instance ToJSON ProjectsInstancesTablesListView where
toJSON = toJSONText
-- | Output only. The type of encryption used to protect this resource.
data EncryptionInfoEncryptionType
= EncryptionTypeUnspecified
-- ^ @ENCRYPTION_TYPE_UNSPECIFIED@
-- Encryption type was not specified, though data at rest remains
-- encrypted.
| GoogleDefaultEncryption
-- ^ @GOOGLE_DEFAULT_ENCRYPTION@
-- The data backing this resource is encrypted at rest with a key that is
-- fully managed by Google. No key version or status will be populated.
-- This is the default state.
| CustomerManagedEncryption
-- ^ @CUSTOMER_MANAGED_ENCRYPTION@
-- The data backing this resource is encrypted at rest with a key that is
-- managed by the customer. The in-use version of the key and its status
-- are populated for CMEK-protected tables. CMEK-protected backups are
-- pinned to the key version that was in use at the time the backup was
-- taken. This key version is populated but its status is not tracked and
-- is reported as \`UNKNOWN\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable EncryptionInfoEncryptionType
instance FromHttpApiData EncryptionInfoEncryptionType where
parseQueryParam = \case
"ENCRYPTION_TYPE_UNSPECIFIED" -> Right EncryptionTypeUnspecified
"GOOGLE_DEFAULT_ENCRYPTION" -> Right GoogleDefaultEncryption
"CUSTOMER_MANAGED_ENCRYPTION" -> Right CustomerManagedEncryption
x -> Left ("Unable to parse EncryptionInfoEncryptionType from: " <> x)
instance ToHttpApiData EncryptionInfoEncryptionType where
toQueryParam = \case
EncryptionTypeUnspecified -> "ENCRYPTION_TYPE_UNSPECIFIED"
GoogleDefaultEncryption -> "GOOGLE_DEFAULT_ENCRYPTION"
CustomerManagedEncryption -> "CUSTOMER_MANAGED_ENCRYPTION"
instance FromJSON EncryptionInfoEncryptionType where
parseJSON = parseJSONText "EncryptionInfoEncryptionType"
instance ToJSON EncryptionInfoEncryptionType where
toJSON = toJSONText
-- | The type of the restore source.
data RestoreTableMetadataSourceType
= RTMSTRestoreSourceTypeUnspecified
-- ^ @RESTORE_SOURCE_TYPE_UNSPECIFIED@
-- No restore associated.
| RTMSTBackup
-- ^ @BACKUP@
-- A backup was used as the source of the restore.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RestoreTableMetadataSourceType
instance FromHttpApiData RestoreTableMetadataSourceType where
parseQueryParam = \case
"RESTORE_SOURCE_TYPE_UNSPECIFIED" -> Right RTMSTRestoreSourceTypeUnspecified
"BACKUP" -> Right RTMSTBackup
x -> Left ("Unable to parse RestoreTableMetadataSourceType from: " <> x)
instance ToHttpApiData RestoreTableMetadataSourceType where
toQueryParam = \case
RTMSTRestoreSourceTypeUnspecified -> "RESTORE_SOURCE_TYPE_UNSPECIFIED"
RTMSTBackup -> "BACKUP"
instance FromJSON RestoreTableMetadataSourceType where
parseJSON = parseJSONText "RestoreTableMetadataSourceType"
instance ToJSON RestoreTableMetadataSourceType where
toJSON = toJSONText
-- | Output only. The state of replication for the table in this cluster.
data ClusterStateReplicationState
= StateNotKnown
-- ^ @STATE_NOT_KNOWN@
-- The replication state of the table is unknown in this cluster.
| Initializing
-- ^ @INITIALIZING@
-- The cluster was recently created, and the table must finish copying over
-- pre-existing data from other clusters before it can begin receiving live
-- replication updates and serving Data API requests.
| PlannedMaintenance
-- ^ @PLANNED_MAINTENANCE@
-- The table is temporarily unable to serve Data API requests from this
-- cluster due to planned internal maintenance.
| UnplannedMaintenance
-- ^ @UNPLANNED_MAINTENANCE@
-- The table is temporarily unable to serve Data API requests from this
-- cluster due to unplanned or emergency maintenance.
| Ready
-- ^ @READY@
-- The table can serve Data API requests from this cluster. Depending on
-- replication delay, reads may not immediately reflect the state of the
-- table in other clusters.
| ReadyOptimizing
-- ^ @READY_OPTIMIZING@
-- The table is fully created and ready for use after a restore, and is
-- being optimized for performance. When optimizations are complete, the
-- table will transition to \`READY\` state.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ClusterStateReplicationState
instance FromHttpApiData ClusterStateReplicationState where
parseQueryParam = \case
"STATE_NOT_KNOWN" -> Right StateNotKnown
"INITIALIZING" -> Right Initializing
"PLANNED_MAINTENANCE" -> Right PlannedMaintenance
"UNPLANNED_MAINTENANCE" -> Right UnplannedMaintenance
"READY" -> Right Ready
"READY_OPTIMIZING" -> Right ReadyOptimizing
x -> Left ("Unable to parse ClusterStateReplicationState from: " <> x)
instance ToHttpApiData ClusterStateReplicationState where
toQueryParam = \case
StateNotKnown -> "STATE_NOT_KNOWN"
Initializing -> "INITIALIZING"
PlannedMaintenance -> "PLANNED_MAINTENANCE"
UnplannedMaintenance -> "UNPLANNED_MAINTENANCE"
Ready -> "READY"
ReadyOptimizing -> "READY_OPTIMIZING"
instance FromJSON ClusterStateReplicationState where
parseJSON = parseJSONText "ClusterStateReplicationState"
instance ToJSON ClusterStateReplicationState where
toJSON = toJSONText
-- | Required. The type of the instance. Defaults to \`PRODUCTION\`.
data InstanceType
= TypeUnspecified
-- ^ @TYPE_UNSPECIFIED@
-- The type of the instance is unspecified. If set when creating an
-- instance, a \`PRODUCTION\` instance will be created. If set when
-- updating an instance, the type will be left unchanged.
| Production
-- ^ @PRODUCTION@
-- An instance meant for production use. \`serve_nodes\` must be set on the
-- cluster.
| Development
-- ^ @DEVELOPMENT@
-- DEPRECATED: Prefer PRODUCTION for all use cases, as it no longer
-- enforces a higher minimum node count than DEVELOPMENT.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceType
instance FromHttpApiData InstanceType where
parseQueryParam = \case
"TYPE_UNSPECIFIED" -> Right TypeUnspecified
"PRODUCTION" -> Right Production
"DEVELOPMENT" -> Right Development
x -> Left ("Unable to parse InstanceType from: " <> x)
instance ToHttpApiData InstanceType where
toQueryParam = \case
TypeUnspecified -> "TYPE_UNSPECIFIED"
Production -> "PRODUCTION"
Development -> "DEVELOPMENT"
instance FromJSON InstanceType where
parseJSON = parseJSONText "InstanceType"
instance ToJSON InstanceType where
toJSON = toJSONText
data TableProgressState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
| Pending
-- ^ @PENDING@
-- The table has not yet begun copying to the new cluster.
| Copying
-- ^ @COPYING@
-- The table is actively being copied to the new cluster.
| Completed
-- ^ @COMPLETED@
-- The table has been fully copied to the new cluster.
| Cancelled
-- ^ @CANCELLED@
-- The table was deleted before it finished copying to the new cluster.
-- Note that tables deleted after completion will stay marked as COMPLETED,
-- not CANCELLED.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TableProgressState
instance FromHttpApiData TableProgressState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"PENDING" -> Right Pending
"COPYING" -> Right Copying
"COMPLETED" -> Right Completed
"CANCELLED" -> Right Cancelled
x -> Left ("Unable to parse TableProgressState from: " <> x)
instance ToHttpApiData TableProgressState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
Pending -> "PENDING"
Copying -> "COPYING"
Completed -> "COMPLETED"
Cancelled -> "CANCELLED"
instance FromJSON TableProgressState where
parseJSON = parseJSONText "TableProgressState"
instance ToJSON TableProgressState where
toJSON = toJSONText
-- | The log type that this config enables.
data AuditLogConfigLogType
= LogTypeUnspecified
-- ^ @LOG_TYPE_UNSPECIFIED@
-- Default case. Should never be this.
| AdminRead
-- ^ @ADMIN_READ@
-- Admin reads. Example: CloudIAM getIamPolicy
| DataWrite
-- ^ @DATA_WRITE@
-- Data writes. Example: CloudSQL Users create
| DataRead
-- ^ @DATA_READ@
-- Data reads. Example: CloudSQL Users list
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AuditLogConfigLogType
instance FromHttpApiData AuditLogConfigLogType where
parseQueryParam = \case
"LOG_TYPE_UNSPECIFIED" -> Right LogTypeUnspecified
"ADMIN_READ" -> Right AdminRead
"DATA_WRITE" -> Right DataWrite
"DATA_READ" -> Right DataRead
x -> Left ("Unable to parse AuditLogConfigLogType from: " <> x)
instance ToHttpApiData AuditLogConfigLogType where
toQueryParam = \case
LogTypeUnspecified -> "LOG_TYPE_UNSPECIFIED"
AdminRead -> "ADMIN_READ"
DataWrite -> "DATA_WRITE"
DataRead -> "DATA_READ"
instance FromJSON AuditLogConfigLogType where
parseJSON = parseJSONText "AuditLogConfigLogType"
instance ToJSON AuditLogConfigLogType where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | Immutable. The granularity (i.e. \`MILLIS\`) at which timestamps are
-- stored in this table. Timestamps not matching the granularity will be
-- rejected. If unspecified at creation time, the value will be set to
-- \`MILLIS\`. Views: \`SCHEMA_VIEW\`, \`FULL\`.
data TableGranularity
= TimestampGranularityUnspecified
-- ^ @TIMESTAMP_GRANULARITY_UNSPECIFIED@
-- The user did not specify a granularity. Should not be returned. When
-- specified during table creation, MILLIS will be used.
| Millis
-- ^ @MILLIS@
-- The table keeps data versioned at a granularity of 1ms.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TableGranularity
instance FromHttpApiData TableGranularity where
parseQueryParam = \case
"TIMESTAMP_GRANULARITY_UNSPECIFIED" -> Right TimestampGranularityUnspecified
"MILLIS" -> Right Millis
x -> Left ("Unable to parse TableGranularity from: " <> x)
instance ToHttpApiData TableGranularity where
toQueryParam = \case
TimestampGranularityUnspecified -> "TIMESTAMP_GRANULARITY_UNSPECIFIED"
Millis -> "MILLIS"
instance FromJSON TableGranularity where
parseJSON = parseJSONText "TableGranularity"
instance ToJSON TableGranularity where
toJSON = toJSONText
-- | Output only. The current state of the cluster.
data ClusterType
= CTStateNotKnown
-- ^ @STATE_NOT_KNOWN@
-- The state of the cluster could not be determined.
| CTReady
-- ^ @READY@
-- The cluster has been successfully created and is ready to serve
-- requests.
| CTCreating
-- ^ @CREATING@
-- The cluster is currently being created, and may be destroyed if the
-- creation process encounters an error. A cluster may not be able to serve
-- requests while being created.
| CTResizing
-- ^ @RESIZING@
-- The cluster is currently being resized, and may revert to its previous
-- node count if the process encounters an error. A cluster is still
-- capable of serving requests while being resized, but may exhibit
-- performance as if its number of allocated nodes is between the starting
-- and requested states.
| CTDisabled
-- ^ @DISABLED@
-- The cluster has no backing nodes. The data (tables) still exist, but no
-- operations can be performed on the cluster.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ClusterType
instance FromHttpApiData ClusterType where
parseQueryParam = \case
"STATE_NOT_KNOWN" -> Right CTStateNotKnown
"READY" -> Right CTReady
"CREATING" -> Right CTCreating
"RESIZING" -> Right CTResizing
"DISABLED" -> Right CTDisabled
x -> Left ("Unable to parse ClusterType from: " <> x)
instance ToHttpApiData ClusterType where
toQueryParam = \case
CTStateNotKnown -> "STATE_NOT_KNOWN"
CTReady -> "READY"
CTCreating -> "CREATING"
CTResizing -> "RESIZING"
CTDisabled -> "DISABLED"
instance FromJSON ClusterType where
parseJSON = parseJSONText "ClusterType"
instance ToJSON ClusterType where
toJSON = toJSONText
-- | The view to be applied to the returned table\'s fields. Defaults to
-- \`SCHEMA_VIEW\` if unspecified.
data ProjectsInstancesTablesGetView
= PITGVViewUnspecified
-- ^ @VIEW_UNSPECIFIED@
-- Uses the default view for each method as documented in its request.
| PITGVNameOnly
-- ^ @NAME_ONLY@
-- Only populates \`name\`.
| PITGVSchemaView
-- ^ @SCHEMA_VIEW@
-- Only populates \`name\` and fields related to the table\'s schema.
| PITGVReplicationView
-- ^ @REPLICATION_VIEW@
-- Only populates \`name\` and fields related to the table\'s replication
-- state.
| PITGVEncryptionView
-- ^ @ENCRYPTION_VIEW@
-- Only populates \`name\` and fields related to the table\'s encryption
-- state.
| PITGVFull
-- ^ @FULL@
-- Populates all fields.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsInstancesTablesGetView
instance FromHttpApiData ProjectsInstancesTablesGetView where
parseQueryParam = \case
"VIEW_UNSPECIFIED" -> Right PITGVViewUnspecified
"NAME_ONLY" -> Right PITGVNameOnly
"SCHEMA_VIEW" -> Right PITGVSchemaView
"REPLICATION_VIEW" -> Right PITGVReplicationView
"ENCRYPTION_VIEW" -> Right PITGVEncryptionView
"FULL" -> Right PITGVFull
x -> Left ("Unable to parse ProjectsInstancesTablesGetView from: " <> x)
instance ToHttpApiData ProjectsInstancesTablesGetView where
toQueryParam = \case
PITGVViewUnspecified -> "VIEW_UNSPECIFIED"
PITGVNameOnly -> "NAME_ONLY"
PITGVSchemaView -> "SCHEMA_VIEW"
PITGVReplicationView -> "REPLICATION_VIEW"
PITGVEncryptionView -> "ENCRYPTION_VIEW"
PITGVFull -> "FULL"
instance FromJSON ProjectsInstancesTablesGetView where
parseJSON = parseJSONText "ProjectsInstancesTablesGetView"
instance ToJSON ProjectsInstancesTablesGetView where
toJSON = toJSONText
-- | Output only. The current state of the instance.
data InstanceState
= ISStateNotKnown
-- ^ @STATE_NOT_KNOWN@
-- The state of the instance could not be determined.
| ISReady
-- ^ @READY@
-- The instance has been successfully created and can serve requests to its
-- tables.
| ISCreating
-- ^ @CREATING@
-- The instance is currently being created, and may be destroyed if the
-- creation process encounters an error.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstanceState
instance FromHttpApiData InstanceState where
parseQueryParam = \case
"STATE_NOT_KNOWN" -> Right ISStateNotKnown
"READY" -> Right ISReady
"CREATING" -> Right ISCreating
x -> Left ("Unable to parse InstanceState from: " <> x)
instance ToHttpApiData InstanceState where
toQueryParam = \case
ISStateNotKnown -> "STATE_NOT_KNOWN"
ISReady -> "READY"
ISCreating -> "CREATING"
instance FromJSON InstanceState where
parseJSON = parseJSONText "InstanceState"
instance ToJSON InstanceState where
toJSON = toJSONText
-- | Output only. The current state of the backup.
data BackupState
= BSStateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Not specified.
| BSCreating
-- ^ @CREATING@
-- The pending backup is still being created. Operations on the backup may
-- fail with \`FAILED_PRECONDITION\` in this state.
| BSReady
-- ^ @READY@
-- The backup is complete and ready for use.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BackupState
instance FromHttpApiData BackupState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right BSStateUnspecified
"CREATING" -> Right BSCreating
"READY" -> Right BSReady
x -> Left ("Unable to parse BackupState from: " <> x)
instance ToHttpApiData BackupState where
toQueryParam = \case
BSStateUnspecified -> "STATE_UNSPECIFIED"
BSCreating -> "CREATING"
BSReady -> "READY"
instance FromJSON BackupState where
parseJSON = parseJSONText "BackupState"
instance ToJSON BackupState where
toJSON = toJSONText
| brendanhay/gogol | gogol-bigtableadmin/gen/Network/Google/BigtableAdmin/Types/Sum.hs | mpl-2.0 | 22,510 | 0 | 11 | 5,138 | 3,007 | 1,621 | 1,386 | 353 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.YouTube.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.YouTube.Types.Product where
import Network.Google.Prelude
import Network.Google.YouTube.Types.Sum
--
-- /See:/ 'liveChatMessageAuthorDetails' smart constructor.
data LiveChatMessageAuthorDetails =
LiveChatMessageAuthorDetails'
{ _lcmadIsVerified :: !(Maybe Bool)
, _lcmadIsChatOwner :: !(Maybe Bool)
, _lcmadChannelId :: !(Maybe Text)
, _lcmadProFileImageURL :: !(Maybe Text)
, _lcmadIsChatModerator :: !(Maybe Bool)
, _lcmadDisplayName :: !(Maybe Text)
, _lcmadIsChatSponsor :: !(Maybe Bool)
, _lcmadChannelURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatMessageAuthorDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcmadIsVerified'
--
-- * 'lcmadIsChatOwner'
--
-- * 'lcmadChannelId'
--
-- * 'lcmadProFileImageURL'
--
-- * 'lcmadIsChatModerator'
--
-- * 'lcmadDisplayName'
--
-- * 'lcmadIsChatSponsor'
--
-- * 'lcmadChannelURL'
liveChatMessageAuthorDetails
:: LiveChatMessageAuthorDetails
liveChatMessageAuthorDetails =
LiveChatMessageAuthorDetails'
{ _lcmadIsVerified = Nothing
, _lcmadIsChatOwner = Nothing
, _lcmadChannelId = Nothing
, _lcmadProFileImageURL = Nothing
, _lcmadIsChatModerator = Nothing
, _lcmadDisplayName = Nothing
, _lcmadIsChatSponsor = Nothing
, _lcmadChannelURL = Nothing
}
-- | Whether the author\'s identity has been verified by YouTube.
lcmadIsVerified :: Lens' LiveChatMessageAuthorDetails (Maybe Bool)
lcmadIsVerified
= lens _lcmadIsVerified
(\ s a -> s{_lcmadIsVerified = a})
-- | Whether the author is the owner of the live chat.
lcmadIsChatOwner :: Lens' LiveChatMessageAuthorDetails (Maybe Bool)
lcmadIsChatOwner
= lens _lcmadIsChatOwner
(\ s a -> s{_lcmadIsChatOwner = a})
-- | The YouTube channel ID.
lcmadChannelId :: Lens' LiveChatMessageAuthorDetails (Maybe Text)
lcmadChannelId
= lens _lcmadChannelId
(\ s a -> s{_lcmadChannelId = a})
-- | The channels\'s avatar URL.
lcmadProFileImageURL :: Lens' LiveChatMessageAuthorDetails (Maybe Text)
lcmadProFileImageURL
= lens _lcmadProFileImageURL
(\ s a -> s{_lcmadProFileImageURL = a})
-- | Whether the author is a moderator of the live chat.
lcmadIsChatModerator :: Lens' LiveChatMessageAuthorDetails (Maybe Bool)
lcmadIsChatModerator
= lens _lcmadIsChatModerator
(\ s a -> s{_lcmadIsChatModerator = a})
-- | The channel\'s display name.
lcmadDisplayName :: Lens' LiveChatMessageAuthorDetails (Maybe Text)
lcmadDisplayName
= lens _lcmadDisplayName
(\ s a -> s{_lcmadDisplayName = a})
-- | Whether the author is a sponsor of the live chat.
lcmadIsChatSponsor :: Lens' LiveChatMessageAuthorDetails (Maybe Bool)
lcmadIsChatSponsor
= lens _lcmadIsChatSponsor
(\ s a -> s{_lcmadIsChatSponsor = a})
-- | The channel\'s URL.
lcmadChannelURL :: Lens' LiveChatMessageAuthorDetails (Maybe Text)
lcmadChannelURL
= lens _lcmadChannelURL
(\ s a -> s{_lcmadChannelURL = a})
instance FromJSON LiveChatMessageAuthorDetails where
parseJSON
= withObject "LiveChatMessageAuthorDetails"
(\ o ->
LiveChatMessageAuthorDetails' <$>
(o .:? "isVerified") <*> (o .:? "isChatOwner") <*>
(o .:? "channelId")
<*> (o .:? "profileImageUrl")
<*> (o .:? "isChatModerator")
<*> (o .:? "displayName")
<*> (o .:? "isChatSponsor")
<*> (o .:? "channelUrl"))
instance ToJSON LiveChatMessageAuthorDetails where
toJSON LiveChatMessageAuthorDetails'{..}
= object
(catMaybes
[("isVerified" .=) <$> _lcmadIsVerified,
("isChatOwner" .=) <$> _lcmadIsChatOwner,
("channelId" .=) <$> _lcmadChannelId,
("profileImageUrl" .=) <$> _lcmadProFileImageURL,
("isChatModerator" .=) <$> _lcmadIsChatModerator,
("displayName" .=) <$> _lcmadDisplayName,
("isChatSponsor" .=) <$> _lcmadIsChatSponsor,
("channelUrl" .=) <$> _lcmadChannelURL])
-- | Basic details about a subscription\'s subscriber including title,
-- description, channel ID and thumbnails.
--
-- /See:/ 'subscriptionSubscriberSnippet' smart constructor.
data SubscriptionSubscriberSnippet =
SubscriptionSubscriberSnippet'
{ _sssChannelId :: !(Maybe Text)
, _sssThumbnails :: !(Maybe ThumbnailDetails)
, _sssTitle :: !(Maybe Text)
, _sssDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SubscriptionSubscriberSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sssChannelId'
--
-- * 'sssThumbnails'
--
-- * 'sssTitle'
--
-- * 'sssDescription'
subscriptionSubscriberSnippet
:: SubscriptionSubscriberSnippet
subscriptionSubscriberSnippet =
SubscriptionSubscriberSnippet'
{ _sssChannelId = Nothing
, _sssThumbnails = Nothing
, _sssTitle = Nothing
, _sssDescription = Nothing
}
-- | The channel ID of the subscriber.
sssChannelId :: Lens' SubscriptionSubscriberSnippet (Maybe Text)
sssChannelId
= lens _sssChannelId (\ s a -> s{_sssChannelId = a})
-- | Thumbnails for this subscriber.
sssThumbnails :: Lens' SubscriptionSubscriberSnippet (Maybe ThumbnailDetails)
sssThumbnails
= lens _sssThumbnails
(\ s a -> s{_sssThumbnails = a})
-- | The title of the subscriber.
sssTitle :: Lens' SubscriptionSubscriberSnippet (Maybe Text)
sssTitle = lens _sssTitle (\ s a -> s{_sssTitle = a})
-- | The description of the subscriber.
sssDescription :: Lens' SubscriptionSubscriberSnippet (Maybe Text)
sssDescription
= lens _sssDescription
(\ s a -> s{_sssDescription = a})
instance FromJSON SubscriptionSubscriberSnippet where
parseJSON
= withObject "SubscriptionSubscriberSnippet"
(\ o ->
SubscriptionSubscriberSnippet' <$>
(o .:? "channelId") <*> (o .:? "thumbnails") <*>
(o .:? "title")
<*> (o .:? "description"))
instance ToJSON SubscriptionSubscriberSnippet where
toJSON SubscriptionSubscriberSnippet'{..}
= object
(catMaybes
[("channelId" .=) <$> _sssChannelId,
("thumbnails" .=) <$> _sssThumbnails,
("title" .=) <$> _sssTitle,
("description" .=) <$> _sssDescription])
-- | Describes information necessary for ingesting an RTMP or an HTTP stream.
--
-- /See:/ 'ingestionInfo' smart constructor.
data IngestionInfo =
IngestionInfo'
{ _iiRtmpsIngestionAddress :: !(Maybe Text)
, _iiBackupIngestionAddress :: !(Maybe Text)
, _iiIngestionAddress :: !(Maybe Text)
, _iiRtmpsBackupIngestionAddress :: !(Maybe Text)
, _iiStreamName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'IngestionInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iiRtmpsIngestionAddress'
--
-- * 'iiBackupIngestionAddress'
--
-- * 'iiIngestionAddress'
--
-- * 'iiRtmpsBackupIngestionAddress'
--
-- * 'iiStreamName'
ingestionInfo
:: IngestionInfo
ingestionInfo =
IngestionInfo'
{ _iiRtmpsIngestionAddress = Nothing
, _iiBackupIngestionAddress = Nothing
, _iiIngestionAddress = Nothing
, _iiRtmpsBackupIngestionAddress = Nothing
, _iiStreamName = Nothing
}
-- | This ingestion url may be used instead of ingestionAddress in order to
-- stream via RTMPS. Not applicable to non-RTMP streams.
iiRtmpsIngestionAddress :: Lens' IngestionInfo (Maybe Text)
iiRtmpsIngestionAddress
= lens _iiRtmpsIngestionAddress
(\ s a -> s{_iiRtmpsIngestionAddress = a})
-- | The backup ingestion URL that you should use to stream video to YouTube.
-- You have the option of simultaneously streaming the content that you are
-- sending to the ingestionAddress to this URL.
iiBackupIngestionAddress :: Lens' IngestionInfo (Maybe Text)
iiBackupIngestionAddress
= lens _iiBackupIngestionAddress
(\ s a -> s{_iiBackupIngestionAddress = a})
-- | The primary ingestion URL that you should use to stream video to
-- YouTube. You must stream video to this URL. Depending on which
-- application or tool you use to encode your video stream, you may need to
-- enter the stream URL and stream name separately or you may need to
-- concatenate them in the following format: *STREAM_URL\/STREAM_NAME*
iiIngestionAddress :: Lens' IngestionInfo (Maybe Text)
iiIngestionAddress
= lens _iiIngestionAddress
(\ s a -> s{_iiIngestionAddress = a})
-- | This ingestion url may be used instead of backupIngestionAddress in
-- order to stream via RTMPS. Not applicable to non-RTMP streams.
iiRtmpsBackupIngestionAddress :: Lens' IngestionInfo (Maybe Text)
iiRtmpsBackupIngestionAddress
= lens _iiRtmpsBackupIngestionAddress
(\ s a -> s{_iiRtmpsBackupIngestionAddress = a})
-- | The HTTP or RTMP stream name that YouTube assigns to the video stream.
iiStreamName :: Lens' IngestionInfo (Maybe Text)
iiStreamName
= lens _iiStreamName (\ s a -> s{_iiStreamName = a})
instance FromJSON IngestionInfo where
parseJSON
= withObject "IngestionInfo"
(\ o ->
IngestionInfo' <$>
(o .:? "rtmpsIngestionAddress") <*>
(o .:? "backupIngestionAddress")
<*> (o .:? "ingestionAddress")
<*> (o .:? "rtmpsBackupIngestionAddress")
<*> (o .:? "streamName"))
instance ToJSON IngestionInfo where
toJSON IngestionInfo'{..}
= object
(catMaybes
[("rtmpsIngestionAddress" .=) <$>
_iiRtmpsIngestionAddress,
("backupIngestionAddress" .=) <$>
_iiBackupIngestionAddress,
("ingestionAddress" .=) <$> _iiIngestionAddress,
("rtmpsBackupIngestionAddress" .=) <$>
_iiRtmpsBackupIngestionAddress,
("streamName" .=) <$> _iiStreamName])
-- | The auditDetails object encapsulates channel data that is relevant for
-- YouTube Partners during the audit process.
--
-- /See:/ 'channelAuditDetails' smart constructor.
data ChannelAuditDetails =
ChannelAuditDetails'
{ _cadContentIdClaimsGoodStanding :: !(Maybe Bool)
, _cadCopyrightStrikesGoodStanding :: !(Maybe Bool)
, _cadCommUnityGuidelinesGoodStanding :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelAuditDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cadContentIdClaimsGoodStanding'
--
-- * 'cadCopyrightStrikesGoodStanding'
--
-- * 'cadCommUnityGuidelinesGoodStanding'
channelAuditDetails
:: ChannelAuditDetails
channelAuditDetails =
ChannelAuditDetails'
{ _cadContentIdClaimsGoodStanding = Nothing
, _cadCopyrightStrikesGoodStanding = Nothing
, _cadCommUnityGuidelinesGoodStanding = Nothing
}
-- | Whether or not the channel has any unresolved claims.
cadContentIdClaimsGoodStanding :: Lens' ChannelAuditDetails (Maybe Bool)
cadContentIdClaimsGoodStanding
= lens _cadContentIdClaimsGoodStanding
(\ s a -> s{_cadContentIdClaimsGoodStanding = a})
-- | Whether or not the channel has any copyright strikes.
cadCopyrightStrikesGoodStanding :: Lens' ChannelAuditDetails (Maybe Bool)
cadCopyrightStrikesGoodStanding
= lens _cadCopyrightStrikesGoodStanding
(\ s a -> s{_cadCopyrightStrikesGoodStanding = a})
-- | Whether or not the channel respects the community guidelines.
cadCommUnityGuidelinesGoodStanding :: Lens' ChannelAuditDetails (Maybe Bool)
cadCommUnityGuidelinesGoodStanding
= lens _cadCommUnityGuidelinesGoodStanding
(\ s a -> s{_cadCommUnityGuidelinesGoodStanding = a})
instance FromJSON ChannelAuditDetails where
parseJSON
= withObject "ChannelAuditDetails"
(\ o ->
ChannelAuditDetails' <$>
(o .:? "contentIdClaimsGoodStanding") <*>
(o .:? "copyrightStrikesGoodStanding")
<*> (o .:? "communityGuidelinesGoodStanding"))
instance ToJSON ChannelAuditDetails where
toJSON ChannelAuditDetails'{..}
= object
(catMaybes
[("contentIdClaimsGoodStanding" .=) <$>
_cadContentIdClaimsGoodStanding,
("copyrightStrikesGoodStanding" .=) <$>
_cadCopyrightStrikesGoodStanding,
("communityGuidelinesGoodStanding" .=) <$>
_cadCommUnityGuidelinesGoodStanding])
-- | A thumbnail is an image representing a YouTube resource.
--
-- /See:/ 'thumbnail' smart constructor.
data Thumbnail =
Thumbnail'
{ _tHeight :: !(Maybe (Textual Word32))
, _tURL :: !(Maybe Text)
, _tWidth :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Thumbnail' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tHeight'
--
-- * 'tURL'
--
-- * 'tWidth'
thumbnail
:: Thumbnail
thumbnail = Thumbnail' {_tHeight = Nothing, _tURL = Nothing, _tWidth = Nothing}
-- | (Optional) Height of the thumbnail image.
tHeight :: Lens' Thumbnail (Maybe Word32)
tHeight
= lens _tHeight (\ s a -> s{_tHeight = a}) .
mapping _Coerce
-- | The thumbnail image\'s URL.
tURL :: Lens' Thumbnail (Maybe Text)
tURL = lens _tURL (\ s a -> s{_tURL = a})
-- | (Optional) Width of the thumbnail image.
tWidth :: Lens' Thumbnail (Maybe Word32)
tWidth
= lens _tWidth (\ s a -> s{_tWidth = a}) .
mapping _Coerce
instance FromJSON Thumbnail where
parseJSON
= withObject "Thumbnail"
(\ o ->
Thumbnail' <$>
(o .:? "height") <*> (o .:? "url") <*>
(o .:? "width"))
instance ToJSON Thumbnail where
toJSON Thumbnail'{..}
= object
(catMaybes
[("height" .=) <$> _tHeight, ("url" .=) <$> _tURL,
("width" .=) <$> _tWidth])
--
-- /See:/ 'liveChatTextMessageDetails' smart constructor.
newtype LiveChatTextMessageDetails =
LiveChatTextMessageDetails'
{ _lctmdMessageText :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatTextMessageDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lctmdMessageText'
liveChatTextMessageDetails
:: LiveChatTextMessageDetails
liveChatTextMessageDetails =
LiveChatTextMessageDetails' {_lctmdMessageText = Nothing}
-- | The user\'s message.
lctmdMessageText :: Lens' LiveChatTextMessageDetails (Maybe Text)
lctmdMessageText
= lens _lctmdMessageText
(\ s a -> s{_lctmdMessageText = a})
instance FromJSON LiveChatTextMessageDetails where
parseJSON
= withObject "LiveChatTextMessageDetails"
(\ o ->
LiveChatTextMessageDetails' <$>
(o .:? "messageText"))
instance ToJSON LiveChatTextMessageDetails where
toJSON LiveChatTextMessageDetails'{..}
= object
(catMaybes
[("messageText" .=) <$> _lctmdMessageText])
-- | Information that identifies the recommended resource.
--
-- /See:/ 'activityContentDetailsRecommendation' smart constructor.
data ActivityContentDetailsRecommendation =
ActivityContentDetailsRecommendation'
{ _acdrResourceId :: !(Maybe ResourceId)
, _acdrSeedResourceId :: !(Maybe ResourceId)
, _acdrReason :: !(Maybe ActivityContentDetailsRecommendationReason)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsRecommendation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdrResourceId'
--
-- * 'acdrSeedResourceId'
--
-- * 'acdrReason'
activityContentDetailsRecommendation
:: ActivityContentDetailsRecommendation
activityContentDetailsRecommendation =
ActivityContentDetailsRecommendation'
{ _acdrResourceId = Nothing
, _acdrSeedResourceId = Nothing
, _acdrReason = Nothing
}
-- | The resourceId object contains information that identifies the
-- recommended resource.
acdrResourceId :: Lens' ActivityContentDetailsRecommendation (Maybe ResourceId)
acdrResourceId
= lens _acdrResourceId
(\ s a -> s{_acdrResourceId = a})
-- | The seedResourceId object contains information about the resource that
-- caused the recommendation.
acdrSeedResourceId :: Lens' ActivityContentDetailsRecommendation (Maybe ResourceId)
acdrSeedResourceId
= lens _acdrSeedResourceId
(\ s a -> s{_acdrSeedResourceId = a})
-- | The reason that the resource is recommended to the user.
acdrReason :: Lens' ActivityContentDetailsRecommendation (Maybe ActivityContentDetailsRecommendationReason)
acdrReason
= lens _acdrReason (\ s a -> s{_acdrReason = a})
instance FromJSON
ActivityContentDetailsRecommendation
where
parseJSON
= withObject "ActivityContentDetailsRecommendation"
(\ o ->
ActivityContentDetailsRecommendation' <$>
(o .:? "resourceId") <*> (o .:? "seedResourceId") <*>
(o .:? "reason"))
instance ToJSON ActivityContentDetailsRecommendation
where
toJSON ActivityContentDetailsRecommendation'{..}
= object
(catMaybes
[("resourceId" .=) <$> _acdrResourceId,
("seedResourceId" .=) <$> _acdrSeedResourceId,
("reason" .=) <$> _acdrReason])
--
-- /See:/ 'liveChatMessageRetractedDetails' smart constructor.
newtype LiveChatMessageRetractedDetails =
LiveChatMessageRetractedDetails'
{ _lcmrdRetractedMessageId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatMessageRetractedDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcmrdRetractedMessageId'
liveChatMessageRetractedDetails
:: LiveChatMessageRetractedDetails
liveChatMessageRetractedDetails =
LiveChatMessageRetractedDetails' {_lcmrdRetractedMessageId = Nothing}
lcmrdRetractedMessageId :: Lens' LiveChatMessageRetractedDetails (Maybe Text)
lcmrdRetractedMessageId
= lens _lcmrdRetractedMessageId
(\ s a -> s{_lcmrdRetractedMessageId = a})
instance FromJSON LiveChatMessageRetractedDetails
where
parseJSON
= withObject "LiveChatMessageRetractedDetails"
(\ o ->
LiveChatMessageRetractedDetails' <$>
(o .:? "retractedMessageId"))
instance ToJSON LiveChatMessageRetractedDetails where
toJSON LiveChatMessageRetractedDetails'{..}
= object
(catMaybes
[("retractedMessageId" .=) <$>
_lcmrdRetractedMessageId])
--
-- /See:/ 'playListListResponse' smart constructor.
data PlayListListResponse =
PlayListListResponse'
{ _pllrEtag :: !(Maybe Text)
, _pllrTokenPagination :: !(Maybe TokenPagination)
, _pllrNextPageToken :: !(Maybe Text)
, _pllrPageInfo :: !(Maybe PageInfo)
, _pllrKind :: !Text
, _pllrItems :: !(Maybe [PlayList])
, _pllrVisitorId :: !(Maybe Text)
, _pllrEventId :: !(Maybe Text)
, _pllrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllrEtag'
--
-- * 'pllrTokenPagination'
--
-- * 'pllrNextPageToken'
--
-- * 'pllrPageInfo'
--
-- * 'pllrKind'
--
-- * 'pllrItems'
--
-- * 'pllrVisitorId'
--
-- * 'pllrEventId'
--
-- * 'pllrPrevPageToken'
playListListResponse
:: PlayListListResponse
playListListResponse =
PlayListListResponse'
{ _pllrEtag = Nothing
, _pllrTokenPagination = Nothing
, _pllrNextPageToken = Nothing
, _pllrPageInfo = Nothing
, _pllrKind = "youtube#playlistListResponse"
, _pllrItems = Nothing
, _pllrVisitorId = Nothing
, _pllrEventId = Nothing
, _pllrPrevPageToken = Nothing
}
-- | Etag of this resource.
pllrEtag :: Lens' PlayListListResponse (Maybe Text)
pllrEtag = lens _pllrEtag (\ s a -> s{_pllrEtag = a})
pllrTokenPagination :: Lens' PlayListListResponse (Maybe TokenPagination)
pllrTokenPagination
= lens _pllrTokenPagination
(\ s a -> s{_pllrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
pllrNextPageToken :: Lens' PlayListListResponse (Maybe Text)
pllrNextPageToken
= lens _pllrNextPageToken
(\ s a -> s{_pllrNextPageToken = a})
-- | General pagination information.
pllrPageInfo :: Lens' PlayListListResponse (Maybe PageInfo)
pllrPageInfo
= lens _pllrPageInfo (\ s a -> s{_pllrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#playlistListResponse\".
pllrKind :: Lens' PlayListListResponse Text
pllrKind = lens _pllrKind (\ s a -> s{_pllrKind = a})
-- | A list of playlists that match the request criteria
pllrItems :: Lens' PlayListListResponse [PlayList]
pllrItems
= lens _pllrItems (\ s a -> s{_pllrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
pllrVisitorId :: Lens' PlayListListResponse (Maybe Text)
pllrVisitorId
= lens _pllrVisitorId
(\ s a -> s{_pllrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
pllrEventId :: Lens' PlayListListResponse (Maybe Text)
pllrEventId
= lens _pllrEventId (\ s a -> s{_pllrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
pllrPrevPageToken :: Lens' PlayListListResponse (Maybe Text)
pllrPrevPageToken
= lens _pllrPrevPageToken
(\ s a -> s{_pllrPrevPageToken = a})
instance FromJSON PlayListListResponse where
parseJSON
= withObject "PlayListListResponse"
(\ o ->
PlayListListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#playlistListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON PlayListListResponse where
toJSON PlayListListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _pllrEtag,
("tokenPagination" .=) <$> _pllrTokenPagination,
("nextPageToken" .=) <$> _pllrNextPageToken,
("pageInfo" .=) <$> _pllrPageInfo,
Just ("kind" .= _pllrKind),
("items" .=) <$> _pllrItems,
("visitorId" .=) <$> _pllrVisitorId,
("eventId" .=) <$> _pllrEventId,
("prevPageToken" .=) <$> _pllrPrevPageToken])
-- | Basic details about a channel section, including title, style and
-- position.
--
-- /See:/ 'channelSectionSnippet' smart constructor.
data ChannelSectionSnippet =
ChannelSectionSnippet'
{ _cssStyle :: !(Maybe ChannelSectionSnippetStyle)
, _cssChannelId :: !(Maybe Text)
, _cssLocalized :: !(Maybe ChannelSectionLocalization)
, _cssTitle :: !(Maybe Text)
, _cssType :: !(Maybe ChannelSectionSnippetType)
, _cssPosition :: !(Maybe (Textual Word32))
, _cssDefaultLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSectionSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cssStyle'
--
-- * 'cssChannelId'
--
-- * 'cssLocalized'
--
-- * 'cssTitle'
--
-- * 'cssType'
--
-- * 'cssPosition'
--
-- * 'cssDefaultLanguage'
channelSectionSnippet
:: ChannelSectionSnippet
channelSectionSnippet =
ChannelSectionSnippet'
{ _cssStyle = Nothing
, _cssChannelId = Nothing
, _cssLocalized = Nothing
, _cssTitle = Nothing
, _cssType = Nothing
, _cssPosition = Nothing
, _cssDefaultLanguage = Nothing
}
-- | The style of the channel section.
cssStyle :: Lens' ChannelSectionSnippet (Maybe ChannelSectionSnippetStyle)
cssStyle = lens _cssStyle (\ s a -> s{_cssStyle = a})
-- | The ID that YouTube uses to uniquely identify the channel that published
-- the channel section.
cssChannelId :: Lens' ChannelSectionSnippet (Maybe Text)
cssChannelId
= lens _cssChannelId (\ s a -> s{_cssChannelId = a})
-- | Localized title, read-only.
cssLocalized :: Lens' ChannelSectionSnippet (Maybe ChannelSectionLocalization)
cssLocalized
= lens _cssLocalized (\ s a -> s{_cssLocalized = a})
-- | The channel section\'s title for multiple_playlists and
-- multiple_channels.
cssTitle :: Lens' ChannelSectionSnippet (Maybe Text)
cssTitle = lens _cssTitle (\ s a -> s{_cssTitle = a})
-- | The type of the channel section.
cssType :: Lens' ChannelSectionSnippet (Maybe ChannelSectionSnippetType)
cssType = lens _cssType (\ s a -> s{_cssType = a})
-- | The position of the channel section in the channel.
cssPosition :: Lens' ChannelSectionSnippet (Maybe Word32)
cssPosition
= lens _cssPosition (\ s a -> s{_cssPosition = a}) .
mapping _Coerce
-- | The language of the channel section\'s default title and description.
cssDefaultLanguage :: Lens' ChannelSectionSnippet (Maybe Text)
cssDefaultLanguage
= lens _cssDefaultLanguage
(\ s a -> s{_cssDefaultLanguage = a})
instance FromJSON ChannelSectionSnippet where
parseJSON
= withObject "ChannelSectionSnippet"
(\ o ->
ChannelSectionSnippet' <$>
(o .:? "style") <*> (o .:? "channelId") <*>
(o .:? "localized")
<*> (o .:? "title")
<*> (o .:? "type")
<*> (o .:? "position")
<*> (o .:? "defaultLanguage"))
instance ToJSON ChannelSectionSnippet where
toJSON ChannelSectionSnippet'{..}
= object
(catMaybes
[("style" .=) <$> _cssStyle,
("channelId" .=) <$> _cssChannelId,
("localized" .=) <$> _cssLocalized,
("title" .=) <$> _cssTitle, ("type" .=) <$> _cssType,
("position" .=) <$> _cssPosition,
("defaultLanguage" .=) <$> _cssDefaultLanguage])
-- | JSON template for the status part of a channel.
--
-- /See:/ 'channelStatus' smart constructor.
data ChannelStatus =
ChannelStatus'
{ _csIsLinked :: !(Maybe Bool)
, _csLongUploadsStatus :: !(Maybe ChannelStatusLongUploadsStatus)
, _csPrivacyStatus :: !(Maybe ChannelStatusPrivacyStatus)
, _csSelfDeclaredMadeForKids :: !(Maybe Bool)
, _csMadeForKids :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csIsLinked'
--
-- * 'csLongUploadsStatus'
--
-- * 'csPrivacyStatus'
--
-- * 'csSelfDeclaredMadeForKids'
--
-- * 'csMadeForKids'
channelStatus
:: ChannelStatus
channelStatus =
ChannelStatus'
{ _csIsLinked = Nothing
, _csLongUploadsStatus = Nothing
, _csPrivacyStatus = Nothing
, _csSelfDeclaredMadeForKids = Nothing
, _csMadeForKids = Nothing
}
-- | If true, then the user is linked to either a YouTube username or G+
-- account. Otherwise, the user doesn\'t have a public YouTube identity.
csIsLinked :: Lens' ChannelStatus (Maybe Bool)
csIsLinked
= lens _csIsLinked (\ s a -> s{_csIsLinked = a})
-- | The long uploads status of this channel. See
-- https:\/\/support.google.com\/youtube\/answer\/71673 for more
-- information.
csLongUploadsStatus :: Lens' ChannelStatus (Maybe ChannelStatusLongUploadsStatus)
csLongUploadsStatus
= lens _csLongUploadsStatus
(\ s a -> s{_csLongUploadsStatus = a})
-- | Privacy status of the channel.
csPrivacyStatus :: Lens' ChannelStatus (Maybe ChannelStatusPrivacyStatus)
csPrivacyStatus
= lens _csPrivacyStatus
(\ s a -> s{_csPrivacyStatus = a})
csSelfDeclaredMadeForKids :: Lens' ChannelStatus (Maybe Bool)
csSelfDeclaredMadeForKids
= lens _csSelfDeclaredMadeForKids
(\ s a -> s{_csSelfDeclaredMadeForKids = a})
csMadeForKids :: Lens' ChannelStatus (Maybe Bool)
csMadeForKids
= lens _csMadeForKids
(\ s a -> s{_csMadeForKids = a})
instance FromJSON ChannelStatus where
parseJSON
= withObject "ChannelStatus"
(\ o ->
ChannelStatus' <$>
(o .:? "isLinked") <*> (o .:? "longUploadsStatus")
<*> (o .:? "privacyStatus")
<*> (o .:? "selfDeclaredMadeForKids")
<*> (o .:? "madeForKids"))
instance ToJSON ChannelStatus where
toJSON ChannelStatus'{..}
= object
(catMaybes
[("isLinked" .=) <$> _csIsLinked,
("longUploadsStatus" .=) <$> _csLongUploadsStatus,
("privacyStatus" .=) <$> _csPrivacyStatus,
("selfDeclaredMadeForKids" .=) <$>
_csSelfDeclaredMadeForKids,
("madeForKids" .=) <$> _csMadeForKids])
--
-- /See:/ 'liveStreamSnippet' smart constructor.
data LiveStreamSnippet =
LiveStreamSnippet'
{ _lssPublishedAt :: !(Maybe DateTime')
, _lssChannelId :: !(Maybe Text)
, _lssIsDefaultStream :: !(Maybe Bool)
, _lssTitle :: !(Maybe Text)
, _lssDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStreamSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lssPublishedAt'
--
-- * 'lssChannelId'
--
-- * 'lssIsDefaultStream'
--
-- * 'lssTitle'
--
-- * 'lssDescription'
liveStreamSnippet
:: LiveStreamSnippet
liveStreamSnippet =
LiveStreamSnippet'
{ _lssPublishedAt = Nothing
, _lssChannelId = Nothing
, _lssIsDefaultStream = Nothing
, _lssTitle = Nothing
, _lssDescription = Nothing
}
-- | The date and time that the stream was created.
lssPublishedAt :: Lens' LiveStreamSnippet (Maybe UTCTime)
lssPublishedAt
= lens _lssPublishedAt
(\ s a -> s{_lssPublishedAt = a})
. mapping _DateTime
-- | The ID that YouTube uses to uniquely identify the channel that is
-- transmitting the stream.
lssChannelId :: Lens' LiveStreamSnippet (Maybe Text)
lssChannelId
= lens _lssChannelId (\ s a -> s{_lssChannelId = a})
lssIsDefaultStream :: Lens' LiveStreamSnippet (Maybe Bool)
lssIsDefaultStream
= lens _lssIsDefaultStream
(\ s a -> s{_lssIsDefaultStream = a})
-- | The stream\'s title. The value must be between 1 and 128 characters
-- long.
lssTitle :: Lens' LiveStreamSnippet (Maybe Text)
lssTitle = lens _lssTitle (\ s a -> s{_lssTitle = a})
-- | The stream\'s description. The value cannot be longer than 10000
-- characters.
lssDescription :: Lens' LiveStreamSnippet (Maybe Text)
lssDescription
= lens _lssDescription
(\ s a -> s{_lssDescription = a})
instance FromJSON LiveStreamSnippet where
parseJSON
= withObject "LiveStreamSnippet"
(\ o ->
LiveStreamSnippet' <$>
(o .:? "publishedAt") <*> (o .:? "channelId") <*>
(o .:? "isDefaultStream")
<*> (o .:? "title")
<*> (o .:? "description"))
instance ToJSON LiveStreamSnippet where
toJSON LiveStreamSnippet'{..}
= object
(catMaybes
[("publishedAt" .=) <$> _lssPublishedAt,
("channelId" .=) <$> _lssChannelId,
("isDefaultStream" .=) <$> _lssIsDefaultStream,
("title" .=) <$> _lssTitle,
("description" .=) <$> _lssDescription])
-- | A search result contains information about a YouTube video, channel, or
-- playlist that matches the search parameters specified in an API request.
-- While a search result points to a uniquely identifiable resource, like a
-- video, it does not have its own persistent data.
--
-- /See:/ 'searchResult' smart constructor.
data SearchResult =
SearchResult'
{ _srEtag :: !(Maybe Text)
, _srSnippet :: !(Maybe SearchResultSnippet)
, _srKind :: !Text
, _srId :: !(Maybe ResourceId)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SearchResult' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'srEtag'
--
-- * 'srSnippet'
--
-- * 'srKind'
--
-- * 'srId'
searchResult
:: SearchResult
searchResult =
SearchResult'
{ _srEtag = Nothing
, _srSnippet = Nothing
, _srKind = "youtube#searchResult"
, _srId = Nothing
}
-- | Etag of this resource.
srEtag :: Lens' SearchResult (Maybe Text)
srEtag = lens _srEtag (\ s a -> s{_srEtag = a})
-- | The snippet object contains basic details about a search result, such as
-- its title or description. For example, if the search result is a video,
-- then the title will be the video\'s title and the description will be
-- the video\'s description.
srSnippet :: Lens' SearchResult (Maybe SearchResultSnippet)
srSnippet
= lens _srSnippet (\ s a -> s{_srSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#searchResult\".
srKind :: Lens' SearchResult Text
srKind = lens _srKind (\ s a -> s{_srKind = a})
-- | The id object contains information that can be used to uniquely identify
-- the resource that matches the search request.
srId :: Lens' SearchResult (Maybe ResourceId)
srId = lens _srId (\ s a -> s{_srId = a})
instance FromJSON SearchResult where
parseJSON
= withObject "SearchResult"
(\ o ->
SearchResult' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#searchResult")
<*> (o .:? "id"))
instance ToJSON SearchResult where
toJSON SearchResult'{..}
= object
(catMaybes
[("etag" .=) <$> _srEtag,
("snippet" .=) <$> _srSnippet,
Just ("kind" .= _srKind), ("id" .=) <$> _srId])
-- | A *membershipsLevel* resource represents an offer made by YouTube
-- creators for their fans. Users can become members of the channel by
-- joining one of the available levels. They will provide recurring
-- monetary support and receives special benefits.
--
-- /See:/ 'membershipsLevel' smart constructor.
data MembershipsLevel =
MembershipsLevel'
{ _mlEtag :: !(Maybe Text)
, _mlSnippet :: !(Maybe MembershipsLevelSnippet)
, _mlKind :: !Text
, _mlId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MembershipsLevel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mlEtag'
--
-- * 'mlSnippet'
--
-- * 'mlKind'
--
-- * 'mlId'
membershipsLevel
:: MembershipsLevel
membershipsLevel =
MembershipsLevel'
{ _mlEtag = Nothing
, _mlSnippet = Nothing
, _mlKind = "youtube#membershipsLevel"
, _mlId = Nothing
}
-- | Etag of this resource.
mlEtag :: Lens' MembershipsLevel (Maybe Text)
mlEtag = lens _mlEtag (\ s a -> s{_mlEtag = a})
-- | The snippet object contains basic details about the level.
mlSnippet :: Lens' MembershipsLevel (Maybe MembershipsLevelSnippet)
mlSnippet
= lens _mlSnippet (\ s a -> s{_mlSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#membershipsLevelListResponse\".
mlKind :: Lens' MembershipsLevel Text
mlKind = lens _mlKind (\ s a -> s{_mlKind = a})
-- | The ID that YouTube assigns to uniquely identify the memberships level.
mlId :: Lens' MembershipsLevel (Maybe Text)
mlId = lens _mlId (\ s a -> s{_mlId = a})
instance FromJSON MembershipsLevel where
parseJSON
= withObject "MembershipsLevel"
(\ o ->
MembershipsLevel' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#membershipsLevel")
<*> (o .:? "id"))
instance ToJSON MembershipsLevel where
toJSON MembershipsLevel'{..}
= object
(catMaybes
[("etag" .=) <$> _mlEtag,
("snippet" .=) <$> _mlSnippet,
Just ("kind" .= _mlKind), ("id" .=) <$> _mlId])
-- | Stub token pagination template to suppress results.
--
-- /See:/ 'tokenPagination' smart constructor.
data TokenPagination =
TokenPagination'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TokenPagination' with the minimum fields required to make a request.
--
tokenPagination
:: TokenPagination
tokenPagination = TokenPagination'
instance FromJSON TokenPagination where
parseJSON
= withObject "TokenPagination"
(\ o -> pure TokenPagination')
instance ToJSON TokenPagination where
toJSON = const emptyObject
-- | A resource id is a generic reference that points to another YouTube
-- resource.
--
-- /See:/ 'resourceId' smart constructor.
data ResourceId =
ResourceId'
{ _riKind :: !(Maybe Text)
, _riChannelId :: !(Maybe Text)
, _riVideoId :: !(Maybe Text)
, _riPlayListId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ResourceId' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'riKind'
--
-- * 'riChannelId'
--
-- * 'riVideoId'
--
-- * 'riPlayListId'
resourceId
:: ResourceId
resourceId =
ResourceId'
{ _riKind = Nothing
, _riChannelId = Nothing
, _riVideoId = Nothing
, _riPlayListId = Nothing
}
-- | The type of the API resource.
riKind :: Lens' ResourceId (Maybe Text)
riKind = lens _riKind (\ s a -> s{_riKind = a})
-- | The ID that YouTube uses to uniquely identify the referred resource, if
-- that resource is a channel. This property is only present if the
-- resourceId.kind value is youtube#channel.
riChannelId :: Lens' ResourceId (Maybe Text)
riChannelId
= lens _riChannelId (\ s a -> s{_riChannelId = a})
-- | The ID that YouTube uses to uniquely identify the referred resource, if
-- that resource is a video. This property is only present if the
-- resourceId.kind value is youtube#video.
riVideoId :: Lens' ResourceId (Maybe Text)
riVideoId
= lens _riVideoId (\ s a -> s{_riVideoId = a})
-- | The ID that YouTube uses to uniquely identify the referred resource, if
-- that resource is a playlist. This property is only present if the
-- resourceId.kind value is youtube#playlist.
riPlayListId :: Lens' ResourceId (Maybe Text)
riPlayListId
= lens _riPlayListId (\ s a -> s{_riPlayListId = a})
instance FromJSON ResourceId where
parseJSON
= withObject "ResourceId"
(\ o ->
ResourceId' <$>
(o .:? "kind") <*> (o .:? "channelId") <*>
(o .:? "videoId")
<*> (o .:? "playlistId"))
instance ToJSON ResourceId where
toJSON ResourceId'{..}
= object
(catMaybes
[("kind" .=) <$> _riKind,
("channelId" .=) <$> _riChannelId,
("videoId" .=) <$> _riVideoId,
("playlistId" .=) <$> _riPlayListId])
--
-- /See:/ 'searchListResponse' smart constructor.
data SearchListResponse =
SearchListResponse'
{ _slrEtag :: !(Maybe Text)
, _slrTokenPagination :: !(Maybe TokenPagination)
, _slrNextPageToken :: !(Maybe Text)
, _slrRegionCode :: !(Maybe Text)
, _slrPageInfo :: !(Maybe PageInfo)
, _slrKind :: !Text
, _slrItems :: !(Maybe [SearchResult])
, _slrVisitorId :: !(Maybe Text)
, _slrEventId :: !(Maybe Text)
, _slrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SearchListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'slrEtag'
--
-- * 'slrTokenPagination'
--
-- * 'slrNextPageToken'
--
-- * 'slrRegionCode'
--
-- * 'slrPageInfo'
--
-- * 'slrKind'
--
-- * 'slrItems'
--
-- * 'slrVisitorId'
--
-- * 'slrEventId'
--
-- * 'slrPrevPageToken'
searchListResponse
:: SearchListResponse
searchListResponse =
SearchListResponse'
{ _slrEtag = Nothing
, _slrTokenPagination = Nothing
, _slrNextPageToken = Nothing
, _slrRegionCode = Nothing
, _slrPageInfo = Nothing
, _slrKind = "youtube#searchListResponse"
, _slrItems = Nothing
, _slrVisitorId = Nothing
, _slrEventId = Nothing
, _slrPrevPageToken = Nothing
}
-- | Etag of this resource.
slrEtag :: Lens' SearchListResponse (Maybe Text)
slrEtag = lens _slrEtag (\ s a -> s{_slrEtag = a})
slrTokenPagination :: Lens' SearchListResponse (Maybe TokenPagination)
slrTokenPagination
= lens _slrTokenPagination
(\ s a -> s{_slrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
slrNextPageToken :: Lens' SearchListResponse (Maybe Text)
slrNextPageToken
= lens _slrNextPageToken
(\ s a -> s{_slrNextPageToken = a})
slrRegionCode :: Lens' SearchListResponse (Maybe Text)
slrRegionCode
= lens _slrRegionCode
(\ s a -> s{_slrRegionCode = a})
-- | General pagination information.
slrPageInfo :: Lens' SearchListResponse (Maybe PageInfo)
slrPageInfo
= lens _slrPageInfo (\ s a -> s{_slrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#searchListResponse\".
slrKind :: Lens' SearchListResponse Text
slrKind = lens _slrKind (\ s a -> s{_slrKind = a})
-- | Pagination information for token pagination.
slrItems :: Lens' SearchListResponse [SearchResult]
slrItems
= lens _slrItems (\ s a -> s{_slrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
slrVisitorId :: Lens' SearchListResponse (Maybe Text)
slrVisitorId
= lens _slrVisitorId (\ s a -> s{_slrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
slrEventId :: Lens' SearchListResponse (Maybe Text)
slrEventId
= lens _slrEventId (\ s a -> s{_slrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
slrPrevPageToken :: Lens' SearchListResponse (Maybe Text)
slrPrevPageToken
= lens _slrPrevPageToken
(\ s a -> s{_slrPrevPageToken = a})
instance FromJSON SearchListResponse where
parseJSON
= withObject "SearchListResponse"
(\ o ->
SearchListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "regionCode")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#searchListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON SearchListResponse where
toJSON SearchListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _slrEtag,
("tokenPagination" .=) <$> _slrTokenPagination,
("nextPageToken" .=) <$> _slrNextPageToken,
("regionCode" .=) <$> _slrRegionCode,
("pageInfo" .=) <$> _slrPageInfo,
Just ("kind" .= _slrKind),
("items" .=) <$> _slrItems,
("visitorId" .=) <$> _slrVisitorId,
("eventId" .=) <$> _slrEventId,
("prevPageToken" .=) <$> _slrPrevPageToken])
--
-- /See:/ 'playListStatus' smart constructor.
newtype PlayListStatus =
PlayListStatus'
{ _plsPrivacyStatus :: Maybe PlayListStatusPrivacyStatus
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plsPrivacyStatus'
playListStatus
:: PlayListStatus
playListStatus = PlayListStatus' {_plsPrivacyStatus = Nothing}
-- | The playlist\'s privacy status.
plsPrivacyStatus :: Lens' PlayListStatus (Maybe PlayListStatusPrivacyStatus)
plsPrivacyStatus
= lens _plsPrivacyStatus
(\ s a -> s{_plsPrivacyStatus = a})
instance FromJSON PlayListStatus where
parseJSON
= withObject "PlayListStatus"
(\ o -> PlayListStatus' <$> (o .:? "privacyStatus"))
instance ToJSON PlayListStatus where
toJSON PlayListStatus'{..}
= object
(catMaybes
[("privacyStatus" .=) <$> _plsPrivacyStatus])
--
-- /See:/ 'liveChatMessageListResponse' smart constructor.
data LiveChatMessageListResponse =
LiveChatMessageListResponse'
{ _lcmlrOfflineAt :: !(Maybe DateTime')
, _lcmlrEtag :: !(Maybe Text)
, _lcmlrTokenPagination :: !(Maybe TokenPagination)
, _lcmlrNextPageToken :: !(Maybe Text)
, _lcmlrPageInfo :: !(Maybe PageInfo)
, _lcmlrKind :: !Text
, _lcmlrItems :: !(Maybe [LiveChatMessage])
, _lcmlrVisitorId :: !(Maybe Text)
, _lcmlrPollingIntervalMillis :: !(Maybe (Textual Word32))
, _lcmlrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatMessageListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcmlrOfflineAt'
--
-- * 'lcmlrEtag'
--
-- * 'lcmlrTokenPagination'
--
-- * 'lcmlrNextPageToken'
--
-- * 'lcmlrPageInfo'
--
-- * 'lcmlrKind'
--
-- * 'lcmlrItems'
--
-- * 'lcmlrVisitorId'
--
-- * 'lcmlrPollingIntervalMillis'
--
-- * 'lcmlrEventId'
liveChatMessageListResponse
:: LiveChatMessageListResponse
liveChatMessageListResponse =
LiveChatMessageListResponse'
{ _lcmlrOfflineAt = Nothing
, _lcmlrEtag = Nothing
, _lcmlrTokenPagination = Nothing
, _lcmlrNextPageToken = Nothing
, _lcmlrPageInfo = Nothing
, _lcmlrKind = "youtube#liveChatMessageListResponse"
, _lcmlrItems = Nothing
, _lcmlrVisitorId = Nothing
, _lcmlrPollingIntervalMillis = Nothing
, _lcmlrEventId = Nothing
}
-- | The date and time when the underlying stream went offline.
lcmlrOfflineAt :: Lens' LiveChatMessageListResponse (Maybe UTCTime)
lcmlrOfflineAt
= lens _lcmlrOfflineAt
(\ s a -> s{_lcmlrOfflineAt = a})
. mapping _DateTime
-- | Etag of this resource.
lcmlrEtag :: Lens' LiveChatMessageListResponse (Maybe Text)
lcmlrEtag
= lens _lcmlrEtag (\ s a -> s{_lcmlrEtag = a})
lcmlrTokenPagination :: Lens' LiveChatMessageListResponse (Maybe TokenPagination)
lcmlrTokenPagination
= lens _lcmlrTokenPagination
(\ s a -> s{_lcmlrTokenPagination = a})
lcmlrNextPageToken :: Lens' LiveChatMessageListResponse (Maybe Text)
lcmlrNextPageToken
= lens _lcmlrNextPageToken
(\ s a -> s{_lcmlrNextPageToken = a})
-- | General pagination information.
lcmlrPageInfo :: Lens' LiveChatMessageListResponse (Maybe PageInfo)
lcmlrPageInfo
= lens _lcmlrPageInfo
(\ s a -> s{_lcmlrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveChatMessageListResponse\".
lcmlrKind :: Lens' LiveChatMessageListResponse Text
lcmlrKind
= lens _lcmlrKind (\ s a -> s{_lcmlrKind = a})
lcmlrItems :: Lens' LiveChatMessageListResponse [LiveChatMessage]
lcmlrItems
= lens _lcmlrItems (\ s a -> s{_lcmlrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
lcmlrVisitorId :: Lens' LiveChatMessageListResponse (Maybe Text)
lcmlrVisitorId
= lens _lcmlrVisitorId
(\ s a -> s{_lcmlrVisitorId = a})
-- | The amount of time the client should wait before polling again.
lcmlrPollingIntervalMillis :: Lens' LiveChatMessageListResponse (Maybe Word32)
lcmlrPollingIntervalMillis
= lens _lcmlrPollingIntervalMillis
(\ s a -> s{_lcmlrPollingIntervalMillis = a})
. mapping _Coerce
-- | Serialized EventId of the request which produced this response.
lcmlrEventId :: Lens' LiveChatMessageListResponse (Maybe Text)
lcmlrEventId
= lens _lcmlrEventId (\ s a -> s{_lcmlrEventId = a})
instance FromJSON LiveChatMessageListResponse where
parseJSON
= withObject "LiveChatMessageListResponse"
(\ o ->
LiveChatMessageListResponse' <$>
(o .:? "offlineAt") <*> (o .:? "etag") <*>
(o .:? "tokenPagination")
<*> (o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!=
"youtube#liveChatMessageListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "pollingIntervalMillis")
<*> (o .:? "eventId"))
instance ToJSON LiveChatMessageListResponse where
toJSON LiveChatMessageListResponse'{..}
= object
(catMaybes
[("offlineAt" .=) <$> _lcmlrOfflineAt,
("etag" .=) <$> _lcmlrEtag,
("tokenPagination" .=) <$> _lcmlrTokenPagination,
("nextPageToken" .=) <$> _lcmlrNextPageToken,
("pageInfo" .=) <$> _lcmlrPageInfo,
Just ("kind" .= _lcmlrKind),
("items" .=) <$> _lcmlrItems,
("visitorId" .=) <$> _lcmlrVisitorId,
("pollingIntervalMillis" .=) <$>
_lcmlrPollingIntervalMillis,
("eventId" .=) <$> _lcmlrEventId])
--
-- /See:/ 'channelListResponse' smart constructor.
data ChannelListResponse =
ChannelListResponse'
{ _clrEtag :: !(Maybe Text)
, _clrTokenPagination :: !(Maybe TokenPagination)
, _clrNextPageToken :: !(Maybe Text)
, _clrPageInfo :: !(Maybe PageInfo)
, _clrKind :: !Text
, _clrItems :: !(Maybe [Channel])
, _clrVisitorId :: !(Maybe Text)
, _clrEventId :: !(Maybe Text)
, _clrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clrEtag'
--
-- * 'clrTokenPagination'
--
-- * 'clrNextPageToken'
--
-- * 'clrPageInfo'
--
-- * 'clrKind'
--
-- * 'clrItems'
--
-- * 'clrVisitorId'
--
-- * 'clrEventId'
--
-- * 'clrPrevPageToken'
channelListResponse
:: ChannelListResponse
channelListResponse =
ChannelListResponse'
{ _clrEtag = Nothing
, _clrTokenPagination = Nothing
, _clrNextPageToken = Nothing
, _clrPageInfo = Nothing
, _clrKind = "youtube#channelListResponse"
, _clrItems = Nothing
, _clrVisitorId = Nothing
, _clrEventId = Nothing
, _clrPrevPageToken = Nothing
}
-- | Etag of this resource.
clrEtag :: Lens' ChannelListResponse (Maybe Text)
clrEtag = lens _clrEtag (\ s a -> s{_clrEtag = a})
clrTokenPagination :: Lens' ChannelListResponse (Maybe TokenPagination)
clrTokenPagination
= lens _clrTokenPagination
(\ s a -> s{_clrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
clrNextPageToken :: Lens' ChannelListResponse (Maybe Text)
clrNextPageToken
= lens _clrNextPageToken
(\ s a -> s{_clrNextPageToken = a})
-- | General pagination information.
clrPageInfo :: Lens' ChannelListResponse (Maybe PageInfo)
clrPageInfo
= lens _clrPageInfo (\ s a -> s{_clrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#channelListResponse\".
clrKind :: Lens' ChannelListResponse Text
clrKind = lens _clrKind (\ s a -> s{_clrKind = a})
clrItems :: Lens' ChannelListResponse [Channel]
clrItems
= lens _clrItems (\ s a -> s{_clrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
clrVisitorId :: Lens' ChannelListResponse (Maybe Text)
clrVisitorId
= lens _clrVisitorId (\ s a -> s{_clrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
clrEventId :: Lens' ChannelListResponse (Maybe Text)
clrEventId
= lens _clrEventId (\ s a -> s{_clrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
clrPrevPageToken :: Lens' ChannelListResponse (Maybe Text)
clrPrevPageToken
= lens _clrPrevPageToken
(\ s a -> s{_clrPrevPageToken = a})
instance FromJSON ChannelListResponse where
parseJSON
= withObject "ChannelListResponse"
(\ o ->
ChannelListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#channelListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON ChannelListResponse where
toJSON ChannelListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _clrEtag,
("tokenPagination" .=) <$> _clrTokenPagination,
("nextPageToken" .=) <$> _clrNextPageToken,
("pageInfo" .=) <$> _clrPageInfo,
Just ("kind" .= _clrKind),
("items" .=) <$> _clrItems,
("visitorId" .=) <$> _clrVisitorId,
("eventId" .=) <$> _clrEventId,
("prevPageToken" .=) <$> _clrPrevPageToken])
--
-- /See:/ 'channelProFileDetails' smart constructor.
data ChannelProFileDetails =
ChannelProFileDetails'
{ _cpfdChannelId :: !(Maybe Text)
, _cpfdProFileImageURL :: !(Maybe Text)
, _cpfdDisplayName :: !(Maybe Text)
, _cpfdChannelURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelProFileDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cpfdChannelId'
--
-- * 'cpfdProFileImageURL'
--
-- * 'cpfdDisplayName'
--
-- * 'cpfdChannelURL'
channelProFileDetails
:: ChannelProFileDetails
channelProFileDetails =
ChannelProFileDetails'
{ _cpfdChannelId = Nothing
, _cpfdProFileImageURL = Nothing
, _cpfdDisplayName = Nothing
, _cpfdChannelURL = Nothing
}
-- | The YouTube channel ID.
cpfdChannelId :: Lens' ChannelProFileDetails (Maybe Text)
cpfdChannelId
= lens _cpfdChannelId
(\ s a -> s{_cpfdChannelId = a})
-- | The channels\'s avatar URL.
cpfdProFileImageURL :: Lens' ChannelProFileDetails (Maybe Text)
cpfdProFileImageURL
= lens _cpfdProFileImageURL
(\ s a -> s{_cpfdProFileImageURL = a})
-- | The channel\'s display name.
cpfdDisplayName :: Lens' ChannelProFileDetails (Maybe Text)
cpfdDisplayName
= lens _cpfdDisplayName
(\ s a -> s{_cpfdDisplayName = a})
-- | The channel\'s URL.
cpfdChannelURL :: Lens' ChannelProFileDetails (Maybe Text)
cpfdChannelURL
= lens _cpfdChannelURL
(\ s a -> s{_cpfdChannelURL = a})
instance FromJSON ChannelProFileDetails where
parseJSON
= withObject "ChannelProFileDetails"
(\ o ->
ChannelProFileDetails' <$>
(o .:? "channelId") <*> (o .:? "profileImageUrl") <*>
(o .:? "displayName")
<*> (o .:? "channelUrl"))
instance ToJSON ChannelProFileDetails where
toJSON ChannelProFileDetails'{..}
= object
(catMaybes
[("channelId" .=) <$> _cpfdChannelId,
("profileImageUrl" .=) <$> _cpfdProFileImageURL,
("displayName" .=) <$> _cpfdDisplayName,
("channelUrl" .=) <$> _cpfdChannelURL])
--
-- /See:/ 'superChatEventListResponse' smart constructor.
data SuperChatEventListResponse =
SuperChatEventListResponse'
{ _scelrEtag :: !(Maybe Text)
, _scelrTokenPagination :: !(Maybe TokenPagination)
, _scelrNextPageToken :: !(Maybe Text)
, _scelrPageInfo :: !(Maybe PageInfo)
, _scelrKind :: !Text
, _scelrItems :: !(Maybe [SuperChatEvent])
, _scelrVisitorId :: !(Maybe Text)
, _scelrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SuperChatEventListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scelrEtag'
--
-- * 'scelrTokenPagination'
--
-- * 'scelrNextPageToken'
--
-- * 'scelrPageInfo'
--
-- * 'scelrKind'
--
-- * 'scelrItems'
--
-- * 'scelrVisitorId'
--
-- * 'scelrEventId'
superChatEventListResponse
:: SuperChatEventListResponse
superChatEventListResponse =
SuperChatEventListResponse'
{ _scelrEtag = Nothing
, _scelrTokenPagination = Nothing
, _scelrNextPageToken = Nothing
, _scelrPageInfo = Nothing
, _scelrKind = "youtube#superChatEventListResponse"
, _scelrItems = Nothing
, _scelrVisitorId = Nothing
, _scelrEventId = Nothing
}
-- | Etag of this resource.
scelrEtag :: Lens' SuperChatEventListResponse (Maybe Text)
scelrEtag
= lens _scelrEtag (\ s a -> s{_scelrEtag = a})
scelrTokenPagination :: Lens' SuperChatEventListResponse (Maybe TokenPagination)
scelrTokenPagination
= lens _scelrTokenPagination
(\ s a -> s{_scelrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
scelrNextPageToken :: Lens' SuperChatEventListResponse (Maybe Text)
scelrNextPageToken
= lens _scelrNextPageToken
(\ s a -> s{_scelrNextPageToken = a})
scelrPageInfo :: Lens' SuperChatEventListResponse (Maybe PageInfo)
scelrPageInfo
= lens _scelrPageInfo
(\ s a -> s{_scelrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#superChatEventListResponse\".
scelrKind :: Lens' SuperChatEventListResponse Text
scelrKind
= lens _scelrKind (\ s a -> s{_scelrKind = a})
-- | A list of Super Chat purchases that match the request criteria.
scelrItems :: Lens' SuperChatEventListResponse [SuperChatEvent]
scelrItems
= lens _scelrItems (\ s a -> s{_scelrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
scelrVisitorId :: Lens' SuperChatEventListResponse (Maybe Text)
scelrVisitorId
= lens _scelrVisitorId
(\ s a -> s{_scelrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
scelrEventId :: Lens' SuperChatEventListResponse (Maybe Text)
scelrEventId
= lens _scelrEventId (\ s a -> s{_scelrEventId = a})
instance FromJSON SuperChatEventListResponse where
parseJSON
= withObject "SuperChatEventListResponse"
(\ o ->
SuperChatEventListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!=
"youtube#superChatEventListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON SuperChatEventListResponse where
toJSON SuperChatEventListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _scelrEtag,
("tokenPagination" .=) <$> _scelrTokenPagination,
("nextPageToken" .=) <$> _scelrNextPageToken,
("pageInfo" .=) <$> _scelrPageInfo,
Just ("kind" .= _scelrKind),
("items" .=) <$> _scelrItems,
("visitorId" .=) <$> _scelrVisitorId,
("eventId" .=) <$> _scelrEventId])
--
-- /See:/ 'videoAbuseReportReasonListResponse' smart constructor.
data VideoAbuseReportReasonListResponse =
VideoAbuseReportReasonListResponse'
{ _varrlrEtag :: !(Maybe Text)
, _varrlrKind :: !Text
, _varrlrItems :: !(Maybe [VideoAbuseReportReason])
, _varrlrVisitorId :: !(Maybe Text)
, _varrlrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoAbuseReportReasonListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'varrlrEtag'
--
-- * 'varrlrKind'
--
-- * 'varrlrItems'
--
-- * 'varrlrVisitorId'
--
-- * 'varrlrEventId'
videoAbuseReportReasonListResponse
:: VideoAbuseReportReasonListResponse
videoAbuseReportReasonListResponse =
VideoAbuseReportReasonListResponse'
{ _varrlrEtag = Nothing
, _varrlrKind = "youtube#videoAbuseReportReasonListResponse"
, _varrlrItems = Nothing
, _varrlrVisitorId = Nothing
, _varrlrEventId = Nothing
}
-- | Etag of this resource.
varrlrEtag :: Lens' VideoAbuseReportReasonListResponse (Maybe Text)
varrlrEtag
= lens _varrlrEtag (\ s a -> s{_varrlrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \`\"youtube#videoAbuseReportReasonListResponse\"\`.
varrlrKind :: Lens' VideoAbuseReportReasonListResponse Text
varrlrKind
= lens _varrlrKind (\ s a -> s{_varrlrKind = a})
-- | A list of valid abuse reasons that are used with \`video.ReportAbuse\`.
varrlrItems :: Lens' VideoAbuseReportReasonListResponse [VideoAbuseReportReason]
varrlrItems
= lens _varrlrItems (\ s a -> s{_varrlrItems = a}) .
_Default
. _Coerce
-- | The \`visitorId\` identifies the visitor.
varrlrVisitorId :: Lens' VideoAbuseReportReasonListResponse (Maybe Text)
varrlrVisitorId
= lens _varrlrVisitorId
(\ s a -> s{_varrlrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
varrlrEventId :: Lens' VideoAbuseReportReasonListResponse (Maybe Text)
varrlrEventId
= lens _varrlrEventId
(\ s a -> s{_varrlrEventId = a})
instance FromJSON VideoAbuseReportReasonListResponse
where
parseJSON
= withObject "VideoAbuseReportReasonListResponse"
(\ o ->
VideoAbuseReportReasonListResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!=
"youtube#videoAbuseReportReasonListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON VideoAbuseReportReasonListResponse
where
toJSON VideoAbuseReportReasonListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _varrlrEtag,
Just ("kind" .= _varrlrKind),
("items" .=) <$> _varrlrItems,
("visitorId" .=) <$> _varrlrVisitorId,
("eventId" .=) <$> _varrlrEventId])
--
-- /See:/ 'liveChatUserBannedMessageDetails' smart constructor.
data LiveChatUserBannedMessageDetails =
LiveChatUserBannedMessageDetails'
{ _lcubmdBanType :: !(Maybe LiveChatUserBannedMessageDetailsBanType)
, _lcubmdBannedUserDetails :: !(Maybe ChannelProFileDetails)
, _lcubmdBanDurationSeconds :: !(Maybe (Textual Word64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatUserBannedMessageDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcubmdBanType'
--
-- * 'lcubmdBannedUserDetails'
--
-- * 'lcubmdBanDurationSeconds'
liveChatUserBannedMessageDetails
:: LiveChatUserBannedMessageDetails
liveChatUserBannedMessageDetails =
LiveChatUserBannedMessageDetails'
{ _lcubmdBanType = Nothing
, _lcubmdBannedUserDetails = Nothing
, _lcubmdBanDurationSeconds = Nothing
}
-- | The type of ban.
lcubmdBanType :: Lens' LiveChatUserBannedMessageDetails (Maybe LiveChatUserBannedMessageDetailsBanType)
lcubmdBanType
= lens _lcubmdBanType
(\ s a -> s{_lcubmdBanType = a})
-- | The details of the user that was banned.
lcubmdBannedUserDetails :: Lens' LiveChatUserBannedMessageDetails (Maybe ChannelProFileDetails)
lcubmdBannedUserDetails
= lens _lcubmdBannedUserDetails
(\ s a -> s{_lcubmdBannedUserDetails = a})
-- | The duration of the ban. This property is only present if the banType is
-- temporary.
lcubmdBanDurationSeconds :: Lens' LiveChatUserBannedMessageDetails (Maybe Word64)
lcubmdBanDurationSeconds
= lens _lcubmdBanDurationSeconds
(\ s a -> s{_lcubmdBanDurationSeconds = a})
. mapping _Coerce
instance FromJSON LiveChatUserBannedMessageDetails
where
parseJSON
= withObject "LiveChatUserBannedMessageDetails"
(\ o ->
LiveChatUserBannedMessageDetails' <$>
(o .:? "banType") <*> (o .:? "bannedUserDetails") <*>
(o .:? "banDurationSeconds"))
instance ToJSON LiveChatUserBannedMessageDetails
where
toJSON LiveChatUserBannedMessageDetails'{..}
= object
(catMaybes
[("banType" .=) <$> _lcubmdBanType,
("bannedUserDetails" .=) <$>
_lcubmdBannedUserDetails,
("banDurationSeconds" .=) <$>
_lcubmdBanDurationSeconds])
-- | Detailed settings of a broadcast.
--
-- /See:/ 'liveBroadcastContentDetails' smart constructor.
data LiveBroadcastContentDetails =
LiveBroadcastContentDetails'
{ _lbcdEnableContentEncryption :: !(Maybe Bool)
, _lbcdEnableLowLatency :: !(Maybe Bool)
, _lbcdLatencyPreference :: !(Maybe LiveBroadcastContentDetailsLatencyPreference)
, _lbcdEnableAutoStop :: !(Maybe Bool)
, _lbcdClosedCaptionsType :: !(Maybe LiveBroadcastContentDetailsClosedCaptionsType)
, _lbcdEnableEmbed :: !(Maybe Bool)
, _lbcdStartWithSlate :: !(Maybe Bool)
, _lbcdProjection :: !(Maybe LiveBroadcastContentDetailsProjection)
, _lbcdMonitorStream :: !(Maybe MonitorStreamInfo)
, _lbcdStereoLayout :: !(Maybe LiveBroadcastContentDetailsStereoLayout)
, _lbcdBoundStreamId :: !(Maybe Text)
, _lbcdRecordFromStart :: !(Maybe Bool)
, _lbcdMesh :: !(Maybe Bytes)
, _lbcdEnableClosedCaptions :: !(Maybe Bool)
, _lbcdEnableAutoStart :: !(Maybe Bool)
, _lbcdBoundStreamLastUpdateTimeMs :: !(Maybe DateTime')
, _lbcdEnableDvr :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbcdEnableContentEncryption'
--
-- * 'lbcdEnableLowLatency'
--
-- * 'lbcdLatencyPreference'
--
-- * 'lbcdEnableAutoStop'
--
-- * 'lbcdClosedCaptionsType'
--
-- * 'lbcdEnableEmbed'
--
-- * 'lbcdStartWithSlate'
--
-- * 'lbcdProjection'
--
-- * 'lbcdMonitorStream'
--
-- * 'lbcdStereoLayout'
--
-- * 'lbcdBoundStreamId'
--
-- * 'lbcdRecordFromStart'
--
-- * 'lbcdMesh'
--
-- * 'lbcdEnableClosedCaptions'
--
-- * 'lbcdEnableAutoStart'
--
-- * 'lbcdBoundStreamLastUpdateTimeMs'
--
-- * 'lbcdEnableDvr'
liveBroadcastContentDetails
:: LiveBroadcastContentDetails
liveBroadcastContentDetails =
LiveBroadcastContentDetails'
{ _lbcdEnableContentEncryption = Nothing
, _lbcdEnableLowLatency = Nothing
, _lbcdLatencyPreference = Nothing
, _lbcdEnableAutoStop = Nothing
, _lbcdClosedCaptionsType = Nothing
, _lbcdEnableEmbed = Nothing
, _lbcdStartWithSlate = Nothing
, _lbcdProjection = Nothing
, _lbcdMonitorStream = Nothing
, _lbcdStereoLayout = Nothing
, _lbcdBoundStreamId = Nothing
, _lbcdRecordFromStart = Nothing
, _lbcdMesh = Nothing
, _lbcdEnableClosedCaptions = Nothing
, _lbcdEnableAutoStart = Nothing
, _lbcdBoundStreamLastUpdateTimeMs = Nothing
, _lbcdEnableDvr = Nothing
}
-- | This setting indicates whether YouTube should enable content encryption
-- for the broadcast.
lbcdEnableContentEncryption :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableContentEncryption
= lens _lbcdEnableContentEncryption
(\ s a -> s{_lbcdEnableContentEncryption = a})
-- | Indicates whether this broadcast has low latency enabled.
lbcdEnableLowLatency :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableLowLatency
= lens _lbcdEnableLowLatency
(\ s a -> s{_lbcdEnableLowLatency = a})
-- | If both this and enable_low_latency are set, they must match.
-- LATENCY_NORMAL should match enable_low_latency=false LATENCY_LOW should
-- match enable_low_latency=true LATENCY_ULTRA_LOW should have
-- enable_low_latency omitted.
lbcdLatencyPreference :: Lens' LiveBroadcastContentDetails (Maybe LiveBroadcastContentDetailsLatencyPreference)
lbcdLatencyPreference
= lens _lbcdLatencyPreference
(\ s a -> s{_lbcdLatencyPreference = a})
-- | This setting indicates whether auto stop is enabled for this broadcast.
-- The default value for this property is false. This setting can only be
-- used by Events.
lbcdEnableAutoStop :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableAutoStop
= lens _lbcdEnableAutoStop
(\ s a -> s{_lbcdEnableAutoStop = a})
lbcdClosedCaptionsType :: Lens' LiveBroadcastContentDetails (Maybe LiveBroadcastContentDetailsClosedCaptionsType)
lbcdClosedCaptionsType
= lens _lbcdClosedCaptionsType
(\ s a -> s{_lbcdClosedCaptionsType = a})
-- | This setting indicates whether the broadcast video can be played in an
-- embedded player. If you choose to archive the video (using the
-- enableArchive property), this setting will also apply to the archived
-- video.
lbcdEnableEmbed :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableEmbed
= lens _lbcdEnableEmbed
(\ s a -> s{_lbcdEnableEmbed = a})
-- | This setting indicates whether the broadcast should automatically begin
-- with an in-stream slate when you update the broadcast\'s status to live.
-- After updating the status, you then need to send a liveCuepoints.insert
-- request that sets the cuepoint\'s eventState to end to remove the
-- in-stream slate and make your broadcast stream visible to viewers.
lbcdStartWithSlate :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdStartWithSlate
= lens _lbcdStartWithSlate
(\ s a -> s{_lbcdStartWithSlate = a})
-- | The projection format of this broadcast. This defaults to rectangular.
lbcdProjection :: Lens' LiveBroadcastContentDetails (Maybe LiveBroadcastContentDetailsProjection)
lbcdProjection
= lens _lbcdProjection
(\ s a -> s{_lbcdProjection = a})
-- | The monitorStream object contains information about the monitor stream,
-- which the broadcaster can use to review the event content before the
-- broadcast stream is shown publicly.
lbcdMonitorStream :: Lens' LiveBroadcastContentDetails (Maybe MonitorStreamInfo)
lbcdMonitorStream
= lens _lbcdMonitorStream
(\ s a -> s{_lbcdMonitorStream = a})
-- | The 3D stereo layout of this broadcast. This defaults to mono.
lbcdStereoLayout :: Lens' LiveBroadcastContentDetails (Maybe LiveBroadcastContentDetailsStereoLayout)
lbcdStereoLayout
= lens _lbcdStereoLayout
(\ s a -> s{_lbcdStereoLayout = a})
-- | This value uniquely identifies the live stream bound to the broadcast.
lbcdBoundStreamId :: Lens' LiveBroadcastContentDetails (Maybe Text)
lbcdBoundStreamId
= lens _lbcdBoundStreamId
(\ s a -> s{_lbcdBoundStreamId = a})
-- | Automatically start recording after the event goes live. The default
-- value for this property is true. *Important:* You must also set the
-- enableDvr property\'s value to true if you want the playback to be
-- available immediately after the broadcast ends. If you set this
-- property\'s value to true but do not also set the enableDvr property to
-- true, there may be a delay of around one day before the archived video
-- will be available for playback.
lbcdRecordFromStart :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdRecordFromStart
= lens _lbcdRecordFromStart
(\ s a -> s{_lbcdRecordFromStart = a})
-- | The mesh for projecting the video if projection is mesh. The mesh value
-- must be a UTF-8 string containing the base-64 encoding of 3D mesh data
-- that follows the Spherical Video V2 RFC specification for an mshp box,
-- excluding the box size and type but including the following four
-- reserved zero bytes for the version and flags.
lbcdMesh :: Lens' LiveBroadcastContentDetails (Maybe ByteString)
lbcdMesh
= lens _lbcdMesh (\ s a -> s{_lbcdMesh = a}) .
mapping _Bytes
-- | This setting indicates whether HTTP POST closed captioning is enabled
-- for this broadcast. The ingestion URL of the closed captions is returned
-- through the liveStreams API. This is mutually exclusive with using the
-- closed_captions_type property, and is equivalent to setting
-- closed_captions_type to CLOSED_CAPTIONS_HTTP_POST.
lbcdEnableClosedCaptions :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableClosedCaptions
= lens _lbcdEnableClosedCaptions
(\ s a -> s{_lbcdEnableClosedCaptions = a})
-- | This setting indicates whether auto start is enabled for this broadcast.
-- The default value for this property is false. This setting can only be
-- used by Events.
lbcdEnableAutoStart :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableAutoStart
= lens _lbcdEnableAutoStart
(\ s a -> s{_lbcdEnableAutoStart = a})
-- | The date and time that the live stream referenced by boundStreamId was
-- last updated.
lbcdBoundStreamLastUpdateTimeMs :: Lens' LiveBroadcastContentDetails (Maybe UTCTime)
lbcdBoundStreamLastUpdateTimeMs
= lens _lbcdBoundStreamLastUpdateTimeMs
(\ s a -> s{_lbcdBoundStreamLastUpdateTimeMs = a})
. mapping _DateTime
-- | This setting determines whether viewers can access DVR controls while
-- watching the video. DVR controls enable the viewer to control the video
-- playback experience by pausing, rewinding, or fast forwarding content.
-- The default value for this property is true. *Important:* You must set
-- the value to true and also set the enableArchive property\'s value to
-- true if you want to make playback available immediately after the
-- broadcast ends.
lbcdEnableDvr :: Lens' LiveBroadcastContentDetails (Maybe Bool)
lbcdEnableDvr
= lens _lbcdEnableDvr
(\ s a -> s{_lbcdEnableDvr = a})
instance FromJSON LiveBroadcastContentDetails where
parseJSON
= withObject "LiveBroadcastContentDetails"
(\ o ->
LiveBroadcastContentDetails' <$>
(o .:? "enableContentEncryption") <*>
(o .:? "enableLowLatency")
<*> (o .:? "latencyPreference")
<*> (o .:? "enableAutoStop")
<*> (o .:? "closedCaptionsType")
<*> (o .:? "enableEmbed")
<*> (o .:? "startWithSlate")
<*> (o .:? "projection")
<*> (o .:? "monitorStream")
<*> (o .:? "stereoLayout")
<*> (o .:? "boundStreamId")
<*> (o .:? "recordFromStart")
<*> (o .:? "mesh")
<*> (o .:? "enableClosedCaptions")
<*> (o .:? "enableAutoStart")
<*> (o .:? "boundStreamLastUpdateTimeMs")
<*> (o .:? "enableDvr"))
instance ToJSON LiveBroadcastContentDetails where
toJSON LiveBroadcastContentDetails'{..}
= object
(catMaybes
[("enableContentEncryption" .=) <$>
_lbcdEnableContentEncryption,
("enableLowLatency" .=) <$> _lbcdEnableLowLatency,
("latencyPreference" .=) <$> _lbcdLatencyPreference,
("enableAutoStop" .=) <$> _lbcdEnableAutoStop,
("closedCaptionsType" .=) <$>
_lbcdClosedCaptionsType,
("enableEmbed" .=) <$> _lbcdEnableEmbed,
("startWithSlate" .=) <$> _lbcdStartWithSlate,
("projection" .=) <$> _lbcdProjection,
("monitorStream" .=) <$> _lbcdMonitorStream,
("stereoLayout" .=) <$> _lbcdStereoLayout,
("boundStreamId" .=) <$> _lbcdBoundStreamId,
("recordFromStart" .=) <$> _lbcdRecordFromStart,
("mesh" .=) <$> _lbcdMesh,
("enableClosedCaptions" .=) <$>
_lbcdEnableClosedCaptions,
("enableAutoStart" .=) <$> _lbcdEnableAutoStart,
("boundStreamLastUpdateTimeMs" .=) <$>
_lbcdBoundStreamLastUpdateTimeMs,
("enableDvr" .=) <$> _lbcdEnableDvr])
--
-- /See:/ 'channelSection' smart constructor.
data ChannelSection =
ChannelSection'
{ _csEtag :: !(Maybe Text)
, _csSnippet :: !(Maybe ChannelSectionSnippet)
, _csKind :: !Text
, _csContentDetails :: !(Maybe ChannelSectionContentDetails)
, _csTargeting :: !(Maybe ChannelSectionTargeting)
, _csId :: !(Maybe Text)
, _csLocalizations :: !(Maybe ChannelSectionLocalizations)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSection' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csEtag'
--
-- * 'csSnippet'
--
-- * 'csKind'
--
-- * 'csContentDetails'
--
-- * 'csTargeting'
--
-- * 'csId'
--
-- * 'csLocalizations'
channelSection
:: ChannelSection
channelSection =
ChannelSection'
{ _csEtag = Nothing
, _csSnippet = Nothing
, _csKind = "youtube#channelSection"
, _csContentDetails = Nothing
, _csTargeting = Nothing
, _csId = Nothing
, _csLocalizations = Nothing
}
-- | Etag of this resource.
csEtag :: Lens' ChannelSection (Maybe Text)
csEtag = lens _csEtag (\ s a -> s{_csEtag = a})
-- | The snippet object contains basic details about the channel section,
-- such as its type, style and title.
csSnippet :: Lens' ChannelSection (Maybe ChannelSectionSnippet)
csSnippet
= lens _csSnippet (\ s a -> s{_csSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#channelSection\".
csKind :: Lens' ChannelSection Text
csKind = lens _csKind (\ s a -> s{_csKind = a})
-- | The contentDetails object contains details about the channel section
-- content, such as a list of playlists or channels featured in the
-- section.
csContentDetails :: Lens' ChannelSection (Maybe ChannelSectionContentDetails)
csContentDetails
= lens _csContentDetails
(\ s a -> s{_csContentDetails = a})
-- | The targeting object contains basic targeting settings about the channel
-- section.
csTargeting :: Lens' ChannelSection (Maybe ChannelSectionTargeting)
csTargeting
= lens _csTargeting (\ s a -> s{_csTargeting = a})
-- | The ID that YouTube uses to uniquely identify the channel section.
csId :: Lens' ChannelSection (Maybe Text)
csId = lens _csId (\ s a -> s{_csId = a})
-- | Localizations for different languages
csLocalizations :: Lens' ChannelSection (Maybe ChannelSectionLocalizations)
csLocalizations
= lens _csLocalizations
(\ s a -> s{_csLocalizations = a})
instance FromJSON ChannelSection where
parseJSON
= withObject "ChannelSection"
(\ o ->
ChannelSection' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#channelSection")
<*> (o .:? "contentDetails")
<*> (o .:? "targeting")
<*> (o .:? "id")
<*> (o .:? "localizations"))
instance ToJSON ChannelSection where
toJSON ChannelSection'{..}
= object
(catMaybes
[("etag" .=) <$> _csEtag,
("snippet" .=) <$> _csSnippet,
Just ("kind" .= _csKind),
("contentDetails" .=) <$> _csContentDetails,
("targeting" .=) <$> _csTargeting,
("id" .=) <$> _csId,
("localizations" .=) <$> _csLocalizations])
--
-- /See:/ 'channelContentDetailsRelatedPlayLists' smart constructor.
data ChannelContentDetailsRelatedPlayLists =
ChannelContentDetailsRelatedPlayLists'
{ _ccdrplFavorites :: !(Maybe Text)
, _ccdrplWatchHistory :: !(Maybe Text)
, _ccdrplWatchLater :: !(Maybe Text)
, _ccdrplUploads :: !(Maybe Text)
, _ccdrplLikes :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelContentDetailsRelatedPlayLists' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccdrplFavorites'
--
-- * 'ccdrplWatchHistory'
--
-- * 'ccdrplWatchLater'
--
-- * 'ccdrplUploads'
--
-- * 'ccdrplLikes'
channelContentDetailsRelatedPlayLists
:: ChannelContentDetailsRelatedPlayLists
channelContentDetailsRelatedPlayLists =
ChannelContentDetailsRelatedPlayLists'
{ _ccdrplFavorites = Nothing
, _ccdrplWatchHistory = Nothing
, _ccdrplWatchLater = Nothing
, _ccdrplUploads = Nothing
, _ccdrplLikes = Nothing
}
-- | The ID of the playlist that contains the channel\"s favorite videos. Use
-- the playlistItems.insert and playlistItems.delete to add or remove items
-- from that list.
ccdrplFavorites :: Lens' ChannelContentDetailsRelatedPlayLists (Maybe Text)
ccdrplFavorites
= lens _ccdrplFavorites
(\ s a -> s{_ccdrplFavorites = a})
-- | The ID of the playlist that contains the channel\"s watch history. Use
-- the playlistItems.insert and playlistItems.delete to add or remove items
-- from that list.
ccdrplWatchHistory :: Lens' ChannelContentDetailsRelatedPlayLists (Maybe Text)
ccdrplWatchHistory
= lens _ccdrplWatchHistory
(\ s a -> s{_ccdrplWatchHistory = a})
-- | The ID of the playlist that contains the channel\"s watch later
-- playlist. Use the playlistItems.insert and playlistItems.delete to add
-- or remove items from that list.
ccdrplWatchLater :: Lens' ChannelContentDetailsRelatedPlayLists (Maybe Text)
ccdrplWatchLater
= lens _ccdrplWatchLater
(\ s a -> s{_ccdrplWatchLater = a})
-- | The ID of the playlist that contains the channel\"s uploaded videos. Use
-- the videos.insert method to upload new videos and the videos.delete
-- method to delete previously uploaded videos.
ccdrplUploads :: Lens' ChannelContentDetailsRelatedPlayLists (Maybe Text)
ccdrplUploads
= lens _ccdrplUploads
(\ s a -> s{_ccdrplUploads = a})
-- | The ID of the playlist that contains the channel\"s liked videos. Use
-- the playlistItems.insert and playlistItems.delete to add or remove items
-- from that list.
ccdrplLikes :: Lens' ChannelContentDetailsRelatedPlayLists (Maybe Text)
ccdrplLikes
= lens _ccdrplLikes (\ s a -> s{_ccdrplLikes = a})
instance FromJSON
ChannelContentDetailsRelatedPlayLists
where
parseJSON
= withObject "ChannelContentDetailsRelatedPlayLists"
(\ o ->
ChannelContentDetailsRelatedPlayLists' <$>
(o .:? "favorites") <*> (o .:? "watchHistory") <*>
(o .:? "watchLater")
<*> (o .:? "uploads")
<*> (o .:? "likes"))
instance ToJSON ChannelContentDetailsRelatedPlayLists
where
toJSON ChannelContentDetailsRelatedPlayLists'{..}
= object
(catMaybes
[("favorites" .=) <$> _ccdrplFavorites,
("watchHistory" .=) <$> _ccdrplWatchHistory,
("watchLater" .=) <$> _ccdrplWatchLater,
("uploads" .=) <$> _ccdrplUploads,
("likes" .=) <$> _ccdrplLikes])
-- | A live stream describes a live ingestion point.
--
-- /See:/ 'liveStream' smart constructor.
data LiveStream =
LiveStream'
{ _lsStatus :: !(Maybe LiveStreamStatus)
, _lsEtag :: !(Maybe Text)
, _lsSnippet :: !(Maybe LiveStreamSnippet)
, _lsKind :: !Text
, _lsContentDetails :: !(Maybe LiveStreamContentDetails)
, _lsId :: !(Maybe Text)
, _lsCdn :: !(Maybe CdnSettings)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStream' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lsStatus'
--
-- * 'lsEtag'
--
-- * 'lsSnippet'
--
-- * 'lsKind'
--
-- * 'lsContentDetails'
--
-- * 'lsId'
--
-- * 'lsCdn'
liveStream
:: LiveStream
liveStream =
LiveStream'
{ _lsStatus = Nothing
, _lsEtag = Nothing
, _lsSnippet = Nothing
, _lsKind = "youtube#liveStream"
, _lsContentDetails = Nothing
, _lsId = Nothing
, _lsCdn = Nothing
}
-- | The status object contains information about live stream\'s status.
lsStatus :: Lens' LiveStream (Maybe LiveStreamStatus)
lsStatus = lens _lsStatus (\ s a -> s{_lsStatus = a})
-- | Etag of this resource.
lsEtag :: Lens' LiveStream (Maybe Text)
lsEtag = lens _lsEtag (\ s a -> s{_lsEtag = a})
-- | The snippet object contains basic details about the stream, including
-- its channel, title, and description.
lsSnippet :: Lens' LiveStream (Maybe LiveStreamSnippet)
lsSnippet
= lens _lsSnippet (\ s a -> s{_lsSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveStream\".
lsKind :: Lens' LiveStream Text
lsKind = lens _lsKind (\ s a -> s{_lsKind = a})
-- | The content_details object contains information about the stream,
-- including the closed captions ingestion URL.
lsContentDetails :: Lens' LiveStream (Maybe LiveStreamContentDetails)
lsContentDetails
= lens _lsContentDetails
(\ s a -> s{_lsContentDetails = a})
-- | The ID that YouTube assigns to uniquely identify the stream.
lsId :: Lens' LiveStream (Maybe Text)
lsId = lens _lsId (\ s a -> s{_lsId = a})
-- | The cdn object defines the live stream\'s content delivery network (CDN)
-- settings. These settings provide details about the manner in which you
-- stream your content to YouTube.
lsCdn :: Lens' LiveStream (Maybe CdnSettings)
lsCdn = lens _lsCdn (\ s a -> s{_lsCdn = a})
instance FromJSON LiveStream where
parseJSON
= withObject "LiveStream"
(\ o ->
LiveStream' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#liveStream")
<*> (o .:? "contentDetails")
<*> (o .:? "id")
<*> (o .:? "cdn"))
instance ToJSON LiveStream where
toJSON LiveStream'{..}
= object
(catMaybes
[("status" .=) <$> _lsStatus,
("etag" .=) <$> _lsEtag,
("snippet" .=) <$> _lsSnippet,
Just ("kind" .= _lsKind),
("contentDetails" .=) <$> _lsContentDetails,
("id" .=) <$> _lsId, ("cdn" .=) <$> _lsCdn])
-- | Information about a video that was marked as a favorite video.
--
-- /See:/ 'activityContentDetailsFavorite' smart constructor.
newtype ActivityContentDetailsFavorite =
ActivityContentDetailsFavorite'
{ _acdfResourceId :: Maybe ResourceId
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsFavorite' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdfResourceId'
activityContentDetailsFavorite
:: ActivityContentDetailsFavorite
activityContentDetailsFavorite =
ActivityContentDetailsFavorite' {_acdfResourceId = Nothing}
-- | The resourceId object contains information that identifies the resource
-- that was marked as a favorite.
acdfResourceId :: Lens' ActivityContentDetailsFavorite (Maybe ResourceId)
acdfResourceId
= lens _acdfResourceId
(\ s a -> s{_acdfResourceId = a})
instance FromJSON ActivityContentDetailsFavorite
where
parseJSON
= withObject "ActivityContentDetailsFavorite"
(\ o ->
ActivityContentDetailsFavorite' <$>
(o .:? "resourceId"))
instance ToJSON ActivityContentDetailsFavorite where
toJSON ActivityContentDetailsFavorite'{..}
= object
(catMaybes [("resourceId" .=) <$> _acdfResourceId])
-- | Details about the content of a YouTube Video.
--
-- /See:/ 'videoContentDetails' smart constructor.
data VideoContentDetails =
VideoContentDetails'
{ _vcdCountryRestriction :: !(Maybe AccessPolicy)
, _vcdHasCustomThumbnail :: !(Maybe Bool)
, _vcdDefinition :: !(Maybe VideoContentDetailsDefinition)
, _vcdDimension :: !(Maybe Text)
, _vcdCaption :: !(Maybe VideoContentDetailsCaption)
, _vcdRegionRestriction :: !(Maybe VideoContentDetailsRegionRestriction)
, _vcdProjection :: !(Maybe VideoContentDetailsProjection)
, _vcdDuration :: !(Maybe Text)
, _vcdContentRating :: !(Maybe ContentRating)
, _vcdLicensedContent :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vcdCountryRestriction'
--
-- * 'vcdHasCustomThumbnail'
--
-- * 'vcdDefinition'
--
-- * 'vcdDimension'
--
-- * 'vcdCaption'
--
-- * 'vcdRegionRestriction'
--
-- * 'vcdProjection'
--
-- * 'vcdDuration'
--
-- * 'vcdContentRating'
--
-- * 'vcdLicensedContent'
videoContentDetails
:: VideoContentDetails
videoContentDetails =
VideoContentDetails'
{ _vcdCountryRestriction = Nothing
, _vcdHasCustomThumbnail = Nothing
, _vcdDefinition = Nothing
, _vcdDimension = Nothing
, _vcdCaption = Nothing
, _vcdRegionRestriction = Nothing
, _vcdProjection = Nothing
, _vcdDuration = Nothing
, _vcdContentRating = Nothing
, _vcdLicensedContent = Nothing
}
-- | The countryRestriction object contains information about the countries
-- where a video is (or is not) viewable.
vcdCountryRestriction :: Lens' VideoContentDetails (Maybe AccessPolicy)
vcdCountryRestriction
= lens _vcdCountryRestriction
(\ s a -> s{_vcdCountryRestriction = a})
-- | Indicates whether the video uploader has provided a custom thumbnail
-- image for the video. This property is only visible to the video
-- uploader.
vcdHasCustomThumbnail :: Lens' VideoContentDetails (Maybe Bool)
vcdHasCustomThumbnail
= lens _vcdHasCustomThumbnail
(\ s a -> s{_vcdHasCustomThumbnail = a})
-- | The value of definition indicates whether the video is available in high
-- definition or only in standard definition.
vcdDefinition :: Lens' VideoContentDetails (Maybe VideoContentDetailsDefinition)
vcdDefinition
= lens _vcdDefinition
(\ s a -> s{_vcdDefinition = a})
-- | The value of dimension indicates whether the video is available in 3D or
-- in 2D.
vcdDimension :: Lens' VideoContentDetails (Maybe Text)
vcdDimension
= lens _vcdDimension (\ s a -> s{_vcdDimension = a})
-- | The value of captions indicates whether the video has captions or not.
vcdCaption :: Lens' VideoContentDetails (Maybe VideoContentDetailsCaption)
vcdCaption
= lens _vcdCaption (\ s a -> s{_vcdCaption = a})
-- | The regionRestriction object contains information about the countries
-- where a video is (or is not) viewable. The object will contain either
-- the contentDetails.regionRestriction.allowed property or the
-- contentDetails.regionRestriction.blocked property.
vcdRegionRestriction :: Lens' VideoContentDetails (Maybe VideoContentDetailsRegionRestriction)
vcdRegionRestriction
= lens _vcdRegionRestriction
(\ s a -> s{_vcdRegionRestriction = a})
-- | Specifies the projection format of the video.
vcdProjection :: Lens' VideoContentDetails (Maybe VideoContentDetailsProjection)
vcdProjection
= lens _vcdProjection
(\ s a -> s{_vcdProjection = a})
-- | The length of the video. The tag value is an ISO 8601 duration in the
-- format PT#M#S, in which the letters PT indicate that the value specifies
-- a period of time, and the letters M and S refer to length in minutes and
-- seconds, respectively. The # characters preceding the M and S letters
-- are both integers that specify the number of minutes (or seconds) of the
-- video. For example, a value of PT15M51S indicates that the video is 15
-- minutes and 51 seconds long.
vcdDuration :: Lens' VideoContentDetails (Maybe Text)
vcdDuration
= lens _vcdDuration (\ s a -> s{_vcdDuration = a})
-- | Specifies the ratings that the video received under various rating
-- schemes.
vcdContentRating :: Lens' VideoContentDetails (Maybe ContentRating)
vcdContentRating
= lens _vcdContentRating
(\ s a -> s{_vcdContentRating = a})
-- | The value of is_license_content indicates whether the video is licensed
-- content.
vcdLicensedContent :: Lens' VideoContentDetails (Maybe Bool)
vcdLicensedContent
= lens _vcdLicensedContent
(\ s a -> s{_vcdLicensedContent = a})
instance FromJSON VideoContentDetails where
parseJSON
= withObject "VideoContentDetails"
(\ o ->
VideoContentDetails' <$>
(o .:? "countryRestriction") <*>
(o .:? "hasCustomThumbnail")
<*> (o .:? "definition")
<*> (o .:? "dimension")
<*> (o .:? "caption")
<*> (o .:? "regionRestriction")
<*> (o .:? "projection")
<*> (o .:? "duration")
<*> (o .:? "contentRating")
<*> (o .:? "licensedContent"))
instance ToJSON VideoContentDetails where
toJSON VideoContentDetails'{..}
= object
(catMaybes
[("countryRestriction" .=) <$>
_vcdCountryRestriction,
("hasCustomThumbnail" .=) <$> _vcdHasCustomThumbnail,
("definition" .=) <$> _vcdDefinition,
("dimension" .=) <$> _vcdDimension,
("caption" .=) <$> _vcdCaption,
("regionRestriction" .=) <$> _vcdRegionRestriction,
("projection" .=) <$> _vcdProjection,
("duration" .=) <$> _vcdDuration,
("contentRating" .=) <$> _vcdContentRating,
("licensedContent" .=) <$> _vcdLicensedContent])
-- | Branding properties for images associated with the channel.
--
-- /See:/ 'imageSettings' smart constructor.
data ImageSettings =
ImageSettings'
{ _isBannerMobileLowImageURL :: !(Maybe Text)
, _isBannerTabletExtraHdImageURL :: !(Maybe Text)
, _isSmallBrandedBannerImageImapScript :: !(Maybe LocalizedProperty)
, _isBannerTvHighImageURL :: !(Maybe Text)
, _isBannerMobileHdImageURL :: !(Maybe Text)
, _isBannerTvMediumImageURL :: !(Maybe Text)
, _isBannerTvImageURL :: !(Maybe Text)
, _isBannerTabletImageURL :: !(Maybe Text)
, _isBannerMobileImageURL :: !(Maybe Text)
, _isTrackingImageURL :: !(Maybe Text)
, _isBannerMobileMediumHdImageURL :: !(Maybe Text)
, _isLargeBrandedBannerImageURL :: !(Maybe LocalizedProperty)
, _isBannerExternalURL :: !(Maybe Text)
, _isBackgRoundImageURL :: !(Maybe LocalizedProperty)
, _isSmallBrandedBannerImageURL :: !(Maybe LocalizedProperty)
, _isBannerImageURL :: !(Maybe Text)
, _isWatchIconImageURL :: !(Maybe Text)
, _isBannerTvLowImageURL :: !(Maybe Text)
, _isBannerMobileExtraHdImageURL :: !(Maybe Text)
, _isLargeBrandedBannerImageImapScript :: !(Maybe LocalizedProperty)
, _isBannerTabletLowImageURL :: !(Maybe Text)
, _isBannerTabletHdImageURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ImageSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'isBannerMobileLowImageURL'
--
-- * 'isBannerTabletExtraHdImageURL'
--
-- * 'isSmallBrandedBannerImageImapScript'
--
-- * 'isBannerTvHighImageURL'
--
-- * 'isBannerMobileHdImageURL'
--
-- * 'isBannerTvMediumImageURL'
--
-- * 'isBannerTvImageURL'
--
-- * 'isBannerTabletImageURL'
--
-- * 'isBannerMobileImageURL'
--
-- * 'isTrackingImageURL'
--
-- * 'isBannerMobileMediumHdImageURL'
--
-- * 'isLargeBrandedBannerImageURL'
--
-- * 'isBannerExternalURL'
--
-- * 'isBackgRoundImageURL'
--
-- * 'isSmallBrandedBannerImageURL'
--
-- * 'isBannerImageURL'
--
-- * 'isWatchIconImageURL'
--
-- * 'isBannerTvLowImageURL'
--
-- * 'isBannerMobileExtraHdImageURL'
--
-- * 'isLargeBrandedBannerImageImapScript'
--
-- * 'isBannerTabletLowImageURL'
--
-- * 'isBannerTabletHdImageURL'
imageSettings
:: ImageSettings
imageSettings =
ImageSettings'
{ _isBannerMobileLowImageURL = Nothing
, _isBannerTabletExtraHdImageURL = Nothing
, _isSmallBrandedBannerImageImapScript = Nothing
, _isBannerTvHighImageURL = Nothing
, _isBannerMobileHdImageURL = Nothing
, _isBannerTvMediumImageURL = Nothing
, _isBannerTvImageURL = Nothing
, _isBannerTabletImageURL = Nothing
, _isBannerMobileImageURL = Nothing
, _isTrackingImageURL = Nothing
, _isBannerMobileMediumHdImageURL = Nothing
, _isLargeBrandedBannerImageURL = Nothing
, _isBannerExternalURL = Nothing
, _isBackgRoundImageURL = Nothing
, _isSmallBrandedBannerImageURL = Nothing
, _isBannerImageURL = Nothing
, _isWatchIconImageURL = Nothing
, _isBannerTvLowImageURL = Nothing
, _isBannerMobileExtraHdImageURL = Nothing
, _isLargeBrandedBannerImageImapScript = Nothing
, _isBannerTabletLowImageURL = Nothing
, _isBannerTabletHdImageURL = Nothing
}
-- | Banner image. Mobile size low resolution (320x88).
isBannerMobileLowImageURL :: Lens' ImageSettings (Maybe Text)
isBannerMobileLowImageURL
= lens _isBannerMobileLowImageURL
(\ s a -> s{_isBannerMobileLowImageURL = a})
-- | Banner image. Tablet size extra high resolution (2560x424).
isBannerTabletExtraHdImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTabletExtraHdImageURL
= lens _isBannerTabletExtraHdImageURL
(\ s a -> s{_isBannerTabletExtraHdImageURL = a})
-- | The image map script for the small banner image.
isSmallBrandedBannerImageImapScript :: Lens' ImageSettings (Maybe LocalizedProperty)
isSmallBrandedBannerImageImapScript
= lens _isSmallBrandedBannerImageImapScript
(\ s a ->
s{_isSmallBrandedBannerImageImapScript = a})
-- | Banner image. TV size high resolution (1920x1080).
isBannerTvHighImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTvHighImageURL
= lens _isBannerTvHighImageURL
(\ s a -> s{_isBannerTvHighImageURL = a})
-- | Banner image. Mobile size high resolution (1280x360).
isBannerMobileHdImageURL :: Lens' ImageSettings (Maybe Text)
isBannerMobileHdImageURL
= lens _isBannerMobileHdImageURL
(\ s a -> s{_isBannerMobileHdImageURL = a})
-- | Banner image. TV size medium resolution (1280x720).
isBannerTvMediumImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTvMediumImageURL
= lens _isBannerTvMediumImageURL
(\ s a -> s{_isBannerTvMediumImageURL = a})
-- | Banner image. TV size extra high resolution (2120x1192).
isBannerTvImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTvImageURL
= lens _isBannerTvImageURL
(\ s a -> s{_isBannerTvImageURL = a})
-- | Banner image. Tablet size (1707x283).
isBannerTabletImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTabletImageURL
= lens _isBannerTabletImageURL
(\ s a -> s{_isBannerTabletImageURL = a})
-- | Banner image. Mobile size (640x175).
isBannerMobileImageURL :: Lens' ImageSettings (Maybe Text)
isBannerMobileImageURL
= lens _isBannerMobileImageURL
(\ s a -> s{_isBannerMobileImageURL = a})
-- | The URL for a 1px by 1px tracking pixel that can be used to collect
-- statistics for views of the channel or video pages.
isTrackingImageURL :: Lens' ImageSettings (Maybe Text)
isTrackingImageURL
= lens _isTrackingImageURL
(\ s a -> s{_isTrackingImageURL = a})
-- | Banner image. Mobile size medium\/high resolution (960x263).
isBannerMobileMediumHdImageURL :: Lens' ImageSettings (Maybe Text)
isBannerMobileMediumHdImageURL
= lens _isBannerMobileMediumHdImageURL
(\ s a -> s{_isBannerMobileMediumHdImageURL = a})
-- | The URL for the 854px by 70px image that appears below the video player
-- in the expanded video view of the video watch page.
isLargeBrandedBannerImageURL :: Lens' ImageSettings (Maybe LocalizedProperty)
isLargeBrandedBannerImageURL
= lens _isLargeBrandedBannerImageURL
(\ s a -> s{_isLargeBrandedBannerImageURL = a})
-- | This is generated when a ChannelBanner.Insert request has succeeded for
-- the given channel.
isBannerExternalURL :: Lens' ImageSettings (Maybe Text)
isBannerExternalURL
= lens _isBannerExternalURL
(\ s a -> s{_isBannerExternalURL = a})
-- | The URL for the background image shown on the video watch page. The
-- image should be 1200px by 615px, with a maximum file size of 128k.
isBackgRoundImageURL :: Lens' ImageSettings (Maybe LocalizedProperty)
isBackgRoundImageURL
= lens _isBackgRoundImageURL
(\ s a -> s{_isBackgRoundImageURL = a})
-- | The URL for the 640px by 70px banner image that appears below the video
-- player in the default view of the video watch page. The URL for the
-- image that appears above the top-left corner of the video player. This
-- is a 25-pixel-high image with a flexible width that cannot exceed 170
-- pixels.
isSmallBrandedBannerImageURL :: Lens' ImageSettings (Maybe LocalizedProperty)
isSmallBrandedBannerImageURL
= lens _isSmallBrandedBannerImageURL
(\ s a -> s{_isSmallBrandedBannerImageURL = a})
-- | Banner image. Desktop size (1060x175).
isBannerImageURL :: Lens' ImageSettings (Maybe Text)
isBannerImageURL
= lens _isBannerImageURL
(\ s a -> s{_isBannerImageURL = a})
isWatchIconImageURL :: Lens' ImageSettings (Maybe Text)
isWatchIconImageURL
= lens _isWatchIconImageURL
(\ s a -> s{_isWatchIconImageURL = a})
-- | Banner image. TV size low resolution (854x480).
isBannerTvLowImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTvLowImageURL
= lens _isBannerTvLowImageURL
(\ s a -> s{_isBannerTvLowImageURL = a})
-- | Banner image. Mobile size high resolution (1440x395).
isBannerMobileExtraHdImageURL :: Lens' ImageSettings (Maybe Text)
isBannerMobileExtraHdImageURL
= lens _isBannerMobileExtraHdImageURL
(\ s a -> s{_isBannerMobileExtraHdImageURL = a})
-- | The image map script for the large banner image.
isLargeBrandedBannerImageImapScript :: Lens' ImageSettings (Maybe LocalizedProperty)
isLargeBrandedBannerImageImapScript
= lens _isLargeBrandedBannerImageImapScript
(\ s a ->
s{_isLargeBrandedBannerImageImapScript = a})
-- | Banner image. Tablet size low resolution (1138x188).
isBannerTabletLowImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTabletLowImageURL
= lens _isBannerTabletLowImageURL
(\ s a -> s{_isBannerTabletLowImageURL = a})
-- | Banner image. Tablet size high resolution (2276x377).
isBannerTabletHdImageURL :: Lens' ImageSettings (Maybe Text)
isBannerTabletHdImageURL
= lens _isBannerTabletHdImageURL
(\ s a -> s{_isBannerTabletHdImageURL = a})
instance FromJSON ImageSettings where
parseJSON
= withObject "ImageSettings"
(\ o ->
ImageSettings' <$>
(o .:? "bannerMobileLowImageUrl") <*>
(o .:? "bannerTabletExtraHdImageUrl")
<*> (o .:? "smallBrandedBannerImageImapScript")
<*> (o .:? "bannerTvHighImageUrl")
<*> (o .:? "bannerMobileHdImageUrl")
<*> (o .:? "bannerTvMediumImageUrl")
<*> (o .:? "bannerTvImageUrl")
<*> (o .:? "bannerTabletImageUrl")
<*> (o .:? "bannerMobileImageUrl")
<*> (o .:? "trackingImageUrl")
<*> (o .:? "bannerMobileMediumHdImageUrl")
<*> (o .:? "largeBrandedBannerImageUrl")
<*> (o .:? "bannerExternalUrl")
<*> (o .:? "backgroundImageUrl")
<*> (o .:? "smallBrandedBannerImageUrl")
<*> (o .:? "bannerImageUrl")
<*> (o .:? "watchIconImageUrl")
<*> (o .:? "bannerTvLowImageUrl")
<*> (o .:? "bannerMobileExtraHdImageUrl")
<*> (o .:? "largeBrandedBannerImageImapScript")
<*> (o .:? "bannerTabletLowImageUrl")
<*> (o .:? "bannerTabletHdImageUrl"))
instance ToJSON ImageSettings where
toJSON ImageSettings'{..}
= object
(catMaybes
[("bannerMobileLowImageUrl" .=) <$>
_isBannerMobileLowImageURL,
("bannerTabletExtraHdImageUrl" .=) <$>
_isBannerTabletExtraHdImageURL,
("smallBrandedBannerImageImapScript" .=) <$>
_isSmallBrandedBannerImageImapScript,
("bannerTvHighImageUrl" .=) <$>
_isBannerTvHighImageURL,
("bannerMobileHdImageUrl" .=) <$>
_isBannerMobileHdImageURL,
("bannerTvMediumImageUrl" .=) <$>
_isBannerTvMediumImageURL,
("bannerTvImageUrl" .=) <$> _isBannerTvImageURL,
("bannerTabletImageUrl" .=) <$>
_isBannerTabletImageURL,
("bannerMobileImageUrl" .=) <$>
_isBannerMobileImageURL,
("trackingImageUrl" .=) <$> _isTrackingImageURL,
("bannerMobileMediumHdImageUrl" .=) <$>
_isBannerMobileMediumHdImageURL,
("largeBrandedBannerImageUrl" .=) <$>
_isLargeBrandedBannerImageURL,
("bannerExternalUrl" .=) <$> _isBannerExternalURL,
("backgroundImageUrl" .=) <$> _isBackgRoundImageURL,
("smallBrandedBannerImageUrl" .=) <$>
_isSmallBrandedBannerImageURL,
("bannerImageUrl" .=) <$> _isBannerImageURL,
("watchIconImageUrl" .=) <$> _isWatchIconImageURL,
("bannerTvLowImageUrl" .=) <$>
_isBannerTvLowImageURL,
("bannerMobileExtraHdImageUrl" .=) <$>
_isBannerMobileExtraHdImageURL,
("largeBrandedBannerImageImapScript" .=) <$>
_isLargeBrandedBannerImageImapScript,
("bannerTabletLowImageUrl" .=) <$>
_isBannerTabletLowImageURL,
("bannerTabletHdImageUrl" .=) <$>
_isBannerTabletHdImageURL])
-- | Freebase topic information related to the video.
--
-- /See:/ 'videoTopicDetails' smart constructor.
data VideoTopicDetails =
VideoTopicDetails'
{ _vtdTopicIds :: !(Maybe [Text])
, _vtdRelevantTopicIds :: !(Maybe [Text])
, _vtdTopicCategories :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoTopicDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vtdTopicIds'
--
-- * 'vtdRelevantTopicIds'
--
-- * 'vtdTopicCategories'
videoTopicDetails
:: VideoTopicDetails
videoTopicDetails =
VideoTopicDetails'
{ _vtdTopicIds = Nothing
, _vtdRelevantTopicIds = Nothing
, _vtdTopicCategories = Nothing
}
-- | A list of Freebase topic IDs that are centrally associated with the
-- video. These are topics that are centrally featured in the video, and it
-- can be said that the video is mainly about each of these. You can
-- retrieve information about each topic using the \< a
-- href=\"http:\/\/wiki.freebase.com\/wiki\/Topic_API\">Freebase Topic API.
vtdTopicIds :: Lens' VideoTopicDetails [Text]
vtdTopicIds
= lens _vtdTopicIds (\ s a -> s{_vtdTopicIds = a}) .
_Default
. _Coerce
-- | Similar to topic_id, except that these topics are merely relevant to the
-- video. These are topics that may be mentioned in, or appear in the
-- video. You can retrieve information about each topic using Freebase
-- Topic API.
vtdRelevantTopicIds :: Lens' VideoTopicDetails [Text]
vtdRelevantTopicIds
= lens _vtdRelevantTopicIds
(\ s a -> s{_vtdRelevantTopicIds = a})
. _Default
. _Coerce
-- | A list of Wikipedia URLs that provide a high-level description of the
-- video\'s content.
vtdTopicCategories :: Lens' VideoTopicDetails [Text]
vtdTopicCategories
= lens _vtdTopicCategories
(\ s a -> s{_vtdTopicCategories = a})
. _Default
. _Coerce
instance FromJSON VideoTopicDetails where
parseJSON
= withObject "VideoTopicDetails"
(\ o ->
VideoTopicDetails' <$>
(o .:? "topicIds" .!= mempty) <*>
(o .:? "relevantTopicIds" .!= mempty)
<*> (o .:? "topicCategories" .!= mempty))
instance ToJSON VideoTopicDetails where
toJSON VideoTopicDetails'{..}
= object
(catMaybes
[("topicIds" .=) <$> _vtdTopicIds,
("relevantTopicIds" .=) <$> _vtdRelevantTopicIds,
("topicCategories" .=) <$> _vtdTopicCategories])
-- | Information about a resource that received a comment.
--
-- /See:/ 'activityContentDetailsComment' smart constructor.
newtype ActivityContentDetailsComment =
ActivityContentDetailsComment'
{ _acdcResourceId :: Maybe ResourceId
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsComment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdcResourceId'
activityContentDetailsComment
:: ActivityContentDetailsComment
activityContentDetailsComment =
ActivityContentDetailsComment' {_acdcResourceId = Nothing}
-- | The resourceId object contains information that identifies the resource
-- associated with the comment.
acdcResourceId :: Lens' ActivityContentDetailsComment (Maybe ResourceId)
acdcResourceId
= lens _acdcResourceId
(\ s a -> s{_acdcResourceId = a})
instance FromJSON ActivityContentDetailsComment where
parseJSON
= withObject "ActivityContentDetailsComment"
(\ o ->
ActivityContentDetailsComment' <$>
(o .:? "resourceId"))
instance ToJSON ActivityContentDetailsComment where
toJSON ActivityContentDetailsComment'{..}
= object
(catMaybes [("resourceId" .=) <$> _acdcResourceId])
-- | A *third party account link* resource represents a link between a
-- YouTube account or a channel and an account on a third-party service.
--
-- /See:/ 'thirdPartyLink' smart constructor.
data ThirdPartyLink =
ThirdPartyLink'
{ _tplStatus :: !(Maybe ThirdPartyLinkStatus)
, _tplEtag :: !(Maybe Text)
, _tplSnippet :: !(Maybe ThirdPartyLinkSnippet)
, _tplKind :: !Text
, _tplLinkingToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ThirdPartyLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tplStatus'
--
-- * 'tplEtag'
--
-- * 'tplSnippet'
--
-- * 'tplKind'
--
-- * 'tplLinkingToken'
thirdPartyLink
:: ThirdPartyLink
thirdPartyLink =
ThirdPartyLink'
{ _tplStatus = Nothing
, _tplEtag = Nothing
, _tplSnippet = Nothing
, _tplKind = "youtube#thirdPartyLink"
, _tplLinkingToken = Nothing
}
-- | The status object contains information about the status of the link.
tplStatus :: Lens' ThirdPartyLink (Maybe ThirdPartyLinkStatus)
tplStatus
= lens _tplStatus (\ s a -> s{_tplStatus = a})
-- | Etag of this resource
tplEtag :: Lens' ThirdPartyLink (Maybe Text)
tplEtag = lens _tplEtag (\ s a -> s{_tplEtag = a})
-- | The snippet object contains basic details about the third- party account
-- link.
tplSnippet :: Lens' ThirdPartyLink (Maybe ThirdPartyLinkSnippet)
tplSnippet
= lens _tplSnippet (\ s a -> s{_tplSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#thirdPartyLink\".
tplKind :: Lens' ThirdPartyLink Text
tplKind = lens _tplKind (\ s a -> s{_tplKind = a})
-- | The linking_token identifies a YouTube account and channel with which
-- the third party account is linked.
tplLinkingToken :: Lens' ThirdPartyLink (Maybe Text)
tplLinkingToken
= lens _tplLinkingToken
(\ s a -> s{_tplLinkingToken = a})
instance FromJSON ThirdPartyLink where
parseJSON
= withObject "ThirdPartyLink"
(\ o ->
ThirdPartyLink' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#thirdPartyLink")
<*> (o .:? "linkingToken"))
instance ToJSON ThirdPartyLink where
toJSON ThirdPartyLink'{..}
= object
(catMaybes
[("status" .=) <$> _tplStatus,
("etag" .=) <$> _tplEtag,
("snippet" .=) <$> _tplSnippet,
Just ("kind" .= _tplKind),
("linkingToken" .=) <$> _tplLinkingToken])
-- | Live broadcast state.
--
-- /See:/ 'liveBroadcastStatus' smart constructor.
data LiveBroadcastStatus =
LiveBroadcastStatus'
{ _lbsLiveBroadcastPriority :: !(Maybe LiveBroadcastStatusLiveBroadcastPriority)
, _lbsRecordingStatus :: !(Maybe LiveBroadcastStatusRecordingStatus)
, _lbsLifeCycleStatus :: !(Maybe LiveBroadcastStatusLifeCycleStatus)
, _lbsPrivacyStatus :: !(Maybe LiveBroadcastStatusPrivacyStatus)
, _lbsSelfDeclaredMadeForKids :: !(Maybe Bool)
, _lbsMadeForKids :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbsLiveBroadcastPriority'
--
-- * 'lbsRecordingStatus'
--
-- * 'lbsLifeCycleStatus'
--
-- * 'lbsPrivacyStatus'
--
-- * 'lbsSelfDeclaredMadeForKids'
--
-- * 'lbsMadeForKids'
liveBroadcastStatus
:: LiveBroadcastStatus
liveBroadcastStatus =
LiveBroadcastStatus'
{ _lbsLiveBroadcastPriority = Nothing
, _lbsRecordingStatus = Nothing
, _lbsLifeCycleStatus = Nothing
, _lbsPrivacyStatus = Nothing
, _lbsSelfDeclaredMadeForKids = Nothing
, _lbsMadeForKids = Nothing
}
-- | Priority of the live broadcast event (internal state).
lbsLiveBroadcastPriority :: Lens' LiveBroadcastStatus (Maybe LiveBroadcastStatusLiveBroadcastPriority)
lbsLiveBroadcastPriority
= lens _lbsLiveBroadcastPriority
(\ s a -> s{_lbsLiveBroadcastPriority = a})
-- | The broadcast\'s recording status.
lbsRecordingStatus :: Lens' LiveBroadcastStatus (Maybe LiveBroadcastStatusRecordingStatus)
lbsRecordingStatus
= lens _lbsRecordingStatus
(\ s a -> s{_lbsRecordingStatus = a})
-- | The broadcast\'s status. The status can be updated using the API\'s
-- liveBroadcasts.transition method.
lbsLifeCycleStatus :: Lens' LiveBroadcastStatus (Maybe LiveBroadcastStatusLifeCycleStatus)
lbsLifeCycleStatus
= lens _lbsLifeCycleStatus
(\ s a -> s{_lbsLifeCycleStatus = a})
-- | The broadcast\'s privacy status. Note that the broadcast represents
-- exactly one YouTube video, so the privacy settings are identical to
-- those supported for videos. In addition, you can set this field by
-- modifying the broadcast resource or by setting the privacyStatus field
-- of the corresponding video resource.
lbsPrivacyStatus :: Lens' LiveBroadcastStatus (Maybe LiveBroadcastStatusPrivacyStatus)
lbsPrivacyStatus
= lens _lbsPrivacyStatus
(\ s a -> s{_lbsPrivacyStatus = a})
-- | This field will be set to True if the creator declares the broadcast to
-- be kids only: go\/live-cw-work.
lbsSelfDeclaredMadeForKids :: Lens' LiveBroadcastStatus (Maybe Bool)
lbsSelfDeclaredMadeForKids
= lens _lbsSelfDeclaredMadeForKids
(\ s a -> s{_lbsSelfDeclaredMadeForKids = a})
-- | Whether the broadcast is made for kids or not, decided by YouTube
-- instead of the creator. This field is read only.
lbsMadeForKids :: Lens' LiveBroadcastStatus (Maybe Bool)
lbsMadeForKids
= lens _lbsMadeForKids
(\ s a -> s{_lbsMadeForKids = a})
instance FromJSON LiveBroadcastStatus where
parseJSON
= withObject "LiveBroadcastStatus"
(\ o ->
LiveBroadcastStatus' <$>
(o .:? "liveBroadcastPriority") <*>
(o .:? "recordingStatus")
<*> (o .:? "lifeCycleStatus")
<*> (o .:? "privacyStatus")
<*> (o .:? "selfDeclaredMadeForKids")
<*> (o .:? "madeForKids"))
instance ToJSON LiveBroadcastStatus where
toJSON LiveBroadcastStatus'{..}
= object
(catMaybes
[("liveBroadcastPriority" .=) <$>
_lbsLiveBroadcastPriority,
("recordingStatus" .=) <$> _lbsRecordingStatus,
("lifeCycleStatus" .=) <$> _lbsLifeCycleStatus,
("privacyStatus" .=) <$> _lbsPrivacyStatus,
("selfDeclaredMadeForKids" .=) <$>
_lbsSelfDeclaredMadeForKids,
("madeForKids" .=) <$> _lbsMadeForKids])
-- | Information about the uploaded video.
--
-- /See:/ 'activityContentDetailsUpload' smart constructor.
newtype ActivityContentDetailsUpload =
ActivityContentDetailsUpload'
{ _acduVideoId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsUpload' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acduVideoId'
activityContentDetailsUpload
:: ActivityContentDetailsUpload
activityContentDetailsUpload =
ActivityContentDetailsUpload' {_acduVideoId = Nothing}
-- | The ID that YouTube uses to uniquely identify the uploaded video.
acduVideoId :: Lens' ActivityContentDetailsUpload (Maybe Text)
acduVideoId
= lens _acduVideoId (\ s a -> s{_acduVideoId = a})
instance FromJSON ActivityContentDetailsUpload where
parseJSON
= withObject "ActivityContentDetailsUpload"
(\ o ->
ActivityContentDetailsUpload' <$> (o .:? "videoId"))
instance ToJSON ActivityContentDetailsUpload where
toJSON ActivityContentDetailsUpload'{..}
= object
(catMaybes [("videoId" .=) <$> _acduVideoId])
-- | Information about a new playlist item.
--
-- /See:/ 'activityContentDetailsPlayListItem' smart constructor.
data ActivityContentDetailsPlayListItem =
ActivityContentDetailsPlayListItem'
{ _acdpliResourceId :: !(Maybe ResourceId)
, _acdpliPlayListId :: !(Maybe Text)
, _acdpliPlayListItemId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsPlayListItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdpliResourceId'
--
-- * 'acdpliPlayListId'
--
-- * 'acdpliPlayListItemId'
activityContentDetailsPlayListItem
:: ActivityContentDetailsPlayListItem
activityContentDetailsPlayListItem =
ActivityContentDetailsPlayListItem'
{ _acdpliResourceId = Nothing
, _acdpliPlayListId = Nothing
, _acdpliPlayListItemId = Nothing
}
-- | The resourceId object contains information about the resource that was
-- added to the playlist.
acdpliResourceId :: Lens' ActivityContentDetailsPlayListItem (Maybe ResourceId)
acdpliResourceId
= lens _acdpliResourceId
(\ s a -> s{_acdpliResourceId = a})
-- | The value that YouTube uses to uniquely identify the playlist.
acdpliPlayListId :: Lens' ActivityContentDetailsPlayListItem (Maybe Text)
acdpliPlayListId
= lens _acdpliPlayListId
(\ s a -> s{_acdpliPlayListId = a})
-- | ID of the item within the playlist.
acdpliPlayListItemId :: Lens' ActivityContentDetailsPlayListItem (Maybe Text)
acdpliPlayListItemId
= lens _acdpliPlayListItemId
(\ s a -> s{_acdpliPlayListItemId = a})
instance FromJSON ActivityContentDetailsPlayListItem
where
parseJSON
= withObject "ActivityContentDetailsPlayListItem"
(\ o ->
ActivityContentDetailsPlayListItem' <$>
(o .:? "resourceId") <*> (o .:? "playlistId") <*>
(o .:? "playlistItemId"))
instance ToJSON ActivityContentDetailsPlayListItem
where
toJSON ActivityContentDetailsPlayListItem'{..}
= object
(catMaybes
[("resourceId" .=) <$> _acdpliResourceId,
("playlistId" .=) <$> _acdpliPlayListId,
("playlistItemId" .=) <$> _acdpliPlayListItemId])
--
-- /See:/ 'superStickerMetadata' smart constructor.
data SuperStickerMetadata =
SuperStickerMetadata'
{ _ssmAltText :: !(Maybe Text)
, _ssmStickerId :: !(Maybe Text)
, _ssmAltTextLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SuperStickerMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ssmAltText'
--
-- * 'ssmStickerId'
--
-- * 'ssmAltTextLanguage'
superStickerMetadata
:: SuperStickerMetadata
superStickerMetadata =
SuperStickerMetadata'
{ _ssmAltText = Nothing
, _ssmStickerId = Nothing
, _ssmAltTextLanguage = Nothing
}
-- | Internationalized alt text that describes the sticker image and any
-- animation associated with it.
ssmAltText :: Lens' SuperStickerMetadata (Maybe Text)
ssmAltText
= lens _ssmAltText (\ s a -> s{_ssmAltText = a})
-- | Unique identifier of the Super Sticker. This is a shorter form of the
-- alt_text that includes pack name and a recognizable characteristic of
-- the sticker.
ssmStickerId :: Lens' SuperStickerMetadata (Maybe Text)
ssmStickerId
= lens _ssmStickerId (\ s a -> s{_ssmStickerId = a})
-- | Specifies the localization language in which the alt text is returned.
ssmAltTextLanguage :: Lens' SuperStickerMetadata (Maybe Text)
ssmAltTextLanguage
= lens _ssmAltTextLanguage
(\ s a -> s{_ssmAltTextLanguage = a})
instance FromJSON SuperStickerMetadata where
parseJSON
= withObject "SuperStickerMetadata"
(\ o ->
SuperStickerMetadata' <$>
(o .:? "altText") <*> (o .:? "stickerId") <*>
(o .:? "altTextLanguage"))
instance ToJSON SuperStickerMetadata where
toJSON SuperStickerMetadata'{..}
= object
(catMaybes
[("altText" .=) <$> _ssmAltText,
("stickerId" .=) <$> _ssmStickerId,
("altTextLanguage" .=) <$> _ssmAltTextLanguage])
-- | Details about a social network post.
--
-- /See:/ 'activityContentDetailsSocial' smart constructor.
data ActivityContentDetailsSocial =
ActivityContentDetailsSocial'
{ _acdsResourceId :: !(Maybe ResourceId)
, _acdsImageURL :: !(Maybe Text)
, _acdsAuthor :: !(Maybe Text)
, _acdsReferenceURL :: !(Maybe Text)
, _acdsType :: !(Maybe ActivityContentDetailsSocialType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsSocial' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdsResourceId'
--
-- * 'acdsImageURL'
--
-- * 'acdsAuthor'
--
-- * 'acdsReferenceURL'
--
-- * 'acdsType'
activityContentDetailsSocial
:: ActivityContentDetailsSocial
activityContentDetailsSocial =
ActivityContentDetailsSocial'
{ _acdsResourceId = Nothing
, _acdsImageURL = Nothing
, _acdsAuthor = Nothing
, _acdsReferenceURL = Nothing
, _acdsType = Nothing
}
-- | The resourceId object encapsulates information that identifies the
-- resource associated with a social network post.
acdsResourceId :: Lens' ActivityContentDetailsSocial (Maybe ResourceId)
acdsResourceId
= lens _acdsResourceId
(\ s a -> s{_acdsResourceId = a})
-- | An image of the post\'s author.
acdsImageURL :: Lens' ActivityContentDetailsSocial (Maybe Text)
acdsImageURL
= lens _acdsImageURL (\ s a -> s{_acdsImageURL = a})
-- | The author of the social network post.
acdsAuthor :: Lens' ActivityContentDetailsSocial (Maybe Text)
acdsAuthor
= lens _acdsAuthor (\ s a -> s{_acdsAuthor = a})
-- | The URL of the social network post.
acdsReferenceURL :: Lens' ActivityContentDetailsSocial (Maybe Text)
acdsReferenceURL
= lens _acdsReferenceURL
(\ s a -> s{_acdsReferenceURL = a})
-- | The name of the social network.
acdsType :: Lens' ActivityContentDetailsSocial (Maybe ActivityContentDetailsSocialType)
acdsType = lens _acdsType (\ s a -> s{_acdsType = a})
instance FromJSON ActivityContentDetailsSocial where
parseJSON
= withObject "ActivityContentDetailsSocial"
(\ o ->
ActivityContentDetailsSocial' <$>
(o .:? "resourceId") <*> (o .:? "imageUrl") <*>
(o .:? "author")
<*> (o .:? "referenceUrl")
<*> (o .:? "type"))
instance ToJSON ActivityContentDetailsSocial where
toJSON ActivityContentDetailsSocial'{..}
= object
(catMaybes
[("resourceId" .=) <$> _acdsResourceId,
("imageUrl" .=) <$> _acdsImageURL,
("author" .=) <$> _acdsAuthor,
("referenceUrl" .=) <$> _acdsReferenceURL,
("type" .=) <$> _acdsType])
-- | A \`__liveChatBan__\` resource represents a ban for a YouTube live chat.
--
-- /See:/ 'liveChatBan' smart constructor.
data LiveChatBan =
LiveChatBan'
{ _lcbEtag :: !(Maybe Text)
, _lcbSnippet :: !(Maybe LiveChatBanSnippet)
, _lcbKind :: !Text
, _lcbId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatBan' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcbEtag'
--
-- * 'lcbSnippet'
--
-- * 'lcbKind'
--
-- * 'lcbId'
liveChatBan
:: LiveChatBan
liveChatBan =
LiveChatBan'
{ _lcbEtag = Nothing
, _lcbSnippet = Nothing
, _lcbKind = "youtube#liveChatBan"
, _lcbId = Nothing
}
-- | Etag of this resource.
lcbEtag :: Lens' LiveChatBan (Maybe Text)
lcbEtag = lens _lcbEtag (\ s a -> s{_lcbEtag = a})
-- | The \`snippet\` object contains basic details about the ban.
lcbSnippet :: Lens' LiveChatBan (Maybe LiveChatBanSnippet)
lcbSnippet
= lens _lcbSnippet (\ s a -> s{_lcbSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \`\"youtube#liveChatBan\"\`.
lcbKind :: Lens' LiveChatBan Text
lcbKind = lens _lcbKind (\ s a -> s{_lcbKind = a})
-- | The ID that YouTube assigns to uniquely identify the ban.
lcbId :: Lens' LiveChatBan (Maybe Text)
lcbId = lens _lcbId (\ s a -> s{_lcbId = a})
instance FromJSON LiveChatBan where
parseJSON
= withObject "LiveChatBan"
(\ o ->
LiveChatBan' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#liveChatBan")
<*> (o .:? "id"))
instance ToJSON LiveChatBan where
toJSON LiveChatBan'{..}
= object
(catMaybes
[("etag" .=) <$> _lcbEtag,
("snippet" .=) <$> _lcbSnippet,
Just ("kind" .= _lcbKind), ("id" .=) <$> _lcbId])
-- | Information about a channel that a user subscribed to.
--
-- /See:/ 'activityContentDetailsSubscription' smart constructor.
newtype ActivityContentDetailsSubscription =
ActivityContentDetailsSubscription'
{ _aResourceId :: Maybe ResourceId
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsSubscription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aResourceId'
activityContentDetailsSubscription
:: ActivityContentDetailsSubscription
activityContentDetailsSubscription =
ActivityContentDetailsSubscription' {_aResourceId = Nothing}
-- | The resourceId object contains information that identifies the resource
-- that the user subscribed to.
aResourceId :: Lens' ActivityContentDetailsSubscription (Maybe ResourceId)
aResourceId
= lens _aResourceId (\ s a -> s{_aResourceId = a})
instance FromJSON ActivityContentDetailsSubscription
where
parseJSON
= withObject "ActivityContentDetailsSubscription"
(\ o ->
ActivityContentDetailsSubscription' <$>
(o .:? "resourceId"))
instance ToJSON ActivityContentDetailsSubscription
where
toJSON ActivityContentDetailsSubscription'{..}
= object
(catMaybes [("resourceId" .=) <$> _aResourceId])
-- | Information about a resource that received a positive (like) rating.
--
-- /See:/ 'activityContentDetailsLike' smart constructor.
newtype ActivityContentDetailsLike =
ActivityContentDetailsLike'
{ _acdlResourceId :: Maybe ResourceId
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsLike' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdlResourceId'
activityContentDetailsLike
:: ActivityContentDetailsLike
activityContentDetailsLike =
ActivityContentDetailsLike' {_acdlResourceId = Nothing}
-- | The resourceId object contains information that identifies the rated
-- resource.
acdlResourceId :: Lens' ActivityContentDetailsLike (Maybe ResourceId)
acdlResourceId
= lens _acdlResourceId
(\ s a -> s{_acdlResourceId = a})
instance FromJSON ActivityContentDetailsLike where
parseJSON
= withObject "ActivityContentDetailsLike"
(\ o ->
ActivityContentDetailsLike' <$> (o .:? "resourceId"))
instance ToJSON ActivityContentDetailsLike where
toJSON ActivityContentDetailsLike'{..}
= object
(catMaybes [("resourceId" .=) <$> _acdlResourceId])
--
-- /See:/ 'playListContentDetails' smart constructor.
newtype PlayListContentDetails =
PlayListContentDetails'
{ _plcdItemCount :: Maybe (Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plcdItemCount'
playListContentDetails
:: PlayListContentDetails
playListContentDetails = PlayListContentDetails' {_plcdItemCount = Nothing}
-- | The number of videos in the playlist.
plcdItemCount :: Lens' PlayListContentDetails (Maybe Word32)
plcdItemCount
= lens _plcdItemCount
(\ s a -> s{_plcdItemCount = a})
. mapping _Coerce
instance FromJSON PlayListContentDetails where
parseJSON
= withObject "PlayListContentDetails"
(\ o ->
PlayListContentDetails' <$> (o .:? "itemCount"))
instance ToJSON PlayListContentDetails where
toJSON PlayListContentDetails'{..}
= object
(catMaybes [("itemCount" .=) <$> _plcdItemCount])
--
-- /See:/ 'liveChatSuperChatDetails' smart constructor.
data LiveChatSuperChatDetails =
LiveChatSuperChatDetails'
{ _lcscdUserComment :: !(Maybe Text)
, _lcscdAmountMicros :: !(Maybe (Textual Word64))
, _lcscdAmountDisplayString :: !(Maybe Text)
, _lcscdCurrency :: !(Maybe Text)
, _lcscdTier :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatSuperChatDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcscdUserComment'
--
-- * 'lcscdAmountMicros'
--
-- * 'lcscdAmountDisplayString'
--
-- * 'lcscdCurrency'
--
-- * 'lcscdTier'
liveChatSuperChatDetails
:: LiveChatSuperChatDetails
liveChatSuperChatDetails =
LiveChatSuperChatDetails'
{ _lcscdUserComment = Nothing
, _lcscdAmountMicros = Nothing
, _lcscdAmountDisplayString = Nothing
, _lcscdCurrency = Nothing
, _lcscdTier = Nothing
}
-- | The comment added by the user to this Super Chat event.
lcscdUserComment :: Lens' LiveChatSuperChatDetails (Maybe Text)
lcscdUserComment
= lens _lcscdUserComment
(\ s a -> s{_lcscdUserComment = a})
-- | The amount purchased by the user, in micros (1,750,000 micros = 1.75).
lcscdAmountMicros :: Lens' LiveChatSuperChatDetails (Maybe Word64)
lcscdAmountMicros
= lens _lcscdAmountMicros
(\ s a -> s{_lcscdAmountMicros = a})
. mapping _Coerce
-- | A rendered string that displays the fund amount and currency to the
-- user.
lcscdAmountDisplayString :: Lens' LiveChatSuperChatDetails (Maybe Text)
lcscdAmountDisplayString
= lens _lcscdAmountDisplayString
(\ s a -> s{_lcscdAmountDisplayString = a})
-- | The currency in which the purchase was made.
lcscdCurrency :: Lens' LiveChatSuperChatDetails (Maybe Text)
lcscdCurrency
= lens _lcscdCurrency
(\ s a -> s{_lcscdCurrency = a})
-- | The tier in which the amount belongs. Lower amounts belong to lower
-- tiers. The lowest tier is 1.
lcscdTier :: Lens' LiveChatSuperChatDetails (Maybe Word32)
lcscdTier
= lens _lcscdTier (\ s a -> s{_lcscdTier = a}) .
mapping _Coerce
instance FromJSON LiveChatSuperChatDetails where
parseJSON
= withObject "LiveChatSuperChatDetails"
(\ o ->
LiveChatSuperChatDetails' <$>
(o .:? "userComment") <*> (o .:? "amountMicros") <*>
(o .:? "amountDisplayString")
<*> (o .:? "currency")
<*> (o .:? "tier"))
instance ToJSON LiveChatSuperChatDetails where
toJSON LiveChatSuperChatDetails'{..}
= object
(catMaybes
[("userComment" .=) <$> _lcscdUserComment,
("amountMicros" .=) <$> _lcscdAmountMicros,
("amountDisplayString" .=) <$>
_lcscdAmountDisplayString,
("currency" .=) <$> _lcscdCurrency,
("tier" .=) <$> _lcscdTier])
-- | Paging details for lists of resources, including total number of items
-- available and number of resources returned in a single page.
--
-- /See:/ 'pageInfo' smart constructor.
data PageInfo =
PageInfo'
{ _piResultsPerPage :: !(Maybe (Textual Int32))
, _piTotalResults :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PageInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'piResultsPerPage'
--
-- * 'piTotalResults'
pageInfo
:: PageInfo
pageInfo = PageInfo' {_piResultsPerPage = Nothing, _piTotalResults = Nothing}
-- | The number of results included in the API response.
piResultsPerPage :: Lens' PageInfo (Maybe Int32)
piResultsPerPage
= lens _piResultsPerPage
(\ s a -> s{_piResultsPerPage = a})
. mapping _Coerce
-- | The total number of results in the result set.
piTotalResults :: Lens' PageInfo (Maybe Int32)
piTotalResults
= lens _piTotalResults
(\ s a -> s{_piTotalResults = a})
. mapping _Coerce
instance FromJSON PageInfo where
parseJSON
= withObject "PageInfo"
(\ o ->
PageInfo' <$>
(o .:? "resultsPerPage") <*> (o .:? "totalResults"))
instance ToJSON PageInfo where
toJSON PageInfo'{..}
= object
(catMaybes
[("resultsPerPage" .=) <$> _piResultsPerPage,
("totalResults" .=) <$> _piTotalResults])
-- | Basic details about a video category, such as its localized title. Next
-- Id: 17
--
-- /See:/ 'videoStatus' smart constructor.
data VideoStatus =
VideoStatus'
{ _vsFailureReason :: !(Maybe VideoStatusFailureReason)
, _vsPublicStatsViewable :: !(Maybe Bool)
, _vsRejectionReason :: !(Maybe VideoStatusRejectionReason)
, _vsPublishAt :: !(Maybe DateTime')
, _vsUploadStatus :: !(Maybe VideoStatusUploadStatus)
, _vsPrivacyStatus :: !(Maybe VideoStatusPrivacyStatus)
, _vsEmbeddable :: !(Maybe Bool)
, _vsSelfDeclaredMadeForKids :: !(Maybe Bool)
, _vsLicense :: !(Maybe VideoStatusLicense)
, _vsMadeForKids :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vsFailureReason'
--
-- * 'vsPublicStatsViewable'
--
-- * 'vsRejectionReason'
--
-- * 'vsPublishAt'
--
-- * 'vsUploadStatus'
--
-- * 'vsPrivacyStatus'
--
-- * 'vsEmbeddable'
--
-- * 'vsSelfDeclaredMadeForKids'
--
-- * 'vsLicense'
--
-- * 'vsMadeForKids'
videoStatus
:: VideoStatus
videoStatus =
VideoStatus'
{ _vsFailureReason = Nothing
, _vsPublicStatsViewable = Nothing
, _vsRejectionReason = Nothing
, _vsPublishAt = Nothing
, _vsUploadStatus = Nothing
, _vsPrivacyStatus = Nothing
, _vsEmbeddable = Nothing
, _vsSelfDeclaredMadeForKids = Nothing
, _vsLicense = Nothing
, _vsMadeForKids = Nothing
}
-- | This value explains why a video failed to upload. This property is only
-- present if the uploadStatus property indicates that the upload failed.
vsFailureReason :: Lens' VideoStatus (Maybe VideoStatusFailureReason)
vsFailureReason
= lens _vsFailureReason
(\ s a -> s{_vsFailureReason = a})
-- | This value indicates if the extended video statistics on the watch page
-- can be viewed by everyone. Note that the view count, likes, etc will
-- still be visible if this is disabled. \'mutable youtube.videos.insert
-- youtube.videos.update
vsPublicStatsViewable :: Lens' VideoStatus (Maybe Bool)
vsPublicStatsViewable
= lens _vsPublicStatsViewable
(\ s a -> s{_vsPublicStatsViewable = a})
-- | This value explains why YouTube rejected an uploaded video. This
-- property is only present if the uploadStatus property indicates that the
-- upload was rejected.
vsRejectionReason :: Lens' VideoStatus (Maybe VideoStatusRejectionReason)
vsRejectionReason
= lens _vsRejectionReason
(\ s a -> s{_vsRejectionReason = a})
-- | The date and time when the video is scheduled to publish. It can be set
-- only if the privacy status of the video is private..
vsPublishAt :: Lens' VideoStatus (Maybe UTCTime)
vsPublishAt
= lens _vsPublishAt (\ s a -> s{_vsPublishAt = a}) .
mapping _DateTime
-- | The status of the uploaded video.
vsUploadStatus :: Lens' VideoStatus (Maybe VideoStatusUploadStatus)
vsUploadStatus
= lens _vsUploadStatus
(\ s a -> s{_vsUploadStatus = a})
-- | The video\'s privacy status.
vsPrivacyStatus :: Lens' VideoStatus (Maybe VideoStatusPrivacyStatus)
vsPrivacyStatus
= lens _vsPrivacyStatus
(\ s a -> s{_vsPrivacyStatus = a})
-- | This value indicates if the video can be embedded on another website.
-- \'mutable youtube.videos.insert youtube.videos.update
vsEmbeddable :: Lens' VideoStatus (Maybe Bool)
vsEmbeddable
= lens _vsEmbeddable (\ s a -> s{_vsEmbeddable = a})
vsSelfDeclaredMadeForKids :: Lens' VideoStatus (Maybe Bool)
vsSelfDeclaredMadeForKids
= lens _vsSelfDeclaredMadeForKids
(\ s a -> s{_vsSelfDeclaredMadeForKids = a})
-- | The video\'s license. \'mutable youtube.videos.insert
-- youtube.videos.update
vsLicense :: Lens' VideoStatus (Maybe VideoStatusLicense)
vsLicense
= lens _vsLicense (\ s a -> s{_vsLicense = a})
vsMadeForKids :: Lens' VideoStatus (Maybe Bool)
vsMadeForKids
= lens _vsMadeForKids
(\ s a -> s{_vsMadeForKids = a})
instance FromJSON VideoStatus where
parseJSON
= withObject "VideoStatus"
(\ o ->
VideoStatus' <$>
(o .:? "failureReason") <*>
(o .:? "publicStatsViewable")
<*> (o .:? "rejectionReason")
<*> (o .:? "publishAt")
<*> (o .:? "uploadStatus")
<*> (o .:? "privacyStatus")
<*> (o .:? "embeddable")
<*> (o .:? "selfDeclaredMadeForKids")
<*> (o .:? "license")
<*> (o .:? "madeForKids"))
instance ToJSON VideoStatus where
toJSON VideoStatus'{..}
= object
(catMaybes
[("failureReason" .=) <$> _vsFailureReason,
("publicStatsViewable" .=) <$>
_vsPublicStatsViewable,
("rejectionReason" .=) <$> _vsRejectionReason,
("publishAt" .=) <$> _vsPublishAt,
("uploadStatus" .=) <$> _vsUploadStatus,
("privacyStatus" .=) <$> _vsPrivacyStatus,
("embeddable" .=) <$> _vsEmbeddable,
("selfDeclaredMadeForKids" .=) <$>
_vsSelfDeclaredMadeForKids,
("license" .=) <$> _vsLicense,
("madeForKids" .=) <$> _vsMadeForKids])
--
-- /See:/ 'testItemTestItemSnippet' smart constructor.
data TestItemTestItemSnippet =
TestItemTestItemSnippet'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TestItemTestItemSnippet' with the minimum fields required to make a request.
--
testItemTestItemSnippet
:: TestItemTestItemSnippet
testItemTestItemSnippet = TestItemTestItemSnippet'
instance FromJSON TestItemTestItemSnippet where
parseJSON
= withObject "TestItemTestItemSnippet"
(\ o -> pure TestItemTestItemSnippet')
instance ToJSON TestItemTestItemSnippet where
toJSON = const emptyObject
-- | Describes original video file properties, including technical details
-- about audio and video streams, but also metadata information like
-- content length, digitization time, or geotagging information.
--
-- /See:/ 'videoFileDetails' smart constructor.
data VideoFileDetails =
VideoFileDetails'
{ _vfdBitrateBps :: !(Maybe (Textual Word64))
, _vfdCreationTime :: !(Maybe Text)
, _vfdDurationMs :: !(Maybe (Textual Word64))
, _vfdFileSize :: !(Maybe (Textual Word64))
, _vfdFileType :: !(Maybe VideoFileDetailsFileType)
, _vfdContainer :: !(Maybe Text)
, _vfdVideoStreams :: !(Maybe [VideoFileDetailsVideoStream])
, _vfdAudioStreams :: !(Maybe [VideoFileDetailsAudioStream])
, _vfdFileName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoFileDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vfdBitrateBps'
--
-- * 'vfdCreationTime'
--
-- * 'vfdDurationMs'
--
-- * 'vfdFileSize'
--
-- * 'vfdFileType'
--
-- * 'vfdContainer'
--
-- * 'vfdVideoStreams'
--
-- * 'vfdAudioStreams'
--
-- * 'vfdFileName'
videoFileDetails
:: VideoFileDetails
videoFileDetails =
VideoFileDetails'
{ _vfdBitrateBps = Nothing
, _vfdCreationTime = Nothing
, _vfdDurationMs = Nothing
, _vfdFileSize = Nothing
, _vfdFileType = Nothing
, _vfdContainer = Nothing
, _vfdVideoStreams = Nothing
, _vfdAudioStreams = Nothing
, _vfdFileName = Nothing
}
-- | The uploaded video file\'s combined (video and audio) bitrate in bits
-- per second.
vfdBitrateBps :: Lens' VideoFileDetails (Maybe Word64)
vfdBitrateBps
= lens _vfdBitrateBps
(\ s a -> s{_vfdBitrateBps = a})
. mapping _Coerce
-- | The date and time when the uploaded video file was created. The value is
-- specified in ISO 8601 format. Currently, the following ISO 8601 formats
-- are supported: - Date only: YYYY-MM-DD - Naive time: YYYY-MM-DDTHH:MM:SS
-- - Time with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM
vfdCreationTime :: Lens' VideoFileDetails (Maybe Text)
vfdCreationTime
= lens _vfdCreationTime
(\ s a -> s{_vfdCreationTime = a})
-- | The length of the uploaded video in milliseconds.
vfdDurationMs :: Lens' VideoFileDetails (Maybe Word64)
vfdDurationMs
= lens _vfdDurationMs
(\ s a -> s{_vfdDurationMs = a})
. mapping _Coerce
-- | The uploaded file\'s size in bytes. This field is present whether a
-- video file or another type of file was uploaded.
vfdFileSize :: Lens' VideoFileDetails (Maybe Word64)
vfdFileSize
= lens _vfdFileSize (\ s a -> s{_vfdFileSize = a}) .
mapping _Coerce
-- | The uploaded file\'s type as detected by YouTube\'s video processing
-- engine. Currently, YouTube only processes video files, but this field is
-- present whether a video file or another type of file was uploaded.
vfdFileType :: Lens' VideoFileDetails (Maybe VideoFileDetailsFileType)
vfdFileType
= lens _vfdFileType (\ s a -> s{_vfdFileType = a})
-- | The uploaded video file\'s container format.
vfdContainer :: Lens' VideoFileDetails (Maybe Text)
vfdContainer
= lens _vfdContainer (\ s a -> s{_vfdContainer = a})
-- | A list of video streams contained in the uploaded video file. Each item
-- in the list contains detailed metadata about a video stream.
vfdVideoStreams :: Lens' VideoFileDetails [VideoFileDetailsVideoStream]
vfdVideoStreams
= lens _vfdVideoStreams
(\ s a -> s{_vfdVideoStreams = a})
. _Default
. _Coerce
-- | A list of audio streams contained in the uploaded video file. Each item
-- in the list contains detailed metadata about an audio stream.
vfdAudioStreams :: Lens' VideoFileDetails [VideoFileDetailsAudioStream]
vfdAudioStreams
= lens _vfdAudioStreams
(\ s a -> s{_vfdAudioStreams = a})
. _Default
. _Coerce
-- | The uploaded file\'s name. This field is present whether a video file or
-- another type of file was uploaded.
vfdFileName :: Lens' VideoFileDetails (Maybe Text)
vfdFileName
= lens _vfdFileName (\ s a -> s{_vfdFileName = a})
instance FromJSON VideoFileDetails where
parseJSON
= withObject "VideoFileDetails"
(\ o ->
VideoFileDetails' <$>
(o .:? "bitrateBps") <*> (o .:? "creationTime") <*>
(o .:? "durationMs")
<*> (o .:? "fileSize")
<*> (o .:? "fileType")
<*> (o .:? "container")
<*> (o .:? "videoStreams" .!= mempty)
<*> (o .:? "audioStreams" .!= mempty)
<*> (o .:? "fileName"))
instance ToJSON VideoFileDetails where
toJSON VideoFileDetails'{..}
= object
(catMaybes
[("bitrateBps" .=) <$> _vfdBitrateBps,
("creationTime" .=) <$> _vfdCreationTime,
("durationMs" .=) <$> _vfdDurationMs,
("fileSize" .=) <$> _vfdFileSize,
("fileType" .=) <$> _vfdFileType,
("container" .=) <$> _vfdContainer,
("videoStreams" .=) <$> _vfdVideoStreams,
("audioStreams" .=) <$> _vfdAudioStreams,
("fileName" .=) <$> _vfdFileName])
--
-- /See:/ 'thumbnailSetResponse' smart constructor.
data ThumbnailSetResponse =
ThumbnailSetResponse'
{ _tsrEtag :: !(Maybe Text)
, _tsrKind :: !Text
, _tsrItems :: !(Maybe [ThumbnailDetails])
, _tsrVisitorId :: !(Maybe Text)
, _tsrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ThumbnailSetResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tsrEtag'
--
-- * 'tsrKind'
--
-- * 'tsrItems'
--
-- * 'tsrVisitorId'
--
-- * 'tsrEventId'
thumbnailSetResponse
:: ThumbnailSetResponse
thumbnailSetResponse =
ThumbnailSetResponse'
{ _tsrEtag = Nothing
, _tsrKind = "youtube#thumbnailSetResponse"
, _tsrItems = Nothing
, _tsrVisitorId = Nothing
, _tsrEventId = Nothing
}
-- | Etag of this resource.
tsrEtag :: Lens' ThumbnailSetResponse (Maybe Text)
tsrEtag = lens _tsrEtag (\ s a -> s{_tsrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#thumbnailSetResponse\".
tsrKind :: Lens' ThumbnailSetResponse Text
tsrKind = lens _tsrKind (\ s a -> s{_tsrKind = a})
-- | A list of thumbnails.
tsrItems :: Lens' ThumbnailSetResponse [ThumbnailDetails]
tsrItems
= lens _tsrItems (\ s a -> s{_tsrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
tsrVisitorId :: Lens' ThumbnailSetResponse (Maybe Text)
tsrVisitorId
= lens _tsrVisitorId (\ s a -> s{_tsrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
tsrEventId :: Lens' ThumbnailSetResponse (Maybe Text)
tsrEventId
= lens _tsrEventId (\ s a -> s{_tsrEventId = a})
instance FromJSON ThumbnailSetResponse where
parseJSON
= withObject "ThumbnailSetResponse"
(\ o ->
ThumbnailSetResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "youtube#thumbnailSetResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON ThumbnailSetResponse where
toJSON ThumbnailSetResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _tsrEtag, Just ("kind" .= _tsrKind),
("items" .=) <$> _tsrItems,
("visitorId" .=) <$> _tsrVisitorId,
("eventId" .=) <$> _tsrEventId])
--
-- /See:/ 'liveBroadcastListResponse' smart constructor.
data LiveBroadcastListResponse =
LiveBroadcastListResponse'
{ _lblrEtag :: !(Maybe Text)
, _lblrTokenPagination :: !(Maybe TokenPagination)
, _lblrNextPageToken :: !(Maybe Text)
, _lblrPageInfo :: !(Maybe PageInfo)
, _lblrKind :: !Text
, _lblrItems :: !(Maybe [LiveBroadcast])
, _lblrVisitorId :: !(Maybe Text)
, _lblrEventId :: !(Maybe Text)
, _lblrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lblrEtag'
--
-- * 'lblrTokenPagination'
--
-- * 'lblrNextPageToken'
--
-- * 'lblrPageInfo'
--
-- * 'lblrKind'
--
-- * 'lblrItems'
--
-- * 'lblrVisitorId'
--
-- * 'lblrEventId'
--
-- * 'lblrPrevPageToken'
liveBroadcastListResponse
:: LiveBroadcastListResponse
liveBroadcastListResponse =
LiveBroadcastListResponse'
{ _lblrEtag = Nothing
, _lblrTokenPagination = Nothing
, _lblrNextPageToken = Nothing
, _lblrPageInfo = Nothing
, _lblrKind = "youtube#liveBroadcastListResponse"
, _lblrItems = Nothing
, _lblrVisitorId = Nothing
, _lblrEventId = Nothing
, _lblrPrevPageToken = Nothing
}
-- | Etag of this resource.
lblrEtag :: Lens' LiveBroadcastListResponse (Maybe Text)
lblrEtag = lens _lblrEtag (\ s a -> s{_lblrEtag = a})
lblrTokenPagination :: Lens' LiveBroadcastListResponse (Maybe TokenPagination)
lblrTokenPagination
= lens _lblrTokenPagination
(\ s a -> s{_lblrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
lblrNextPageToken :: Lens' LiveBroadcastListResponse (Maybe Text)
lblrNextPageToken
= lens _lblrNextPageToken
(\ s a -> s{_lblrNextPageToken = a})
-- | General pagination information.
lblrPageInfo :: Lens' LiveBroadcastListResponse (Maybe PageInfo)
lblrPageInfo
= lens _lblrPageInfo (\ s a -> s{_lblrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveBroadcastListResponse\".
lblrKind :: Lens' LiveBroadcastListResponse Text
lblrKind = lens _lblrKind (\ s a -> s{_lblrKind = a})
-- | A list of broadcasts that match the request criteria.
lblrItems :: Lens' LiveBroadcastListResponse [LiveBroadcast]
lblrItems
= lens _lblrItems (\ s a -> s{_lblrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
lblrVisitorId :: Lens' LiveBroadcastListResponse (Maybe Text)
lblrVisitorId
= lens _lblrVisitorId
(\ s a -> s{_lblrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
lblrEventId :: Lens' LiveBroadcastListResponse (Maybe Text)
lblrEventId
= lens _lblrEventId (\ s a -> s{_lblrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
lblrPrevPageToken :: Lens' LiveBroadcastListResponse (Maybe Text)
lblrPrevPageToken
= lens _lblrPrevPageToken
(\ s a -> s{_lblrPrevPageToken = a})
instance FromJSON LiveBroadcastListResponse where
parseJSON
= withObject "LiveBroadcastListResponse"
(\ o ->
LiveBroadcastListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!=
"youtube#liveBroadcastListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON LiveBroadcastListResponse where
toJSON LiveBroadcastListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _lblrEtag,
("tokenPagination" .=) <$> _lblrTokenPagination,
("nextPageToken" .=) <$> _lblrNextPageToken,
("pageInfo" .=) <$> _lblrPageInfo,
Just ("kind" .= _lblrKind),
("items" .=) <$> _lblrItems,
("visitorId" .=) <$> _lblrVisitorId,
("eventId" .=) <$> _lblrEventId,
("prevPageToken" .=) <$> _lblrPrevPageToken])
-- | Details about the content of a channel.
--
-- /See:/ 'channelContentDetails' smart constructor.
newtype ChannelContentDetails =
ChannelContentDetails'
{ _ccdRelatedPlayLists :: Maybe ChannelContentDetailsRelatedPlayLists
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccdRelatedPlayLists'
channelContentDetails
:: ChannelContentDetails
channelContentDetails = ChannelContentDetails' {_ccdRelatedPlayLists = Nothing}
ccdRelatedPlayLists :: Lens' ChannelContentDetails (Maybe ChannelContentDetailsRelatedPlayLists)
ccdRelatedPlayLists
= lens _ccdRelatedPlayLists
(\ s a -> s{_ccdRelatedPlayLists = a})
instance FromJSON ChannelContentDetails where
parseJSON
= withObject "ChannelContentDetails"
(\ o ->
ChannelContentDetails' <$>
(o .:? "relatedPlaylists"))
instance ToJSON ChannelContentDetails where
toJSON ChannelContentDetails'{..}
= object
(catMaybes
[("relatedPlaylists" .=) <$> _ccdRelatedPlayLists])
-- | Details about a resource which was added to a channel.
--
-- /See:/ 'activityContentDetailsChannelItem' smart constructor.
newtype ActivityContentDetailsChannelItem =
ActivityContentDetailsChannelItem'
{ _acdciResourceId :: Maybe ResourceId
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsChannelItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdciResourceId'
activityContentDetailsChannelItem
:: ActivityContentDetailsChannelItem
activityContentDetailsChannelItem =
ActivityContentDetailsChannelItem' {_acdciResourceId = Nothing}
-- | The resourceId object contains information that identifies the resource
-- that was added to the channel.
acdciResourceId :: Lens' ActivityContentDetailsChannelItem (Maybe ResourceId)
acdciResourceId
= lens _acdciResourceId
(\ s a -> s{_acdciResourceId = a})
instance FromJSON ActivityContentDetailsChannelItem
where
parseJSON
= withObject "ActivityContentDetailsChannelItem"
(\ o ->
ActivityContentDetailsChannelItem' <$>
(o .:? "resourceId"))
instance ToJSON ActivityContentDetailsChannelItem
where
toJSON ActivityContentDetailsChannelItem'{..}
= object
(catMaybes [("resourceId" .=) <$> _acdciResourceId])
--
-- /See:/ 'videoListResponse' smart constructor.
data VideoListResponse =
VideoListResponse'
{ _vlrEtag :: !(Maybe Text)
, _vlrTokenPagination :: !(Maybe TokenPagination)
, _vlrNextPageToken :: !(Maybe Text)
, _vlrPageInfo :: !(Maybe PageInfo)
, _vlrKind :: !Text
, _vlrItems :: !(Maybe [Video])
, _vlrVisitorId :: !(Maybe Text)
, _vlrEventId :: !(Maybe Text)
, _vlrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vlrEtag'
--
-- * 'vlrTokenPagination'
--
-- * 'vlrNextPageToken'
--
-- * 'vlrPageInfo'
--
-- * 'vlrKind'
--
-- * 'vlrItems'
--
-- * 'vlrVisitorId'
--
-- * 'vlrEventId'
--
-- * 'vlrPrevPageToken'
videoListResponse
:: VideoListResponse
videoListResponse =
VideoListResponse'
{ _vlrEtag = Nothing
, _vlrTokenPagination = Nothing
, _vlrNextPageToken = Nothing
, _vlrPageInfo = Nothing
, _vlrKind = "youtube#videoListResponse"
, _vlrItems = Nothing
, _vlrVisitorId = Nothing
, _vlrEventId = Nothing
, _vlrPrevPageToken = Nothing
}
-- | Etag of this resource.
vlrEtag :: Lens' VideoListResponse (Maybe Text)
vlrEtag = lens _vlrEtag (\ s a -> s{_vlrEtag = a})
vlrTokenPagination :: Lens' VideoListResponse (Maybe TokenPagination)
vlrTokenPagination
= lens _vlrTokenPagination
(\ s a -> s{_vlrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
vlrNextPageToken :: Lens' VideoListResponse (Maybe Text)
vlrNextPageToken
= lens _vlrNextPageToken
(\ s a -> s{_vlrNextPageToken = a})
-- | General pagination information.
vlrPageInfo :: Lens' VideoListResponse (Maybe PageInfo)
vlrPageInfo
= lens _vlrPageInfo (\ s a -> s{_vlrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#videoListResponse\".
vlrKind :: Lens' VideoListResponse Text
vlrKind = lens _vlrKind (\ s a -> s{_vlrKind = a})
vlrItems :: Lens' VideoListResponse [Video]
vlrItems
= lens _vlrItems (\ s a -> s{_vlrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
vlrVisitorId :: Lens' VideoListResponse (Maybe Text)
vlrVisitorId
= lens _vlrVisitorId (\ s a -> s{_vlrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
vlrEventId :: Lens' VideoListResponse (Maybe Text)
vlrEventId
= lens _vlrEventId (\ s a -> s{_vlrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
vlrPrevPageToken :: Lens' VideoListResponse (Maybe Text)
vlrPrevPageToken
= lens _vlrPrevPageToken
(\ s a -> s{_vlrPrevPageToken = a})
instance FromJSON VideoListResponse where
parseJSON
= withObject "VideoListResponse"
(\ o ->
VideoListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#videoListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON VideoListResponse where
toJSON VideoListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _vlrEtag,
("tokenPagination" .=) <$> _vlrTokenPagination,
("nextPageToken" .=) <$> _vlrNextPageToken,
("pageInfo" .=) <$> _vlrPageInfo,
Just ("kind" .= _vlrKind),
("items" .=) <$> _vlrItems,
("visitorId" .=) <$> _vlrVisitorId,
("eventId" .=) <$> _vlrEventId,
("prevPageToken" .=) <$> _vlrPrevPageToken])
-- | Details about monetization of a YouTube Video.
--
-- /See:/ 'videoMonetizationDetails' smart constructor.
newtype VideoMonetizationDetails =
VideoMonetizationDetails'
{ _vmdAccess :: Maybe AccessPolicy
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoMonetizationDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vmdAccess'
videoMonetizationDetails
:: VideoMonetizationDetails
videoMonetizationDetails = VideoMonetizationDetails' {_vmdAccess = Nothing}
-- | The value of access indicates whether the video can be monetized or not.
vmdAccess :: Lens' VideoMonetizationDetails (Maybe AccessPolicy)
vmdAccess
= lens _vmdAccess (\ s a -> s{_vmdAccess = a})
instance FromJSON VideoMonetizationDetails where
parseJSON
= withObject "VideoMonetizationDetails"
(\ o ->
VideoMonetizationDetails' <$> (o .:? "access"))
instance ToJSON VideoMonetizationDetails where
toJSON VideoMonetizationDetails'{..}
= object (catMaybes [("access" .=) <$> _vmdAccess])
-- | A single tag suggestion with it\'s relevance information.
--
-- /See:/ 'videoSuggestionsTagSuggestion' smart constructor.
data VideoSuggestionsTagSuggestion =
VideoSuggestionsTagSuggestion'
{ _vstsTag :: !(Maybe Text)
, _vstsCategoryRestricts :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoSuggestionsTagSuggestion' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vstsTag'
--
-- * 'vstsCategoryRestricts'
videoSuggestionsTagSuggestion
:: VideoSuggestionsTagSuggestion
videoSuggestionsTagSuggestion =
VideoSuggestionsTagSuggestion'
{_vstsTag = Nothing, _vstsCategoryRestricts = Nothing}
-- | The keyword tag suggested for the video.
vstsTag :: Lens' VideoSuggestionsTagSuggestion (Maybe Text)
vstsTag = lens _vstsTag (\ s a -> s{_vstsTag = a})
-- | A set of video categories for which the tag is relevant. You can use
-- this information to display appropriate tag suggestions based on the
-- video category that the video uploader associates with the video. By
-- default, tag suggestions are relevant for all categories if there are no
-- restricts defined for the keyword.
vstsCategoryRestricts :: Lens' VideoSuggestionsTagSuggestion [Text]
vstsCategoryRestricts
= lens _vstsCategoryRestricts
(\ s a -> s{_vstsCategoryRestricts = a})
. _Default
. _Coerce
instance FromJSON VideoSuggestionsTagSuggestion where
parseJSON
= withObject "VideoSuggestionsTagSuggestion"
(\ o ->
VideoSuggestionsTagSuggestion' <$>
(o .:? "tag") <*>
(o .:? "categoryRestricts" .!= mempty))
instance ToJSON VideoSuggestionsTagSuggestion where
toJSON VideoSuggestionsTagSuggestion'{..}
= object
(catMaybes
[("tag" .=) <$> _vstsTag,
("categoryRestricts" .=) <$> _vstsCategoryRestricts])
--
-- /See:/ 'abuseType' smart constructor.
newtype AbuseType =
AbuseType'
{ _atId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AbuseType' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atId'
abuseType
:: AbuseType
abuseType = AbuseType' {_atId = Nothing}
atId :: Lens' AbuseType (Maybe Text)
atId = lens _atId (\ s a -> s{_atId = a})
instance FromJSON AbuseType where
parseJSON
= withObject "AbuseType"
(\ o -> AbuseType' <$> (o .:? "id"))
instance ToJSON AbuseType where
toJSON AbuseType'{..}
= object (catMaybes [("id" .=) <$> _atId])
--
-- /See:/ 'liveChatModeratorListResponse' smart constructor.
data LiveChatModeratorListResponse =
LiveChatModeratorListResponse'
{ _lEtag :: !(Maybe Text)
, _lTokenPagination :: !(Maybe TokenPagination)
, _lNextPageToken :: !(Maybe Text)
, _lPageInfo :: !(Maybe PageInfo)
, _lKind :: !Text
, _lItems :: !(Maybe [LiveChatModerator])
, _lVisitorId :: !(Maybe Text)
, _lEventId :: !(Maybe Text)
, _lPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatModeratorListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lEtag'
--
-- * 'lTokenPagination'
--
-- * 'lNextPageToken'
--
-- * 'lPageInfo'
--
-- * 'lKind'
--
-- * 'lItems'
--
-- * 'lVisitorId'
--
-- * 'lEventId'
--
-- * 'lPrevPageToken'
liveChatModeratorListResponse
:: LiveChatModeratorListResponse
liveChatModeratorListResponse =
LiveChatModeratorListResponse'
{ _lEtag = Nothing
, _lTokenPagination = Nothing
, _lNextPageToken = Nothing
, _lPageInfo = Nothing
, _lKind = "youtube#liveChatModeratorListResponse"
, _lItems = Nothing
, _lVisitorId = Nothing
, _lEventId = Nothing
, _lPrevPageToken = Nothing
}
-- | Etag of this resource.
lEtag :: Lens' LiveChatModeratorListResponse (Maybe Text)
lEtag = lens _lEtag (\ s a -> s{_lEtag = a})
lTokenPagination :: Lens' LiveChatModeratorListResponse (Maybe TokenPagination)
lTokenPagination
= lens _lTokenPagination
(\ s a -> s{_lTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
lNextPageToken :: Lens' LiveChatModeratorListResponse (Maybe Text)
lNextPageToken
= lens _lNextPageToken
(\ s a -> s{_lNextPageToken = a})
-- | General pagination information.
lPageInfo :: Lens' LiveChatModeratorListResponse (Maybe PageInfo)
lPageInfo
= lens _lPageInfo (\ s a -> s{_lPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveChatModeratorListResponse\".
lKind :: Lens' LiveChatModeratorListResponse Text
lKind = lens _lKind (\ s a -> s{_lKind = a})
-- | A list of moderators that match the request criteria.
lItems :: Lens' LiveChatModeratorListResponse [LiveChatModerator]
lItems
= lens _lItems (\ s a -> s{_lItems = a}) . _Default .
_Coerce
-- | The visitorId identifies the visitor.
lVisitorId :: Lens' LiveChatModeratorListResponse (Maybe Text)
lVisitorId
= lens _lVisitorId (\ s a -> s{_lVisitorId = a})
-- | Serialized EventId of the request which produced this response.
lEventId :: Lens' LiveChatModeratorListResponse (Maybe Text)
lEventId = lens _lEventId (\ s a -> s{_lEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
lPrevPageToken :: Lens' LiveChatModeratorListResponse (Maybe Text)
lPrevPageToken
= lens _lPrevPageToken
(\ s a -> s{_lPrevPageToken = a})
instance FromJSON LiveChatModeratorListResponse where
parseJSON
= withObject "LiveChatModeratorListResponse"
(\ o ->
LiveChatModeratorListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!=
"youtube#liveChatModeratorListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON LiveChatModeratorListResponse where
toJSON LiveChatModeratorListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _lEtag,
("tokenPagination" .=) <$> _lTokenPagination,
("nextPageToken" .=) <$> _lNextPageToken,
("pageInfo" .=) <$> _lPageInfo,
Just ("kind" .= _lKind), ("items" .=) <$> _lItems,
("visitorId" .=) <$> _lVisitorId,
("eventId" .=) <$> _lEventId,
("prevPageToken" .=) <$> _lPrevPageToken])
-- | Basic details about an activity, including title, description,
-- thumbnails, activity type and group. Next ID: 12
--
-- /See:/ 'activitySnippet' smart constructor.
data ActivitySnippet =
ActivitySnippet'
{ _asPublishedAt :: !(Maybe DateTime')
, _asChannelTitle :: !(Maybe Text)
, _asChannelId :: !(Maybe Text)
, _asThumbnails :: !(Maybe ThumbnailDetails)
, _asGroupId :: !(Maybe Text)
, _asTitle :: !(Maybe Text)
, _asType :: !(Maybe ActivitySnippetType)
, _asDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivitySnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'asPublishedAt'
--
-- * 'asChannelTitle'
--
-- * 'asChannelId'
--
-- * 'asThumbnails'
--
-- * 'asGroupId'
--
-- * 'asTitle'
--
-- * 'asType'
--
-- * 'asDescription'
activitySnippet
:: ActivitySnippet
activitySnippet =
ActivitySnippet'
{ _asPublishedAt = Nothing
, _asChannelTitle = Nothing
, _asChannelId = Nothing
, _asThumbnails = Nothing
, _asGroupId = Nothing
, _asTitle = Nothing
, _asType = Nothing
, _asDescription = Nothing
}
-- | The date and time that the video was uploaded.
asPublishedAt :: Lens' ActivitySnippet (Maybe UTCTime)
asPublishedAt
= lens _asPublishedAt
(\ s a -> s{_asPublishedAt = a})
. mapping _DateTime
-- | Channel title for the channel responsible for this activity
asChannelTitle :: Lens' ActivitySnippet (Maybe Text)
asChannelTitle
= lens _asChannelTitle
(\ s a -> s{_asChannelTitle = a})
-- | The ID that YouTube uses to uniquely identify the channel associated
-- with the activity.
asChannelId :: Lens' ActivitySnippet (Maybe Text)
asChannelId
= lens _asChannelId (\ s a -> s{_asChannelId = a})
-- | A map of thumbnail images associated with the resource that is primarily
-- associated with the activity. For each object in the map, the key is the
-- name of the thumbnail image, and the value is an object that contains
-- other information about the thumbnail.
asThumbnails :: Lens' ActivitySnippet (Maybe ThumbnailDetails)
asThumbnails
= lens _asThumbnails (\ s a -> s{_asThumbnails = a})
-- | The group ID associated with the activity. A group ID identifies user
-- events that are associated with the same user and resource. For example,
-- if a user rates a video and marks the same video as a favorite, the
-- entries for those events would have the same group ID in the user\'s
-- activity feed. In your user interface, you can avoid repetition by
-- grouping events with the same groupId value.
asGroupId :: Lens' ActivitySnippet (Maybe Text)
asGroupId
= lens _asGroupId (\ s a -> s{_asGroupId = a})
-- | The title of the resource primarily associated with the activity.
asTitle :: Lens' ActivitySnippet (Maybe Text)
asTitle = lens _asTitle (\ s a -> s{_asTitle = a})
-- | The type of activity that the resource describes.
asType :: Lens' ActivitySnippet (Maybe ActivitySnippetType)
asType = lens _asType (\ s a -> s{_asType = a})
-- | The description of the resource primarily associated with the activity.
-- \'mutable youtube.activities.insert
asDescription :: Lens' ActivitySnippet (Maybe Text)
asDescription
= lens _asDescription
(\ s a -> s{_asDescription = a})
instance FromJSON ActivitySnippet where
parseJSON
= withObject "ActivitySnippet"
(\ o ->
ActivitySnippet' <$>
(o .:? "publishedAt") <*> (o .:? "channelTitle") <*>
(o .:? "channelId")
<*> (o .:? "thumbnails")
<*> (o .:? "groupId")
<*> (o .:? "title")
<*> (o .:? "type")
<*> (o .:? "description"))
instance ToJSON ActivitySnippet where
toJSON ActivitySnippet'{..}
= object
(catMaybes
[("publishedAt" .=) <$> _asPublishedAt,
("channelTitle" .=) <$> _asChannelTitle,
("channelId" .=) <$> _asChannelId,
("thumbnails" .=) <$> _asThumbnails,
("groupId" .=) <$> _asGroupId,
("title" .=) <$> _asTitle, ("type" .=) <$> _asType,
("description" .=) <$> _asDescription])
-- | Freebase topic information related to the channel.
--
-- /See:/ 'channelTopicDetails' smart constructor.
data ChannelTopicDetails =
ChannelTopicDetails'
{ _ctdTopicIds :: !(Maybe [Text])
, _ctdTopicCategories :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelTopicDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctdTopicIds'
--
-- * 'ctdTopicCategories'
channelTopicDetails
:: ChannelTopicDetails
channelTopicDetails =
ChannelTopicDetails' {_ctdTopicIds = Nothing, _ctdTopicCategories = Nothing}
-- | A list of Freebase topic IDs associated with the channel. You can
-- retrieve information about each topic using the Freebase Topic API.
ctdTopicIds :: Lens' ChannelTopicDetails [Text]
ctdTopicIds
= lens _ctdTopicIds (\ s a -> s{_ctdTopicIds = a}) .
_Default
. _Coerce
-- | A list of Wikipedia URLs that describe the channel\'s content.
ctdTopicCategories :: Lens' ChannelTopicDetails [Text]
ctdTopicCategories
= lens _ctdTopicCategories
(\ s a -> s{_ctdTopicCategories = a})
. _Default
. _Coerce
instance FromJSON ChannelTopicDetails where
parseJSON
= withObject "ChannelTopicDetails"
(\ o ->
ChannelTopicDetails' <$>
(o .:? "topicIds" .!= mempty) <*>
(o .:? "topicCategories" .!= mempty))
instance ToJSON ChannelTopicDetails where
toJSON ChannelTopicDetails'{..}
= object
(catMaybes
[("topicIds" .=) <$> _ctdTopicIds,
("topicCategories" .=) <$> _ctdTopicCategories])
--
-- /See:/ 'videoCategoryListResponse' smart constructor.
data VideoCategoryListResponse =
VideoCategoryListResponse'
{ _vclrEtag :: !(Maybe Text)
, _vclrTokenPagination :: !(Maybe TokenPagination)
, _vclrNextPageToken :: !(Maybe Text)
, _vclrPageInfo :: !(Maybe PageInfo)
, _vclrKind :: !Text
, _vclrItems :: !(Maybe [VideoCategory])
, _vclrVisitorId :: !(Maybe Text)
, _vclrEventId :: !(Maybe Text)
, _vclrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoCategoryListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vclrEtag'
--
-- * 'vclrTokenPagination'
--
-- * 'vclrNextPageToken'
--
-- * 'vclrPageInfo'
--
-- * 'vclrKind'
--
-- * 'vclrItems'
--
-- * 'vclrVisitorId'
--
-- * 'vclrEventId'
--
-- * 'vclrPrevPageToken'
videoCategoryListResponse
:: VideoCategoryListResponse
videoCategoryListResponse =
VideoCategoryListResponse'
{ _vclrEtag = Nothing
, _vclrTokenPagination = Nothing
, _vclrNextPageToken = Nothing
, _vclrPageInfo = Nothing
, _vclrKind = "youtube#videoCategoryListResponse"
, _vclrItems = Nothing
, _vclrVisitorId = Nothing
, _vclrEventId = Nothing
, _vclrPrevPageToken = Nothing
}
-- | Etag of this resource.
vclrEtag :: Lens' VideoCategoryListResponse (Maybe Text)
vclrEtag = lens _vclrEtag (\ s a -> s{_vclrEtag = a})
vclrTokenPagination :: Lens' VideoCategoryListResponse (Maybe TokenPagination)
vclrTokenPagination
= lens _vclrTokenPagination
(\ s a -> s{_vclrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
vclrNextPageToken :: Lens' VideoCategoryListResponse (Maybe Text)
vclrNextPageToken
= lens _vclrNextPageToken
(\ s a -> s{_vclrNextPageToken = a})
-- | General pagination information.
vclrPageInfo :: Lens' VideoCategoryListResponse (Maybe PageInfo)
vclrPageInfo
= lens _vclrPageInfo (\ s a -> s{_vclrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#videoCategoryListResponse\".
vclrKind :: Lens' VideoCategoryListResponse Text
vclrKind = lens _vclrKind (\ s a -> s{_vclrKind = a})
-- | A list of video categories that can be associated with YouTube videos.
-- In this map, the video category ID is the map key, and its value is the
-- corresponding videoCategory resource.
vclrItems :: Lens' VideoCategoryListResponse [VideoCategory]
vclrItems
= lens _vclrItems (\ s a -> s{_vclrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
vclrVisitorId :: Lens' VideoCategoryListResponse (Maybe Text)
vclrVisitorId
= lens _vclrVisitorId
(\ s a -> s{_vclrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
vclrEventId :: Lens' VideoCategoryListResponse (Maybe Text)
vclrEventId
= lens _vclrEventId (\ s a -> s{_vclrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
vclrPrevPageToken :: Lens' VideoCategoryListResponse (Maybe Text)
vclrPrevPageToken
= lens _vclrPrevPageToken
(\ s a -> s{_vclrPrevPageToken = a})
instance FromJSON VideoCategoryListResponse where
parseJSON
= withObject "VideoCategoryListResponse"
(\ o ->
VideoCategoryListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!=
"youtube#videoCategoryListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON VideoCategoryListResponse where
toJSON VideoCategoryListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _vclrEtag,
("tokenPagination" .=) <$> _vclrTokenPagination,
("nextPageToken" .=) <$> _vclrNextPageToken,
("pageInfo" .=) <$> _vclrPageInfo,
Just ("kind" .= _vclrKind),
("items" .=) <$> _vclrItems,
("visitorId" .=) <$> _vclrVisitorId,
("eventId" .=) <$> _vclrEventId,
("prevPageToken" .=) <$> _vclrPrevPageToken])
-- | Describes processing status and progress and availability of some other
-- Video resource parts.
--
-- /See:/ 'videoProcessingDetails' smart constructor.
data VideoProcessingDetails =
VideoProcessingDetails'
{ _vpdProcessingFailureReason :: !(Maybe VideoProcessingDetailsProcessingFailureReason)
, _vpdProcessingIssuesAvailability :: !(Maybe Text)
, _vpdProcessingProgress :: !(Maybe VideoProcessingDetailsProcessingProgress)
, _vpdThumbnailsAvailability :: !(Maybe Text)
, _vpdTagSuggestionsAvailability :: !(Maybe Text)
, _vpdProcessingStatus :: !(Maybe VideoProcessingDetailsProcessingStatus)
, _vpdEditorSuggestionsAvailability :: !(Maybe Text)
, _vpdFileDetailsAvailability :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoProcessingDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vpdProcessingFailureReason'
--
-- * 'vpdProcessingIssuesAvailability'
--
-- * 'vpdProcessingProgress'
--
-- * 'vpdThumbnailsAvailability'
--
-- * 'vpdTagSuggestionsAvailability'
--
-- * 'vpdProcessingStatus'
--
-- * 'vpdEditorSuggestionsAvailability'
--
-- * 'vpdFileDetailsAvailability'
videoProcessingDetails
:: VideoProcessingDetails
videoProcessingDetails =
VideoProcessingDetails'
{ _vpdProcessingFailureReason = Nothing
, _vpdProcessingIssuesAvailability = Nothing
, _vpdProcessingProgress = Nothing
, _vpdThumbnailsAvailability = Nothing
, _vpdTagSuggestionsAvailability = Nothing
, _vpdProcessingStatus = Nothing
, _vpdEditorSuggestionsAvailability = Nothing
, _vpdFileDetailsAvailability = Nothing
}
-- | The reason that YouTube failed to process the video. This property will
-- only have a value if the processingStatus property\'s value is failed.
vpdProcessingFailureReason :: Lens' VideoProcessingDetails (Maybe VideoProcessingDetailsProcessingFailureReason)
vpdProcessingFailureReason
= lens _vpdProcessingFailureReason
(\ s a -> s{_vpdProcessingFailureReason = a})
-- | This value indicates whether the video processing engine has generated
-- suggestions that might improve YouTube\'s ability to process the the
-- video, warnings that explain video processing problems, or errors that
-- cause video processing problems. You can retrieve these suggestions by
-- requesting the suggestions part in your videos.list() request.
vpdProcessingIssuesAvailability :: Lens' VideoProcessingDetails (Maybe Text)
vpdProcessingIssuesAvailability
= lens _vpdProcessingIssuesAvailability
(\ s a -> s{_vpdProcessingIssuesAvailability = a})
-- | The processingProgress object contains information about the progress
-- YouTube has made in processing the video. The values are really only
-- relevant if the video\'s processing status is processing.
vpdProcessingProgress :: Lens' VideoProcessingDetails (Maybe VideoProcessingDetailsProcessingProgress)
vpdProcessingProgress
= lens _vpdProcessingProgress
(\ s a -> s{_vpdProcessingProgress = a})
-- | This value indicates whether thumbnail images have been generated for
-- the video.
vpdThumbnailsAvailability :: Lens' VideoProcessingDetails (Maybe Text)
vpdThumbnailsAvailability
= lens _vpdThumbnailsAvailability
(\ s a -> s{_vpdThumbnailsAvailability = a})
-- | This value indicates whether keyword (tag) suggestions are available for
-- the video. Tags can be added to a video\'s metadata to make it easier
-- for other users to find the video. You can retrieve these suggestions by
-- requesting the suggestions part in your videos.list() request.
vpdTagSuggestionsAvailability :: Lens' VideoProcessingDetails (Maybe Text)
vpdTagSuggestionsAvailability
= lens _vpdTagSuggestionsAvailability
(\ s a -> s{_vpdTagSuggestionsAvailability = a})
-- | The video\'s processing status. This value indicates whether YouTube was
-- able to process the video or if the video is still being processed.
vpdProcessingStatus :: Lens' VideoProcessingDetails (Maybe VideoProcessingDetailsProcessingStatus)
vpdProcessingStatus
= lens _vpdProcessingStatus
(\ s a -> s{_vpdProcessingStatus = a})
-- | This value indicates whether video editing suggestions, which might
-- improve video quality or the playback experience, are available for the
-- video. You can retrieve these suggestions by requesting the suggestions
-- part in your videos.list() request.
vpdEditorSuggestionsAvailability :: Lens' VideoProcessingDetails (Maybe Text)
vpdEditorSuggestionsAvailability
= lens _vpdEditorSuggestionsAvailability
(\ s a -> s{_vpdEditorSuggestionsAvailability = a})
-- | This value indicates whether file details are available for the uploaded
-- video. You can retrieve a video\'s file details by requesting the
-- fileDetails part in your videos.list() request.
vpdFileDetailsAvailability :: Lens' VideoProcessingDetails (Maybe Text)
vpdFileDetailsAvailability
= lens _vpdFileDetailsAvailability
(\ s a -> s{_vpdFileDetailsAvailability = a})
instance FromJSON VideoProcessingDetails where
parseJSON
= withObject "VideoProcessingDetails"
(\ o ->
VideoProcessingDetails' <$>
(o .:? "processingFailureReason") <*>
(o .:? "processingIssuesAvailability")
<*> (o .:? "processingProgress")
<*> (o .:? "thumbnailsAvailability")
<*> (o .:? "tagSuggestionsAvailability")
<*> (o .:? "processingStatus")
<*> (o .:? "editorSuggestionsAvailability")
<*> (o .:? "fileDetailsAvailability"))
instance ToJSON VideoProcessingDetails where
toJSON VideoProcessingDetails'{..}
= object
(catMaybes
[("processingFailureReason" .=) <$>
_vpdProcessingFailureReason,
("processingIssuesAvailability" .=) <$>
_vpdProcessingIssuesAvailability,
("processingProgress" .=) <$> _vpdProcessingProgress,
("thumbnailsAvailability" .=) <$>
_vpdThumbnailsAvailability,
("tagSuggestionsAvailability" .=) <$>
_vpdTagSuggestionsAvailability,
("processingStatus" .=) <$> _vpdProcessingStatus,
("editorSuggestionsAvailability" .=) <$>
_vpdEditorSuggestionsAvailability,
("fileDetailsAvailability" .=) <$>
_vpdFileDetailsAvailability])
-- | Basic details about a comment thread.
--
-- /See:/ 'commentThreadSnippet' smart constructor.
data CommentThreadSnippet =
CommentThreadSnippet'
{ _ctsIsPublic :: !(Maybe Bool)
, _ctsChannelId :: !(Maybe Text)
, _ctsCanReply :: !(Maybe Bool)
, _ctsVideoId :: !(Maybe Text)
, _ctsTotalReplyCount :: !(Maybe (Textual Word32))
, _ctsTopLevelComment :: !(Maybe Comment)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentThreadSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctsIsPublic'
--
-- * 'ctsChannelId'
--
-- * 'ctsCanReply'
--
-- * 'ctsVideoId'
--
-- * 'ctsTotalReplyCount'
--
-- * 'ctsTopLevelComment'
commentThreadSnippet
:: CommentThreadSnippet
commentThreadSnippet =
CommentThreadSnippet'
{ _ctsIsPublic = Nothing
, _ctsChannelId = Nothing
, _ctsCanReply = Nothing
, _ctsVideoId = Nothing
, _ctsTotalReplyCount = Nothing
, _ctsTopLevelComment = Nothing
}
-- | Whether the thread (and therefore all its comments) is visible to all
-- YouTube users.
ctsIsPublic :: Lens' CommentThreadSnippet (Maybe Bool)
ctsIsPublic
= lens _ctsIsPublic (\ s a -> s{_ctsIsPublic = a})
-- | The YouTube channel the comments in the thread refer to or the channel
-- with the video the comments refer to. If video_id isn\'t set the
-- comments refer to the channel itself.
ctsChannelId :: Lens' CommentThreadSnippet (Maybe Text)
ctsChannelId
= lens _ctsChannelId (\ s a -> s{_ctsChannelId = a})
-- | Whether the current viewer of the thread can reply to it. This is viewer
-- specific - other viewers may see a different value for this field.
ctsCanReply :: Lens' CommentThreadSnippet (Maybe Bool)
ctsCanReply
= lens _ctsCanReply (\ s a -> s{_ctsCanReply = a})
-- | The ID of the video the comments refer to, if any. No video_id implies a
-- channel discussion comment.
ctsVideoId :: Lens' CommentThreadSnippet (Maybe Text)
ctsVideoId
= lens _ctsVideoId (\ s a -> s{_ctsVideoId = a})
-- | The total number of replies (not including the top level comment).
ctsTotalReplyCount :: Lens' CommentThreadSnippet (Maybe Word32)
ctsTotalReplyCount
= lens _ctsTotalReplyCount
(\ s a -> s{_ctsTotalReplyCount = a})
. mapping _Coerce
-- | The top level comment of this thread.
ctsTopLevelComment :: Lens' CommentThreadSnippet (Maybe Comment)
ctsTopLevelComment
= lens _ctsTopLevelComment
(\ s a -> s{_ctsTopLevelComment = a})
instance FromJSON CommentThreadSnippet where
parseJSON
= withObject "CommentThreadSnippet"
(\ o ->
CommentThreadSnippet' <$>
(o .:? "isPublic") <*> (o .:? "channelId") <*>
(o .:? "canReply")
<*> (o .:? "videoId")
<*> (o .:? "totalReplyCount")
<*> (o .:? "topLevelComment"))
instance ToJSON CommentThreadSnippet where
toJSON CommentThreadSnippet'{..}
= object
(catMaybes
[("isPublic" .=) <$> _ctsIsPublic,
("channelId" .=) <$> _ctsChannelId,
("canReply" .=) <$> _ctsCanReply,
("videoId" .=) <$> _ctsVideoId,
("totalReplyCount" .=) <$> _ctsTotalReplyCount,
("topLevelComment" .=) <$> _ctsTopLevelComment])
--
-- /See:/ 'channelSectionListResponse' smart constructor.
data ChannelSectionListResponse =
ChannelSectionListResponse'
{ _cslrEtag :: !(Maybe Text)
, _cslrKind :: !Text
, _cslrItems :: !(Maybe [ChannelSection])
, _cslrVisitorId :: !(Maybe Text)
, _cslrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSectionListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cslrEtag'
--
-- * 'cslrKind'
--
-- * 'cslrItems'
--
-- * 'cslrVisitorId'
--
-- * 'cslrEventId'
channelSectionListResponse
:: ChannelSectionListResponse
channelSectionListResponse =
ChannelSectionListResponse'
{ _cslrEtag = Nothing
, _cslrKind = "youtube#channelSectionListResponse"
, _cslrItems = Nothing
, _cslrVisitorId = Nothing
, _cslrEventId = Nothing
}
-- | Etag of this resource.
cslrEtag :: Lens' ChannelSectionListResponse (Maybe Text)
cslrEtag = lens _cslrEtag (\ s a -> s{_cslrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#channelSectionListResponse\".
cslrKind :: Lens' ChannelSectionListResponse Text
cslrKind = lens _cslrKind (\ s a -> s{_cslrKind = a})
-- | A list of ChannelSections that match the request criteria.
cslrItems :: Lens' ChannelSectionListResponse [ChannelSection]
cslrItems
= lens _cslrItems (\ s a -> s{_cslrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
cslrVisitorId :: Lens' ChannelSectionListResponse (Maybe Text)
cslrVisitorId
= lens _cslrVisitorId
(\ s a -> s{_cslrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
cslrEventId :: Lens' ChannelSectionListResponse (Maybe Text)
cslrEventId
= lens _cslrEventId (\ s a -> s{_cslrEventId = a})
instance FromJSON ChannelSectionListResponse where
parseJSON
= withObject "ChannelSectionListResponse"
(\ o ->
ChannelSectionListResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!=
"youtube#channelSectionListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON ChannelSectionListResponse where
toJSON ChannelSectionListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _cslrEtag,
Just ("kind" .= _cslrKind),
("items" .=) <$> _cslrItems,
("visitorId" .=) <$> _cslrVisitorId,
("eventId" .=) <$> _cslrEventId])
-- | A \`__superChatEvent__\` resource represents a Super Chat purchase on a
-- YouTube channel.
--
-- /See:/ 'superChatEvent' smart constructor.
data SuperChatEvent =
SuperChatEvent'
{ _sceEtag :: !(Maybe Text)
, _sceSnippet :: !(Maybe SuperChatEventSnippet)
, _sceKind :: !Text
, _sceId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SuperChatEvent' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sceEtag'
--
-- * 'sceSnippet'
--
-- * 'sceKind'
--
-- * 'sceId'
superChatEvent
:: SuperChatEvent
superChatEvent =
SuperChatEvent'
{ _sceEtag = Nothing
, _sceSnippet = Nothing
, _sceKind = "youtube#superChatEvent"
, _sceId = Nothing
}
-- | Etag of this resource.
sceEtag :: Lens' SuperChatEvent (Maybe Text)
sceEtag = lens _sceEtag (\ s a -> s{_sceEtag = a})
-- | The \`snippet\` object contains basic details about the Super Chat
-- event.
sceSnippet :: Lens' SuperChatEvent (Maybe SuperChatEventSnippet)
sceSnippet
= lens _sceSnippet (\ s a -> s{_sceSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \`\"youtube#superChatEvent\"\`.
sceKind :: Lens' SuperChatEvent Text
sceKind = lens _sceKind (\ s a -> s{_sceKind = a})
-- | The ID that YouTube assigns to uniquely identify the Super Chat event.
sceId :: Lens' SuperChatEvent (Maybe Text)
sceId = lens _sceId (\ s a -> s{_sceId = a})
instance FromJSON SuperChatEvent where
parseJSON
= withObject "SuperChatEvent"
(\ o ->
SuperChatEvent' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#superChatEvent")
<*> (o .:? "id"))
instance ToJSON SuperChatEvent where
toJSON SuperChatEvent'{..}
= object
(catMaybes
[("etag" .=) <$> _sceEtag,
("snippet" .=) <$> _sceSnippet,
Just ("kind" .= _sceKind), ("id" .=) <$> _sceId])
-- | A \`__videoAbuseReportReason__\` resource identifies a reason that a
-- video could be reported as abusive. Video abuse report reasons are used
-- with \`video.ReportAbuse\`.
--
-- /See:/ 'videoAbuseReportReason' smart constructor.
data VideoAbuseReportReason =
VideoAbuseReportReason'
{ _varrEtag :: !(Maybe Text)
, _varrSnippet :: !(Maybe VideoAbuseReportReasonSnippet)
, _varrKind :: !Text
, _varrId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoAbuseReportReason' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'varrEtag'
--
-- * 'varrSnippet'
--
-- * 'varrKind'
--
-- * 'varrId'
videoAbuseReportReason
:: VideoAbuseReportReason
videoAbuseReportReason =
VideoAbuseReportReason'
{ _varrEtag = Nothing
, _varrSnippet = Nothing
, _varrKind = "youtube#videoAbuseReportReason"
, _varrId = Nothing
}
-- | Etag of this resource.
varrEtag :: Lens' VideoAbuseReportReason (Maybe Text)
varrEtag = lens _varrEtag (\ s a -> s{_varrEtag = a})
-- | The \`snippet\` object contains basic details about the abuse report
-- reason.
varrSnippet :: Lens' VideoAbuseReportReason (Maybe VideoAbuseReportReasonSnippet)
varrSnippet
= lens _varrSnippet (\ s a -> s{_varrSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \`\"youtube#videoAbuseReportReason\"\`.
varrKind :: Lens' VideoAbuseReportReason Text
varrKind = lens _varrKind (\ s a -> s{_varrKind = a})
-- | The high-level, or primary, reason that the content is abusive. The
-- value is an abuse report reason ID.
varrId :: Lens' VideoAbuseReportReason (Maybe Text)
varrId = lens _varrId (\ s a -> s{_varrId = a})
instance FromJSON VideoAbuseReportReason where
parseJSON
= withObject "VideoAbuseReportReason"
(\ o ->
VideoAbuseReportReason' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#videoAbuseReportReason")
<*> (o .:? "id"))
instance ToJSON VideoAbuseReportReason where
toJSON VideoAbuseReportReason'{..}
= object
(catMaybes
[("etag" .=) <$> _varrEtag,
("snippet" .=) <$> _varrSnippet,
Just ("kind" .= _varrKind), ("id" .=) <$> _varrId])
--
-- /See:/ 'liveStreamConfigurationIssue' smart constructor.
data LiveStreamConfigurationIssue =
LiveStreamConfigurationIssue'
{ _lsciSeverity :: !(Maybe LiveStreamConfigurationIssueSeverity)
, _lsciReason :: !(Maybe Text)
, _lsciType :: !(Maybe LiveStreamConfigurationIssueType)
, _lsciDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStreamConfigurationIssue' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lsciSeverity'
--
-- * 'lsciReason'
--
-- * 'lsciType'
--
-- * 'lsciDescription'
liveStreamConfigurationIssue
:: LiveStreamConfigurationIssue
liveStreamConfigurationIssue =
LiveStreamConfigurationIssue'
{ _lsciSeverity = Nothing
, _lsciReason = Nothing
, _lsciType = Nothing
, _lsciDescription = Nothing
}
-- | How severe this issue is to the stream.
lsciSeverity :: Lens' LiveStreamConfigurationIssue (Maybe LiveStreamConfigurationIssueSeverity)
lsciSeverity
= lens _lsciSeverity (\ s a -> s{_lsciSeverity = a})
-- | The short-form reason for this issue.
lsciReason :: Lens' LiveStreamConfigurationIssue (Maybe Text)
lsciReason
= lens _lsciReason (\ s a -> s{_lsciReason = a})
-- | The kind of error happening.
lsciType :: Lens' LiveStreamConfigurationIssue (Maybe LiveStreamConfigurationIssueType)
lsciType = lens _lsciType (\ s a -> s{_lsciType = a})
-- | The long-form description of the issue and how to resolve it.
lsciDescription :: Lens' LiveStreamConfigurationIssue (Maybe Text)
lsciDescription
= lens _lsciDescription
(\ s a -> s{_lsciDescription = a})
instance FromJSON LiveStreamConfigurationIssue where
parseJSON
= withObject "LiveStreamConfigurationIssue"
(\ o ->
LiveStreamConfigurationIssue' <$>
(o .:? "severity") <*> (o .:? "reason") <*>
(o .:? "type")
<*> (o .:? "description"))
instance ToJSON LiveStreamConfigurationIssue where
toJSON LiveStreamConfigurationIssue'{..}
= object
(catMaybes
[("severity" .=) <$> _lsciSeverity,
("reason" .=) <$> _lsciReason,
("type" .=) <$> _lsciType,
("description" .=) <$> _lsciDescription])
-- | A *liveChatMessage* resource represents a chat message in a YouTube Live
-- Chat.
--
-- /See:/ 'liveChatMessage' smart constructor.
data LiveChatMessage =
LiveChatMessage'
{ _lcmEtag :: !(Maybe Text)
, _lcmSnippet :: !(Maybe LiveChatMessageSnippet)
, _lcmKind :: !Text
, _lcmAuthorDetails :: !(Maybe LiveChatMessageAuthorDetails)
, _lcmId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatMessage' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcmEtag'
--
-- * 'lcmSnippet'
--
-- * 'lcmKind'
--
-- * 'lcmAuthorDetails'
--
-- * 'lcmId'
liveChatMessage
:: LiveChatMessage
liveChatMessage =
LiveChatMessage'
{ _lcmEtag = Nothing
, _lcmSnippet = Nothing
, _lcmKind = "youtube#liveChatMessage"
, _lcmAuthorDetails = Nothing
, _lcmId = Nothing
}
-- | Etag of this resource.
lcmEtag :: Lens' LiveChatMessage (Maybe Text)
lcmEtag = lens _lcmEtag (\ s a -> s{_lcmEtag = a})
-- | The snippet object contains basic details about the message.
lcmSnippet :: Lens' LiveChatMessage (Maybe LiveChatMessageSnippet)
lcmSnippet
= lens _lcmSnippet (\ s a -> s{_lcmSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveChatMessage\".
lcmKind :: Lens' LiveChatMessage Text
lcmKind = lens _lcmKind (\ s a -> s{_lcmKind = a})
-- | The authorDetails object contains basic details about the user that
-- posted this message.
lcmAuthorDetails :: Lens' LiveChatMessage (Maybe LiveChatMessageAuthorDetails)
lcmAuthorDetails
= lens _lcmAuthorDetails
(\ s a -> s{_lcmAuthorDetails = a})
-- | The ID that YouTube assigns to uniquely identify the message.
lcmId :: Lens' LiveChatMessage (Maybe Text)
lcmId = lens _lcmId (\ s a -> s{_lcmId = a})
instance FromJSON LiveChatMessage where
parseJSON
= withObject "LiveChatMessage"
(\ o ->
LiveChatMessage' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#liveChatMessage")
<*> (o .:? "authorDetails")
<*> (o .:? "id"))
instance ToJSON LiveChatMessage where
toJSON LiveChatMessage'{..}
= object
(catMaybes
[("etag" .=) <$> _lcmEtag,
("snippet" .=) <$> _lcmSnippet,
Just ("kind" .= _lcmKind),
("authorDetails" .=) <$> _lcmAuthorDetails,
("id" .=) <$> _lcmId])
-- | A *channel* resource contains information about a YouTube channel.
--
-- /See:/ 'channel' smart constructor.
data Channel =
Channel'
{ _chaStatus :: !(Maybe ChannelStatus)
, _chaEtag :: !(Maybe Text)
, _chaAuditDetails :: !(Maybe ChannelAuditDetails)
, _chaContentOwnerDetails :: !(Maybe ChannelContentOwnerDetails)
, _chaSnippet :: !(Maybe ChannelSnippet)
, _chaKind :: !Text
, _chaTopicDetails :: !(Maybe ChannelTopicDetails)
, _chaContentDetails :: !(Maybe ChannelContentDetails)
, _chaConversionPings :: !(Maybe ChannelConversionPings)
, _chaBrandingSettings :: !(Maybe ChannelBrandingSettings)
, _chaId :: !(Maybe Text)
, _chaStatistics :: !(Maybe ChannelStatistics)
, _chaLocalizations :: !(Maybe ChannelLocalizations)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Channel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'chaStatus'
--
-- * 'chaEtag'
--
-- * 'chaAuditDetails'
--
-- * 'chaContentOwnerDetails'
--
-- * 'chaSnippet'
--
-- * 'chaKind'
--
-- * 'chaTopicDetails'
--
-- * 'chaContentDetails'
--
-- * 'chaConversionPings'
--
-- * 'chaBrandingSettings'
--
-- * 'chaId'
--
-- * 'chaStatistics'
--
-- * 'chaLocalizations'
channel
:: Channel
channel =
Channel'
{ _chaStatus = Nothing
, _chaEtag = Nothing
, _chaAuditDetails = Nothing
, _chaContentOwnerDetails = Nothing
, _chaSnippet = Nothing
, _chaKind = "youtube#channel"
, _chaTopicDetails = Nothing
, _chaContentDetails = Nothing
, _chaConversionPings = Nothing
, _chaBrandingSettings = Nothing
, _chaId = Nothing
, _chaStatistics = Nothing
, _chaLocalizations = Nothing
}
-- | The status object encapsulates information about the privacy status of
-- the channel.
chaStatus :: Lens' Channel (Maybe ChannelStatus)
chaStatus
= lens _chaStatus (\ s a -> s{_chaStatus = a})
-- | Etag of this resource.
chaEtag :: Lens' Channel (Maybe Text)
chaEtag = lens _chaEtag (\ s a -> s{_chaEtag = a})
-- | The auditionDetails object encapsulates channel data that is relevant
-- for YouTube Partners during the audition process.
chaAuditDetails :: Lens' Channel (Maybe ChannelAuditDetails)
chaAuditDetails
= lens _chaAuditDetails
(\ s a -> s{_chaAuditDetails = a})
-- | The contentOwnerDetails object encapsulates channel data that is
-- relevant for YouTube Partners linked with the channel.
chaContentOwnerDetails :: Lens' Channel (Maybe ChannelContentOwnerDetails)
chaContentOwnerDetails
= lens _chaContentOwnerDetails
(\ s a -> s{_chaContentOwnerDetails = a})
-- | The snippet object contains basic details about the channel, such as its
-- title, description, and thumbnail images.
chaSnippet :: Lens' Channel (Maybe ChannelSnippet)
chaSnippet
= lens _chaSnippet (\ s a -> s{_chaSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#channel\".
chaKind :: Lens' Channel Text
chaKind = lens _chaKind (\ s a -> s{_chaKind = a})
-- | The topicDetails object encapsulates information about Freebase topics
-- associated with the channel.
chaTopicDetails :: Lens' Channel (Maybe ChannelTopicDetails)
chaTopicDetails
= lens _chaTopicDetails
(\ s a -> s{_chaTopicDetails = a})
-- | The contentDetails object encapsulates information about the channel\'s
-- content.
chaContentDetails :: Lens' Channel (Maybe ChannelContentDetails)
chaContentDetails
= lens _chaContentDetails
(\ s a -> s{_chaContentDetails = a})
-- | The conversionPings object encapsulates information about conversion
-- pings that need to be respected by the channel.
chaConversionPings :: Lens' Channel (Maybe ChannelConversionPings)
chaConversionPings
= lens _chaConversionPings
(\ s a -> s{_chaConversionPings = a})
-- | The brandingSettings object encapsulates information about the branding
-- of the channel.
chaBrandingSettings :: Lens' Channel (Maybe ChannelBrandingSettings)
chaBrandingSettings
= lens _chaBrandingSettings
(\ s a -> s{_chaBrandingSettings = a})
-- | The ID that YouTube uses to uniquely identify the channel.
chaId :: Lens' Channel (Maybe Text)
chaId = lens _chaId (\ s a -> s{_chaId = a})
-- | The statistics object encapsulates statistics for the channel.
chaStatistics :: Lens' Channel (Maybe ChannelStatistics)
chaStatistics
= lens _chaStatistics
(\ s a -> s{_chaStatistics = a})
-- | Localizations for different languages
chaLocalizations :: Lens' Channel (Maybe ChannelLocalizations)
chaLocalizations
= lens _chaLocalizations
(\ s a -> s{_chaLocalizations = a})
instance FromJSON Channel where
parseJSON
= withObject "Channel"
(\ o ->
Channel' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "auditDetails")
<*> (o .:? "contentOwnerDetails")
<*> (o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#channel")
<*> (o .:? "topicDetails")
<*> (o .:? "contentDetails")
<*> (o .:? "conversionPings")
<*> (o .:? "brandingSettings")
<*> (o .:? "id")
<*> (o .:? "statistics")
<*> (o .:? "localizations"))
instance ToJSON Channel where
toJSON Channel'{..}
= object
(catMaybes
[("status" .=) <$> _chaStatus,
("etag" .=) <$> _chaEtag,
("auditDetails" .=) <$> _chaAuditDetails,
("contentOwnerDetails" .=) <$>
_chaContentOwnerDetails,
("snippet" .=) <$> _chaSnippet,
Just ("kind" .= _chaKind),
("topicDetails" .=) <$> _chaTopicDetails,
("contentDetails" .=) <$> _chaContentDetails,
("conversionPings" .=) <$> _chaConversionPings,
("brandingSettings" .=) <$> _chaBrandingSettings,
("id" .=) <$> _chaId,
("statistics" .=) <$> _chaStatistics,
("localizations" .=) <$> _chaLocalizations])
-- | ChannelSection targeting setting.
--
-- /See:/ 'channelSectionTargeting' smart constructor.
data ChannelSectionTargeting =
ChannelSectionTargeting'
{ _cstRegions :: !(Maybe [Text])
, _cstCountries :: !(Maybe [Text])
, _cstLanguages :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSectionTargeting' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cstRegions'
--
-- * 'cstCountries'
--
-- * 'cstLanguages'
channelSectionTargeting
:: ChannelSectionTargeting
channelSectionTargeting =
ChannelSectionTargeting'
{_cstRegions = Nothing, _cstCountries = Nothing, _cstLanguages = Nothing}
-- | The region the channel section is targeting.
cstRegions :: Lens' ChannelSectionTargeting [Text]
cstRegions
= lens _cstRegions (\ s a -> s{_cstRegions = a}) .
_Default
. _Coerce
-- | The country the channel section is targeting.
cstCountries :: Lens' ChannelSectionTargeting [Text]
cstCountries
= lens _cstCountries (\ s a -> s{_cstCountries = a})
. _Default
. _Coerce
-- | The language the channel section is targeting.
cstLanguages :: Lens' ChannelSectionTargeting [Text]
cstLanguages
= lens _cstLanguages (\ s a -> s{_cstLanguages = a})
. _Default
. _Coerce
instance FromJSON ChannelSectionTargeting where
parseJSON
= withObject "ChannelSectionTargeting"
(\ o ->
ChannelSectionTargeting' <$>
(o .:? "regions" .!= mempty) <*>
(o .:? "countries" .!= mempty)
<*> (o .:? "languages" .!= mempty))
instance ToJSON ChannelSectionTargeting where
toJSON ChannelSectionTargeting'{..}
= object
(catMaybes
[("regions" .=) <$> _cstRegions,
("countries" .=) <$> _cstCountries,
("languages" .=) <$> _cstLanguages])
--
-- /See:/ 'liveStreamListResponse' smart constructor.
data LiveStreamListResponse =
LiveStreamListResponse'
{ _lslrEtag :: !(Maybe Text)
, _lslrTokenPagination :: !(Maybe TokenPagination)
, _lslrNextPageToken :: !(Maybe Text)
, _lslrPageInfo :: !(Maybe PageInfo)
, _lslrKind :: !Text
, _lslrItems :: !(Maybe [LiveStream])
, _lslrVisitorId :: !(Maybe Text)
, _lslrEventId :: !(Maybe Text)
, _lslrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStreamListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lslrEtag'
--
-- * 'lslrTokenPagination'
--
-- * 'lslrNextPageToken'
--
-- * 'lslrPageInfo'
--
-- * 'lslrKind'
--
-- * 'lslrItems'
--
-- * 'lslrVisitorId'
--
-- * 'lslrEventId'
--
-- * 'lslrPrevPageToken'
liveStreamListResponse
:: LiveStreamListResponse
liveStreamListResponse =
LiveStreamListResponse'
{ _lslrEtag = Nothing
, _lslrTokenPagination = Nothing
, _lslrNextPageToken = Nothing
, _lslrPageInfo = Nothing
, _lslrKind = "youtube#liveStreamListResponse"
, _lslrItems = Nothing
, _lslrVisitorId = Nothing
, _lslrEventId = Nothing
, _lslrPrevPageToken = Nothing
}
-- | Etag of this resource.
lslrEtag :: Lens' LiveStreamListResponse (Maybe Text)
lslrEtag = lens _lslrEtag (\ s a -> s{_lslrEtag = a})
lslrTokenPagination :: Lens' LiveStreamListResponse (Maybe TokenPagination)
lslrTokenPagination
= lens _lslrTokenPagination
(\ s a -> s{_lslrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
lslrNextPageToken :: Lens' LiveStreamListResponse (Maybe Text)
lslrNextPageToken
= lens _lslrNextPageToken
(\ s a -> s{_lslrNextPageToken = a})
lslrPageInfo :: Lens' LiveStreamListResponse (Maybe PageInfo)
lslrPageInfo
= lens _lslrPageInfo (\ s a -> s{_lslrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveStreamListResponse\".
lslrKind :: Lens' LiveStreamListResponse Text
lslrKind = lens _lslrKind (\ s a -> s{_lslrKind = a})
-- | A list of live streams that match the request criteria.
lslrItems :: Lens' LiveStreamListResponse [LiveStream]
lslrItems
= lens _lslrItems (\ s a -> s{_lslrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
lslrVisitorId :: Lens' LiveStreamListResponse (Maybe Text)
lslrVisitorId
= lens _lslrVisitorId
(\ s a -> s{_lslrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
lslrEventId :: Lens' LiveStreamListResponse (Maybe Text)
lslrEventId
= lens _lslrEventId (\ s a -> s{_lslrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
lslrPrevPageToken :: Lens' LiveStreamListResponse (Maybe Text)
lslrPrevPageToken
= lens _lslrPrevPageToken
(\ s a -> s{_lslrPrevPageToken = a})
instance FromJSON LiveStreamListResponse where
parseJSON
= withObject "LiveStreamListResponse"
(\ o ->
LiveStreamListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!= "youtube#liveStreamListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON LiveStreamListResponse where
toJSON LiveStreamListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _lslrEtag,
("tokenPagination" .=) <$> _lslrTokenPagination,
("nextPageToken" .=) <$> _lslrNextPageToken,
("pageInfo" .=) <$> _lslrPageInfo,
Just ("kind" .= _lslrKind),
("items" .=) <$> _lslrItems,
("visitorId" .=) <$> _lslrVisitorId,
("eventId" .=) <$> _lslrEventId,
("prevPageToken" .=) <$> _lslrPrevPageToken])
--
-- /See:/ 'testItem' smart constructor.
data TestItem =
TestItem'
{ _tiSnippet :: !(Maybe TestItemTestItemSnippet)
, _tiGaia :: !(Maybe (Textual Int64))
, _tiFeaturedPart :: !(Maybe Bool)
, _tiId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TestItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiSnippet'
--
-- * 'tiGaia'
--
-- * 'tiFeaturedPart'
--
-- * 'tiId'
testItem
:: TestItem
testItem =
TestItem'
{ _tiSnippet = Nothing
, _tiGaia = Nothing
, _tiFeaturedPart = Nothing
, _tiId = Nothing
}
tiSnippet :: Lens' TestItem (Maybe TestItemTestItemSnippet)
tiSnippet
= lens _tiSnippet (\ s a -> s{_tiSnippet = a})
tiGaia :: Lens' TestItem (Maybe Int64)
tiGaia
= lens _tiGaia (\ s a -> s{_tiGaia = a}) .
mapping _Coerce
tiFeaturedPart :: Lens' TestItem (Maybe Bool)
tiFeaturedPart
= lens _tiFeaturedPart
(\ s a -> s{_tiFeaturedPart = a})
tiId :: Lens' TestItem (Maybe Text)
tiId = lens _tiId (\ s a -> s{_tiId = a})
instance FromJSON TestItem where
parseJSON
= withObject "TestItem"
(\ o ->
TestItem' <$>
(o .:? "snippet") <*> (o .:? "gaia") <*>
(o .:? "featuredPart")
<*> (o .:? "id"))
instance ToJSON TestItem where
toJSON TestItem'{..}
= object
(catMaybes
[("snippet" .=) <$> _tiSnippet,
("gaia" .=) <$> _tiGaia,
("featuredPart" .=) <$> _tiFeaturedPart,
("id" .=) <$> _tiId])
-- | Localizations for different languages
--
-- /See:/ 'channelLocalizations' smart constructor.
newtype ChannelLocalizations =
ChannelLocalizations'
{ _clAddtional :: HashMap Text ChannelLocalization
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelLocalizations' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clAddtional'
channelLocalizations
:: HashMap Text ChannelLocalization -- ^ 'clAddtional'
-> ChannelLocalizations
channelLocalizations pClAddtional_ =
ChannelLocalizations' {_clAddtional = _Coerce # pClAddtional_}
clAddtional :: Lens' ChannelLocalizations (HashMap Text ChannelLocalization)
clAddtional
= lens _clAddtional (\ s a -> s{_clAddtional = a}) .
_Coerce
instance FromJSON ChannelLocalizations where
parseJSON
= withObject "ChannelLocalizations"
(\ o ->
ChannelLocalizations' <$> (parseJSONObject o))
instance ToJSON ChannelLocalizations where
toJSON = toJSON . _clAddtional
-- | Basic details about a playlist, including title, description and
-- thumbnails.
--
-- /See:/ 'playListSnippet' smart constructor.
data PlayListSnippet =
PlayListSnippet'
{ _plsPublishedAt :: !(Maybe DateTime')
, _plsChannelTitle :: !(Maybe Text)
, _plsChannelId :: !(Maybe Text)
, _plsThumbnails :: !(Maybe ThumbnailDetails)
, _plsLocalized :: !(Maybe PlayListLocalization)
, _plsTitle :: !(Maybe Text)
, _plsThumbnailVideoId :: !(Maybe Text)
, _plsDescription :: !(Maybe Text)
, _plsTags :: !(Maybe [Text])
, _plsDefaultLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plsPublishedAt'
--
-- * 'plsChannelTitle'
--
-- * 'plsChannelId'
--
-- * 'plsThumbnails'
--
-- * 'plsLocalized'
--
-- * 'plsTitle'
--
-- * 'plsThumbnailVideoId'
--
-- * 'plsDescription'
--
-- * 'plsTags'
--
-- * 'plsDefaultLanguage'
playListSnippet
:: PlayListSnippet
playListSnippet =
PlayListSnippet'
{ _plsPublishedAt = Nothing
, _plsChannelTitle = Nothing
, _plsChannelId = Nothing
, _plsThumbnails = Nothing
, _plsLocalized = Nothing
, _plsTitle = Nothing
, _plsThumbnailVideoId = Nothing
, _plsDescription = Nothing
, _plsTags = Nothing
, _plsDefaultLanguage = Nothing
}
-- | The date and time that the playlist was created.
plsPublishedAt :: Lens' PlayListSnippet (Maybe UTCTime)
plsPublishedAt
= lens _plsPublishedAt
(\ s a -> s{_plsPublishedAt = a})
. mapping _DateTime
-- | The channel title of the channel that the video belongs to.
plsChannelTitle :: Lens' PlayListSnippet (Maybe Text)
plsChannelTitle
= lens _plsChannelTitle
(\ s a -> s{_plsChannelTitle = a})
-- | The ID that YouTube uses to uniquely identify the channel that published
-- the playlist.
plsChannelId :: Lens' PlayListSnippet (Maybe Text)
plsChannelId
= lens _plsChannelId (\ s a -> s{_plsChannelId = a})
-- | A map of thumbnail images associated with the playlist. For each object
-- in the map, the key is the name of the thumbnail image, and the value is
-- an object that contains other information about the thumbnail.
plsThumbnails :: Lens' PlayListSnippet (Maybe ThumbnailDetails)
plsThumbnails
= lens _plsThumbnails
(\ s a -> s{_plsThumbnails = a})
-- | Localized title and description, read-only.
plsLocalized :: Lens' PlayListSnippet (Maybe PlayListLocalization)
plsLocalized
= lens _plsLocalized (\ s a -> s{_plsLocalized = a})
-- | The playlist\'s title.
plsTitle :: Lens' PlayListSnippet (Maybe Text)
plsTitle = lens _plsTitle (\ s a -> s{_plsTitle = a})
-- | Note: if the playlist has a custom thumbnail, this field will not be
-- populated. The video id selected by the user that will be used as the
-- thumbnail of this playlist. This field defaults to the first publicly
-- viewable video in the playlist, if: 1. The user has never selected a
-- video to be the thumbnail of the playlist. 2. The user selects a video
-- to be the thumbnail, and then removes that video from the playlist. 3.
-- The user selects a non-owned video to be the thumbnail, but that video
-- becomes private, or gets deleted.
plsThumbnailVideoId :: Lens' PlayListSnippet (Maybe Text)
plsThumbnailVideoId
= lens _plsThumbnailVideoId
(\ s a -> s{_plsThumbnailVideoId = a})
-- | The playlist\'s description.
plsDescription :: Lens' PlayListSnippet (Maybe Text)
plsDescription
= lens _plsDescription
(\ s a -> s{_plsDescription = a})
-- | Keyword tags associated with the playlist.
plsTags :: Lens' PlayListSnippet [Text]
plsTags
= lens _plsTags (\ s a -> s{_plsTags = a}) . _Default
. _Coerce
-- | The language of the playlist\'s default title and description.
plsDefaultLanguage :: Lens' PlayListSnippet (Maybe Text)
plsDefaultLanguage
= lens _plsDefaultLanguage
(\ s a -> s{_plsDefaultLanguage = a})
instance FromJSON PlayListSnippet where
parseJSON
= withObject "PlayListSnippet"
(\ o ->
PlayListSnippet' <$>
(o .:? "publishedAt") <*> (o .:? "channelTitle") <*>
(o .:? "channelId")
<*> (o .:? "thumbnails")
<*> (o .:? "localized")
<*> (o .:? "title")
<*> (o .:? "thumbnailVideoId")
<*> (o .:? "description")
<*> (o .:? "tags" .!= mempty)
<*> (o .:? "defaultLanguage"))
instance ToJSON PlayListSnippet where
toJSON PlayListSnippet'{..}
= object
(catMaybes
[("publishedAt" .=) <$> _plsPublishedAt,
("channelTitle" .=) <$> _plsChannelTitle,
("channelId" .=) <$> _plsChannelId,
("thumbnails" .=) <$> _plsThumbnails,
("localized" .=) <$> _plsLocalized,
("title" .=) <$> _plsTitle,
("thumbnailVideoId" .=) <$> _plsThumbnailVideoId,
("description" .=) <$> _plsDescription,
("tags" .=) <$> _plsTags,
("defaultLanguage" .=) <$> _plsDefaultLanguage])
--
-- /See:/ 'videoGetRatingResponse' smart constructor.
data VideoGetRatingResponse =
VideoGetRatingResponse'
{ _vgrrEtag :: !(Maybe Text)
, _vgrrKind :: !Text
, _vgrrItems :: !(Maybe [VideoRating])
, _vgrrVisitorId :: !(Maybe Text)
, _vgrrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoGetRatingResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vgrrEtag'
--
-- * 'vgrrKind'
--
-- * 'vgrrItems'
--
-- * 'vgrrVisitorId'
--
-- * 'vgrrEventId'
videoGetRatingResponse
:: VideoGetRatingResponse
videoGetRatingResponse =
VideoGetRatingResponse'
{ _vgrrEtag = Nothing
, _vgrrKind = "youtube#videoGetRatingResponse"
, _vgrrItems = Nothing
, _vgrrVisitorId = Nothing
, _vgrrEventId = Nothing
}
-- | Etag of this resource.
vgrrEtag :: Lens' VideoGetRatingResponse (Maybe Text)
vgrrEtag = lens _vgrrEtag (\ s a -> s{_vgrrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#videoGetRatingResponse\".
vgrrKind :: Lens' VideoGetRatingResponse Text
vgrrKind = lens _vgrrKind (\ s a -> s{_vgrrKind = a})
-- | A list of ratings that match the request criteria.
vgrrItems :: Lens' VideoGetRatingResponse [VideoRating]
vgrrItems
= lens _vgrrItems (\ s a -> s{_vgrrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
vgrrVisitorId :: Lens' VideoGetRatingResponse (Maybe Text)
vgrrVisitorId
= lens _vgrrVisitorId
(\ s a -> s{_vgrrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
vgrrEventId :: Lens' VideoGetRatingResponse (Maybe Text)
vgrrEventId
= lens _vgrrEventId (\ s a -> s{_vgrrEventId = a})
instance FromJSON VideoGetRatingResponse where
parseJSON
= withObject "VideoGetRatingResponse"
(\ o ->
VideoGetRatingResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "youtube#videoGetRatingResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON VideoGetRatingResponse where
toJSON VideoGetRatingResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _vgrrEtag,
Just ("kind" .= _vgrrKind),
("items" .=) <$> _vgrrItems,
("visitorId" .=) <$> _vgrrVisitorId,
("eventId" .=) <$> _vgrrEventId])
--
-- /See:/ 'superChatEventSnippet' smart constructor.
data SuperChatEventSnippet =
SuperChatEventSnippet'
{ _scesDisplayString :: !(Maybe Text)
, _scesSupporterDetails :: !(Maybe ChannelProFileDetails)
, _scesCreatedAt :: !(Maybe DateTime')
, _scesSuperStickerMetadata :: !(Maybe SuperStickerMetadata)
, _scesAmountMicros :: !(Maybe (Textual Word64))
, _scesMessageType :: !(Maybe (Textual Word32))
, _scesChannelId :: !(Maybe Text)
, _scesCommentText :: !(Maybe Text)
, _scesCurrency :: !(Maybe Text)
, _scesIsSuperStickerEvent :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SuperChatEventSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scesDisplayString'
--
-- * 'scesSupporterDetails'
--
-- * 'scesCreatedAt'
--
-- * 'scesSuperStickerMetadata'
--
-- * 'scesAmountMicros'
--
-- * 'scesMessageType'
--
-- * 'scesChannelId'
--
-- * 'scesCommentText'
--
-- * 'scesCurrency'
--
-- * 'scesIsSuperStickerEvent'
superChatEventSnippet
:: SuperChatEventSnippet
superChatEventSnippet =
SuperChatEventSnippet'
{ _scesDisplayString = Nothing
, _scesSupporterDetails = Nothing
, _scesCreatedAt = Nothing
, _scesSuperStickerMetadata = Nothing
, _scesAmountMicros = Nothing
, _scesMessageType = Nothing
, _scesChannelId = Nothing
, _scesCommentText = Nothing
, _scesCurrency = Nothing
, _scesIsSuperStickerEvent = Nothing
}
-- | A rendered string that displays the purchase amount and currency (e.g.,
-- \"$1.00\"). The string is rendered for the given language.
scesDisplayString :: Lens' SuperChatEventSnippet (Maybe Text)
scesDisplayString
= lens _scesDisplayString
(\ s a -> s{_scesDisplayString = a})
-- | Details about the supporter.
scesSupporterDetails :: Lens' SuperChatEventSnippet (Maybe ChannelProFileDetails)
scesSupporterDetails
= lens _scesSupporterDetails
(\ s a -> s{_scesSupporterDetails = a})
-- | The date and time when the event occurred.
scesCreatedAt :: Lens' SuperChatEventSnippet (Maybe UTCTime)
scesCreatedAt
= lens _scesCreatedAt
(\ s a -> s{_scesCreatedAt = a})
. mapping _DateTime
-- | If this event is a Super Sticker event, this field will contain metadata
-- about the Super Sticker.
scesSuperStickerMetadata :: Lens' SuperChatEventSnippet (Maybe SuperStickerMetadata)
scesSuperStickerMetadata
= lens _scesSuperStickerMetadata
(\ s a -> s{_scesSuperStickerMetadata = a})
-- | The purchase amount, in micros of the purchase currency. e.g., 1 is
-- represented as 1000000.
scesAmountMicros :: Lens' SuperChatEventSnippet (Maybe Word64)
scesAmountMicros
= lens _scesAmountMicros
(\ s a -> s{_scesAmountMicros = a})
. mapping _Coerce
-- | The tier for the paid message, which is based on the amount of money
-- spent to purchase the message.
scesMessageType :: Lens' SuperChatEventSnippet (Maybe Word32)
scesMessageType
= lens _scesMessageType
(\ s a -> s{_scesMessageType = a})
. mapping _Coerce
-- | Channel id where the event occurred.
scesChannelId :: Lens' SuperChatEventSnippet (Maybe Text)
scesChannelId
= lens _scesChannelId
(\ s a -> s{_scesChannelId = a})
-- | The text contents of the comment left by the user.
scesCommentText :: Lens' SuperChatEventSnippet (Maybe Text)
scesCommentText
= lens _scesCommentText
(\ s a -> s{_scesCommentText = a})
-- | The currency in which the purchase was made. ISO 4217.
scesCurrency :: Lens' SuperChatEventSnippet (Maybe Text)
scesCurrency
= lens _scesCurrency (\ s a -> s{_scesCurrency = a})
-- | True if this event is a Super Sticker event.
scesIsSuperStickerEvent :: Lens' SuperChatEventSnippet (Maybe Bool)
scesIsSuperStickerEvent
= lens _scesIsSuperStickerEvent
(\ s a -> s{_scesIsSuperStickerEvent = a})
instance FromJSON SuperChatEventSnippet where
parseJSON
= withObject "SuperChatEventSnippet"
(\ o ->
SuperChatEventSnippet' <$>
(o .:? "displayString") <*>
(o .:? "supporterDetails")
<*> (o .:? "createdAt")
<*> (o .:? "superStickerMetadata")
<*> (o .:? "amountMicros")
<*> (o .:? "messageType")
<*> (o .:? "channelId")
<*> (o .:? "commentText")
<*> (o .:? "currency")
<*> (o .:? "isSuperStickerEvent"))
instance ToJSON SuperChatEventSnippet where
toJSON SuperChatEventSnippet'{..}
= object
(catMaybes
[("displayString" .=) <$> _scesDisplayString,
("supporterDetails" .=) <$> _scesSupporterDetails,
("createdAt" .=) <$> _scesCreatedAt,
("superStickerMetadata" .=) <$>
_scesSuperStickerMetadata,
("amountMicros" .=) <$> _scesAmountMicros,
("messageType" .=) <$> _scesMessageType,
("channelId" .=) <$> _scesChannelId,
("commentText" .=) <$> _scesCommentText,
("currency" .=) <$> _scesCurrency,
("isSuperStickerEvent" .=) <$>
_scesIsSuperStickerEvent])
-- | Basic details about a video category, such as its localized title.
--
-- /See:/ 'videoAbuseReportReasonSnippet' smart constructor.
data VideoAbuseReportReasonSnippet =
VideoAbuseReportReasonSnippet'
{ _varrsSecondaryReasons :: !(Maybe [VideoAbuseReportSecondaryReason])
, _varrsLabel :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoAbuseReportReasonSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'varrsSecondaryReasons'
--
-- * 'varrsLabel'
videoAbuseReportReasonSnippet
:: VideoAbuseReportReasonSnippet
videoAbuseReportReasonSnippet =
VideoAbuseReportReasonSnippet'
{_varrsSecondaryReasons = Nothing, _varrsLabel = Nothing}
-- | The secondary reasons associated with this reason, if any are available.
-- (There might be 0 or more.)
varrsSecondaryReasons :: Lens' VideoAbuseReportReasonSnippet [VideoAbuseReportSecondaryReason]
varrsSecondaryReasons
= lens _varrsSecondaryReasons
(\ s a -> s{_varrsSecondaryReasons = a})
. _Default
. _Coerce
-- | The localized label belonging to this abuse report reason.
varrsLabel :: Lens' VideoAbuseReportReasonSnippet (Maybe Text)
varrsLabel
= lens _varrsLabel (\ s a -> s{_varrsLabel = a})
instance FromJSON VideoAbuseReportReasonSnippet where
parseJSON
= withObject "VideoAbuseReportReasonSnippet"
(\ o ->
VideoAbuseReportReasonSnippet' <$>
(o .:? "secondaryReasons" .!= mempty) <*>
(o .:? "label"))
instance ToJSON VideoAbuseReportReasonSnippet where
toJSON VideoAbuseReportReasonSnippet'{..}
= object
(catMaybes
[("secondaryReasons" .=) <$> _varrsSecondaryReasons,
("label" .=) <$> _varrsLabel])
-- | A *caption* resource represents a YouTube caption track. A caption track
-- is associated with exactly one YouTube video.
--
-- /See:/ 'caption' smart constructor.
data Caption =
Caption'
{ _capEtag :: !(Maybe Text)
, _capSnippet :: !(Maybe CaptionSnippet)
, _capKind :: !Text
, _capId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Caption' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'capEtag'
--
-- * 'capSnippet'
--
-- * 'capKind'
--
-- * 'capId'
caption
:: Caption
caption =
Caption'
{ _capEtag = Nothing
, _capSnippet = Nothing
, _capKind = "youtube#caption"
, _capId = Nothing
}
-- | Etag of this resource.
capEtag :: Lens' Caption (Maybe Text)
capEtag = lens _capEtag (\ s a -> s{_capEtag = a})
-- | The snippet object contains basic details about the caption.
capSnippet :: Lens' Caption (Maybe CaptionSnippet)
capSnippet
= lens _capSnippet (\ s a -> s{_capSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#caption\".
capKind :: Lens' Caption Text
capKind = lens _capKind (\ s a -> s{_capKind = a})
-- | The ID that YouTube uses to uniquely identify the caption track.
capId :: Lens' Caption (Maybe Text)
capId = lens _capId (\ s a -> s{_capId = a})
instance FromJSON Caption where
parseJSON
= withObject "Caption"
(\ o ->
Caption' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#caption")
<*> (o .:? "id"))
instance ToJSON Caption where
toJSON Caption'{..}
= object
(catMaybes
[("etag" .=) <$> _capEtag,
("snippet" .=) <$> _capSnippet,
Just ("kind" .= _capKind), ("id" .=) <$> _capId])
-- | DEPRECATED Region restriction of the video.
--
-- /See:/ 'videoContentDetailsRegionRestriction' smart constructor.
data VideoContentDetailsRegionRestriction =
VideoContentDetailsRegionRestriction'
{ _vcdrrAllowed :: !(Maybe [Text])
, _vcdrrBlocked :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoContentDetailsRegionRestriction' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vcdrrAllowed'
--
-- * 'vcdrrBlocked'
videoContentDetailsRegionRestriction
:: VideoContentDetailsRegionRestriction
videoContentDetailsRegionRestriction =
VideoContentDetailsRegionRestriction'
{_vcdrrAllowed = Nothing, _vcdrrBlocked = Nothing}
-- | A list of region codes that identify countries where the video is
-- viewable. If this property is present and a country is not listed in its
-- value, then the video is blocked from appearing in that country. If this
-- property is present and contains an empty list, the video is blocked in
-- all countries.
vcdrrAllowed :: Lens' VideoContentDetailsRegionRestriction [Text]
vcdrrAllowed
= lens _vcdrrAllowed (\ s a -> s{_vcdrrAllowed = a})
. _Default
. _Coerce
-- | A list of region codes that identify countries where the video is
-- blocked. If this property is present and a country is not listed in its
-- value, then the video is viewable in that country. If this property is
-- present and contains an empty list, the video is viewable in all
-- countries.
vcdrrBlocked :: Lens' VideoContentDetailsRegionRestriction [Text]
vcdrrBlocked
= lens _vcdrrBlocked (\ s a -> s{_vcdrrBlocked = a})
. _Default
. _Coerce
instance FromJSON
VideoContentDetailsRegionRestriction
where
parseJSON
= withObject "VideoContentDetailsRegionRestriction"
(\ o ->
VideoContentDetailsRegionRestriction' <$>
(o .:? "allowed" .!= mempty) <*>
(o .:? "blocked" .!= mempty))
instance ToJSON VideoContentDetailsRegionRestriction
where
toJSON VideoContentDetailsRegionRestriction'{..}
= object
(catMaybes
[("allowed" .=) <$> _vcdrrAllowed,
("blocked" .=) <$> _vcdrrBlocked])
-- | Describes a temporal position of a visual widget inside a video.
--
-- /See:/ 'invideoTiming' smart constructor.
data InvideoTiming =
InvideoTiming'
{ _itDurationMs :: !(Maybe (Textual Word64))
, _itOffSetMs :: !(Maybe (Textual Word64))
, _itType :: !(Maybe InvideoTimingType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InvideoTiming' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'itDurationMs'
--
-- * 'itOffSetMs'
--
-- * 'itType'
invideoTiming
:: InvideoTiming
invideoTiming =
InvideoTiming'
{_itDurationMs = Nothing, _itOffSetMs = Nothing, _itType = Nothing}
-- | Defines the duration in milliseconds for which the promotion should be
-- displayed. If missing, the client should use the default.
itDurationMs :: Lens' InvideoTiming (Maybe Word64)
itDurationMs
= lens _itDurationMs (\ s a -> s{_itDurationMs = a})
. mapping _Coerce
-- | Defines the time at which the promotion will appear. Depending on the
-- value of type the value of the offsetMs field will represent a time
-- offset from the start or from the end of the video, expressed in
-- milliseconds.
itOffSetMs :: Lens' InvideoTiming (Maybe Word64)
itOffSetMs
= lens _itOffSetMs (\ s a -> s{_itOffSetMs = a}) .
mapping _Coerce
-- | Describes a timing type. If the value is offsetFromStart, then the
-- offsetMs field represents an offset from the start of the video. If the
-- value is offsetFromEnd, then the offsetMs field represents an offset
-- from the end of the video.
itType :: Lens' InvideoTiming (Maybe InvideoTimingType)
itType = lens _itType (\ s a -> s{_itType = a})
instance FromJSON InvideoTiming where
parseJSON
= withObject "InvideoTiming"
(\ o ->
InvideoTiming' <$>
(o .:? "durationMs") <*> (o .:? "offsetMs") <*>
(o .:? "type"))
instance ToJSON InvideoTiming where
toJSON InvideoTiming'{..}
= object
(catMaybes
[("durationMs" .=) <$> _itDurationMs,
("offsetMs" .=) <$> _itOffSetMs,
("type" .=) <$> _itType])
-- | Localizations for different languages
--
-- /See:/ 'playListLocalizations' smart constructor.
newtype PlayListLocalizations =
PlayListLocalizations'
{ _pllAddtional :: HashMap Text PlayListLocalization
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListLocalizations' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllAddtional'
playListLocalizations
:: HashMap Text PlayListLocalization -- ^ 'pllAddtional'
-> PlayListLocalizations
playListLocalizations pPllAddtional_ =
PlayListLocalizations' {_pllAddtional = _Coerce # pPllAddtional_}
pllAddtional :: Lens' PlayListLocalizations (HashMap Text PlayListLocalization)
pllAddtional
= lens _pllAddtional (\ s a -> s{_pllAddtional = a})
. _Coerce
instance FromJSON PlayListLocalizations where
parseJSON
= withObject "PlayListLocalizations"
(\ o ->
PlayListLocalizations' <$> (parseJSONObject o))
instance ToJSON PlayListLocalizations where
toJSON = toJSON . _pllAddtional
-- | Video processing progress and completion time estimate.
--
-- /See:/ 'videoProcessingDetailsProcessingProgress' smart constructor.
data VideoProcessingDetailsProcessingProgress =
VideoProcessingDetailsProcessingProgress'
{ _vpdppTimeLeftMs :: !(Maybe (Textual Word64))
, _vpdppPartsTotal :: !(Maybe (Textual Word64))
, _vpdppPartsProcessed :: !(Maybe (Textual Word64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoProcessingDetailsProcessingProgress' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vpdppTimeLeftMs'
--
-- * 'vpdppPartsTotal'
--
-- * 'vpdppPartsProcessed'
videoProcessingDetailsProcessingProgress
:: VideoProcessingDetailsProcessingProgress
videoProcessingDetailsProcessingProgress =
VideoProcessingDetailsProcessingProgress'
{ _vpdppTimeLeftMs = Nothing
, _vpdppPartsTotal = Nothing
, _vpdppPartsProcessed = Nothing
}
-- | An estimate of the amount of time, in millseconds, that YouTube needs to
-- finish processing the video.
vpdppTimeLeftMs :: Lens' VideoProcessingDetailsProcessingProgress (Maybe Word64)
vpdppTimeLeftMs
= lens _vpdppTimeLeftMs
(\ s a -> s{_vpdppTimeLeftMs = a})
. mapping _Coerce
-- | An estimate of the total number of parts that need to be processed for
-- the video. The number may be updated with more precise estimates while
-- YouTube processes the video.
vpdppPartsTotal :: Lens' VideoProcessingDetailsProcessingProgress (Maybe Word64)
vpdppPartsTotal
= lens _vpdppPartsTotal
(\ s a -> s{_vpdppPartsTotal = a})
. mapping _Coerce
-- | The number of parts of the video that YouTube has already processed. You
-- can estimate the percentage of the video that YouTube has already
-- processed by calculating: 100 * parts_processed \/ parts_total Note that
-- since the estimated number of parts could increase without a
-- corresponding increase in the number of parts that have already been
-- processed, it is possible that the calculated progress could
-- periodically decrease while YouTube processes a video.
vpdppPartsProcessed :: Lens' VideoProcessingDetailsProcessingProgress (Maybe Word64)
vpdppPartsProcessed
= lens _vpdppPartsProcessed
(\ s a -> s{_vpdppPartsProcessed = a})
. mapping _Coerce
instance FromJSON
VideoProcessingDetailsProcessingProgress
where
parseJSON
= withObject
"VideoProcessingDetailsProcessingProgress"
(\ o ->
VideoProcessingDetailsProcessingProgress' <$>
(o .:? "timeLeftMs") <*> (o .:? "partsTotal") <*>
(o .:? "partsProcessed"))
instance ToJSON
VideoProcessingDetailsProcessingProgress
where
toJSON VideoProcessingDetailsProcessingProgress'{..}
= object
(catMaybes
[("timeLeftMs" .=) <$> _vpdppTimeLeftMs,
("partsTotal" .=) <$> _vpdppPartsTotal,
("partsProcessed" .=) <$> _vpdppPartsProcessed])
-- | Basic details about a channel, including title, description and
-- thumbnails.
--
-- /See:/ 'channelSnippet' smart constructor.
data ChannelSnippet =
ChannelSnippet'
{ _csPublishedAt :: !(Maybe DateTime')
, _csCountry :: !(Maybe Text)
, _csThumbnails :: !(Maybe ThumbnailDetails)
, _csLocalized :: !(Maybe ChannelLocalization)
, _csCustomURL :: !(Maybe Text)
, _csTitle :: !(Maybe Text)
, _csDescription :: !(Maybe Text)
, _csDefaultLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csPublishedAt'
--
-- * 'csCountry'
--
-- * 'csThumbnails'
--
-- * 'csLocalized'
--
-- * 'csCustomURL'
--
-- * 'csTitle'
--
-- * 'csDescription'
--
-- * 'csDefaultLanguage'
channelSnippet
:: ChannelSnippet
channelSnippet =
ChannelSnippet'
{ _csPublishedAt = Nothing
, _csCountry = Nothing
, _csThumbnails = Nothing
, _csLocalized = Nothing
, _csCustomURL = Nothing
, _csTitle = Nothing
, _csDescription = Nothing
, _csDefaultLanguage = Nothing
}
-- | The date and time that the channel was created.
csPublishedAt :: Lens' ChannelSnippet (Maybe UTCTime)
csPublishedAt
= lens _csPublishedAt
(\ s a -> s{_csPublishedAt = a})
. mapping _DateTime
-- | The country of the channel.
csCountry :: Lens' ChannelSnippet (Maybe Text)
csCountry
= lens _csCountry (\ s a -> s{_csCountry = a})
-- | A map of thumbnail images associated with the channel. For each object
-- in the map, the key is the name of the thumbnail image, and the value is
-- an object that contains other information about the thumbnail. When
-- displaying thumbnails in your application, make sure that your code uses
-- the image URLs exactly as they are returned in API responses. For
-- example, your application should not use the http domain instead of the
-- https domain in a URL returned in an API response. Beginning in July
-- 2018, channel thumbnail URLs will only be available in the https domain,
-- which is how the URLs appear in API responses. After that time, you
-- might see broken images in your application if it tries to load YouTube
-- images from the http domain. Thumbnail images might be empty for newly
-- created channels and might take up to one day to populate.
csThumbnails :: Lens' ChannelSnippet (Maybe ThumbnailDetails)
csThumbnails
= lens _csThumbnails (\ s a -> s{_csThumbnails = a})
-- | Localized title and description, read-only.
csLocalized :: Lens' ChannelSnippet (Maybe ChannelLocalization)
csLocalized
= lens _csLocalized (\ s a -> s{_csLocalized = a})
-- | The custom url of the channel.
csCustomURL :: Lens' ChannelSnippet (Maybe Text)
csCustomURL
= lens _csCustomURL (\ s a -> s{_csCustomURL = a})
-- | The channel\'s title.
csTitle :: Lens' ChannelSnippet (Maybe Text)
csTitle = lens _csTitle (\ s a -> s{_csTitle = a})
-- | The description of the channel.
csDescription :: Lens' ChannelSnippet (Maybe Text)
csDescription
= lens _csDescription
(\ s a -> s{_csDescription = a})
-- | The language of the channel\'s default title and description.
csDefaultLanguage :: Lens' ChannelSnippet (Maybe Text)
csDefaultLanguage
= lens _csDefaultLanguage
(\ s a -> s{_csDefaultLanguage = a})
instance FromJSON ChannelSnippet where
parseJSON
= withObject "ChannelSnippet"
(\ o ->
ChannelSnippet' <$>
(o .:? "publishedAt") <*> (o .:? "country") <*>
(o .:? "thumbnails")
<*> (o .:? "localized")
<*> (o .:? "customUrl")
<*> (o .:? "title")
<*> (o .:? "description")
<*> (o .:? "defaultLanguage"))
instance ToJSON ChannelSnippet where
toJSON ChannelSnippet'{..}
= object
(catMaybes
[("publishedAt" .=) <$> _csPublishedAt,
("country" .=) <$> _csCountry,
("thumbnails" .=) <$> _csThumbnails,
("localized" .=) <$> _csLocalized,
("customUrl" .=) <$> _csCustomURL,
("title" .=) <$> _csTitle,
("description" .=) <$> _csDescription,
("defaultLanguage" .=) <$> _csDefaultLanguage])
-- | Internal representation of thumbnails for a YouTube resource.
--
-- /See:/ 'thumbnailDetails' smart constructor.
data ThumbnailDetails =
ThumbnailDetails'
{ _tdMedium :: !(Maybe Thumbnail)
, _tdMaxres :: !(Maybe Thumbnail)
, _tdDefault :: !(Maybe Thumbnail)
, _tdStandard :: !(Maybe Thumbnail)
, _tdHigh :: !(Maybe Thumbnail)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ThumbnailDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tdMedium'
--
-- * 'tdMaxres'
--
-- * 'tdDefault'
--
-- * 'tdStandard'
--
-- * 'tdHigh'
thumbnailDetails
:: ThumbnailDetails
thumbnailDetails =
ThumbnailDetails'
{ _tdMedium = Nothing
, _tdMaxres = Nothing
, _tdDefault = Nothing
, _tdStandard = Nothing
, _tdHigh = Nothing
}
-- | The medium quality image for this resource.
tdMedium :: Lens' ThumbnailDetails (Maybe Thumbnail)
tdMedium = lens _tdMedium (\ s a -> s{_tdMedium = a})
-- | The maximum resolution quality image for this resource.
tdMaxres :: Lens' ThumbnailDetails (Maybe Thumbnail)
tdMaxres = lens _tdMaxres (\ s a -> s{_tdMaxres = a})
-- | The default image for this resource.
tdDefault :: Lens' ThumbnailDetails (Maybe Thumbnail)
tdDefault
= lens _tdDefault (\ s a -> s{_tdDefault = a})
-- | The standard quality image for this resource.
tdStandard :: Lens' ThumbnailDetails (Maybe Thumbnail)
tdStandard
= lens _tdStandard (\ s a -> s{_tdStandard = a})
-- | The high quality image for this resource.
tdHigh :: Lens' ThumbnailDetails (Maybe Thumbnail)
tdHigh = lens _tdHigh (\ s a -> s{_tdHigh = a})
instance FromJSON ThumbnailDetails where
parseJSON
= withObject "ThumbnailDetails"
(\ o ->
ThumbnailDetails' <$>
(o .:? "medium") <*> (o .:? "maxres") <*>
(o .:? "default")
<*> (o .:? "standard")
<*> (o .:? "high"))
instance ToJSON ThumbnailDetails where
toJSON ThumbnailDetails'{..}
= object
(catMaybes
[("medium" .=) <$> _tdMedium,
("maxres" .=) <$> _tdMaxres,
("default" .=) <$> _tdDefault,
("standard" .=) <$> _tdStandard,
("high" .=) <$> _tdHigh])
-- | Settings and Info of the monitor stream
--
-- /See:/ 'monitorStreamInfo' smart constructor.
data MonitorStreamInfo =
MonitorStreamInfo'
{ _msiBroadcastStreamDelayMs :: !(Maybe (Textual Word32))
, _msiEmbedHTML :: !(Maybe Text)
, _msiEnableMonitorStream :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MonitorStreamInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'msiBroadcastStreamDelayMs'
--
-- * 'msiEmbedHTML'
--
-- * 'msiEnableMonitorStream'
monitorStreamInfo
:: MonitorStreamInfo
monitorStreamInfo =
MonitorStreamInfo'
{ _msiBroadcastStreamDelayMs = Nothing
, _msiEmbedHTML = Nothing
, _msiEnableMonitorStream = Nothing
}
-- | If you have set the enableMonitorStream property to true, then this
-- property determines the length of the live broadcast delay.
msiBroadcastStreamDelayMs :: Lens' MonitorStreamInfo (Maybe Word32)
msiBroadcastStreamDelayMs
= lens _msiBroadcastStreamDelayMs
(\ s a -> s{_msiBroadcastStreamDelayMs = a})
. mapping _Coerce
-- | HTML code that embeds a player that plays the monitor stream.
msiEmbedHTML :: Lens' MonitorStreamInfo (Maybe Text)
msiEmbedHTML
= lens _msiEmbedHTML (\ s a -> s{_msiEmbedHTML = a})
-- | This value determines whether the monitor stream is enabled for the
-- broadcast. If the monitor stream is enabled, then YouTube will broadcast
-- the event content on a special stream intended only for the
-- broadcaster\'s consumption. The broadcaster can use the stream to review
-- the event content and also to identify the optimal times to insert
-- cuepoints. You need to set this value to true if you intend to have a
-- broadcast delay for your event. *Note:* This property cannot be updated
-- once the broadcast is in the testing or live state.
msiEnableMonitorStream :: Lens' MonitorStreamInfo (Maybe Bool)
msiEnableMonitorStream
= lens _msiEnableMonitorStream
(\ s a -> s{_msiEnableMonitorStream = a})
instance FromJSON MonitorStreamInfo where
parseJSON
= withObject "MonitorStreamInfo"
(\ o ->
MonitorStreamInfo' <$>
(o .:? "broadcastStreamDelayMs") <*>
(o .:? "embedHtml")
<*> (o .:? "enableMonitorStream"))
instance ToJSON MonitorStreamInfo where
toJSON MonitorStreamInfo'{..}
= object
(catMaybes
[("broadcastStreamDelayMs" .=) <$>
_msiBroadcastStreamDelayMs,
("embedHtml" .=) <$> _msiEmbedHTML,
("enableMonitorStream" .=) <$>
_msiEnableMonitorStream])
--
-- /See:/ 'liveChatMessageSnippet' smart constructor.
data LiveChatMessageSnippet =
LiveChatMessageSnippet'
{ _lcmsMessageDeletedDetails :: !(Maybe LiveChatMessageDeletedDetails)
, _lcmsSuperStickerDetails :: !(Maybe LiveChatSuperStickerDetails)
, _lcmsLiveChatId :: !(Maybe Text)
, _lcmsPublishedAt :: !(Maybe DateTime')
, _lcmsUserBannedDetails :: !(Maybe LiveChatUserBannedMessageDetails)
, _lcmsTextMessageDetails :: !(Maybe LiveChatTextMessageDetails)
, _lcmsMessageRetractedDetails :: !(Maybe LiveChatMessageRetractedDetails)
, _lcmsSuperChatDetails :: !(Maybe LiveChatSuperChatDetails)
, _lcmsType :: !(Maybe LiveChatMessageSnippetType)
, _lcmsAuthorChannelId :: !(Maybe Text)
, _lcmsFanFundingEventDetails :: !(Maybe LiveChatFanFundingEventDetails)
, _lcmsHasDisplayContent :: !(Maybe Bool)
, _lcmsDisplayMessage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatMessageSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcmsMessageDeletedDetails'
--
-- * 'lcmsSuperStickerDetails'
--
-- * 'lcmsLiveChatId'
--
-- * 'lcmsPublishedAt'
--
-- * 'lcmsUserBannedDetails'
--
-- * 'lcmsTextMessageDetails'
--
-- * 'lcmsMessageRetractedDetails'
--
-- * 'lcmsSuperChatDetails'
--
-- * 'lcmsType'
--
-- * 'lcmsAuthorChannelId'
--
-- * 'lcmsFanFundingEventDetails'
--
-- * 'lcmsHasDisplayContent'
--
-- * 'lcmsDisplayMessage'
liveChatMessageSnippet
:: LiveChatMessageSnippet
liveChatMessageSnippet =
LiveChatMessageSnippet'
{ _lcmsMessageDeletedDetails = Nothing
, _lcmsSuperStickerDetails = Nothing
, _lcmsLiveChatId = Nothing
, _lcmsPublishedAt = Nothing
, _lcmsUserBannedDetails = Nothing
, _lcmsTextMessageDetails = Nothing
, _lcmsMessageRetractedDetails = Nothing
, _lcmsSuperChatDetails = Nothing
, _lcmsType = Nothing
, _lcmsAuthorChannelId = Nothing
, _lcmsFanFundingEventDetails = Nothing
, _lcmsHasDisplayContent = Nothing
, _lcmsDisplayMessage = Nothing
}
lcmsMessageDeletedDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatMessageDeletedDetails)
lcmsMessageDeletedDetails
= lens _lcmsMessageDeletedDetails
(\ s a -> s{_lcmsMessageDeletedDetails = a})
-- | Details about the Super Sticker event, this is only set if the type is
-- \'superStickerEvent\'.
lcmsSuperStickerDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatSuperStickerDetails)
lcmsSuperStickerDetails
= lens _lcmsSuperStickerDetails
(\ s a -> s{_lcmsSuperStickerDetails = a})
lcmsLiveChatId :: Lens' LiveChatMessageSnippet (Maybe Text)
lcmsLiveChatId
= lens _lcmsLiveChatId
(\ s a -> s{_lcmsLiveChatId = a})
-- | The date and time when the message was orignally published.
lcmsPublishedAt :: Lens' LiveChatMessageSnippet (Maybe UTCTime)
lcmsPublishedAt
= lens _lcmsPublishedAt
(\ s a -> s{_lcmsPublishedAt = a})
. mapping _DateTime
lcmsUserBannedDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatUserBannedMessageDetails)
lcmsUserBannedDetails
= lens _lcmsUserBannedDetails
(\ s a -> s{_lcmsUserBannedDetails = a})
-- | Details about the text message, this is only set if the type is
-- \'textMessageEvent\'.
lcmsTextMessageDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatTextMessageDetails)
lcmsTextMessageDetails
= lens _lcmsTextMessageDetails
(\ s a -> s{_lcmsTextMessageDetails = a})
lcmsMessageRetractedDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatMessageRetractedDetails)
lcmsMessageRetractedDetails
= lens _lcmsMessageRetractedDetails
(\ s a -> s{_lcmsMessageRetractedDetails = a})
-- | Details about the Super Chat event, this is only set if the type is
-- \'superChatEvent\'.
lcmsSuperChatDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatSuperChatDetails)
lcmsSuperChatDetails
= lens _lcmsSuperChatDetails
(\ s a -> s{_lcmsSuperChatDetails = a})
-- | The type of message, this will always be present, it determines the
-- contents of the message as well as which fields will be present.
lcmsType :: Lens' LiveChatMessageSnippet (Maybe LiveChatMessageSnippetType)
lcmsType = lens _lcmsType (\ s a -> s{_lcmsType = a})
-- | The ID of the user that authored this message, this field is not always
-- filled. textMessageEvent - the user that wrote the message
-- fanFundingEvent - the user that funded the broadcast newSponsorEvent -
-- the user that just became a sponsor messageDeletedEvent - the moderator
-- that took the action messageRetractedEvent - the author that retracted
-- their message userBannedEvent - the moderator that took the action
-- superChatEvent - the user that made the purchase
lcmsAuthorChannelId :: Lens' LiveChatMessageSnippet (Maybe Text)
lcmsAuthorChannelId
= lens _lcmsAuthorChannelId
(\ s a -> s{_lcmsAuthorChannelId = a})
-- | Details about the funding event, this is only set if the type is
-- \'fanFundingEvent\'.
lcmsFanFundingEventDetails :: Lens' LiveChatMessageSnippet (Maybe LiveChatFanFundingEventDetails)
lcmsFanFundingEventDetails
= lens _lcmsFanFundingEventDetails
(\ s a -> s{_lcmsFanFundingEventDetails = a})
-- | Whether the message has display content that should be displayed to
-- users.
lcmsHasDisplayContent :: Lens' LiveChatMessageSnippet (Maybe Bool)
lcmsHasDisplayContent
= lens _lcmsHasDisplayContent
(\ s a -> s{_lcmsHasDisplayContent = a})
-- | Contains a string that can be displayed to the user. If this field is
-- not present the message is silent, at the moment only messages of type
-- TOMBSTONE and CHAT_ENDED_EVENT are silent.
lcmsDisplayMessage :: Lens' LiveChatMessageSnippet (Maybe Text)
lcmsDisplayMessage
= lens _lcmsDisplayMessage
(\ s a -> s{_lcmsDisplayMessage = a})
instance FromJSON LiveChatMessageSnippet where
parseJSON
= withObject "LiveChatMessageSnippet"
(\ o ->
LiveChatMessageSnippet' <$>
(o .:? "messageDeletedDetails") <*>
(o .:? "superStickerDetails")
<*> (o .:? "liveChatId")
<*> (o .:? "publishedAt")
<*> (o .:? "userBannedDetails")
<*> (o .:? "textMessageDetails")
<*> (o .:? "messageRetractedDetails")
<*> (o .:? "superChatDetails")
<*> (o .:? "type")
<*> (o .:? "authorChannelId")
<*> (o .:? "fanFundingEventDetails")
<*> (o .:? "hasDisplayContent")
<*> (o .:? "displayMessage"))
instance ToJSON LiveChatMessageSnippet where
toJSON LiveChatMessageSnippet'{..}
= object
(catMaybes
[("messageDeletedDetails" .=) <$>
_lcmsMessageDeletedDetails,
("superStickerDetails" .=) <$>
_lcmsSuperStickerDetails,
("liveChatId" .=) <$> _lcmsLiveChatId,
("publishedAt" .=) <$> _lcmsPublishedAt,
("userBannedDetails" .=) <$> _lcmsUserBannedDetails,
("textMessageDetails" .=) <$>
_lcmsTextMessageDetails,
("messageRetractedDetails" .=) <$>
_lcmsMessageRetractedDetails,
("superChatDetails" .=) <$> _lcmsSuperChatDetails,
("type" .=) <$> _lcmsType,
("authorChannelId" .=) <$> _lcmsAuthorChannelId,
("fanFundingEventDetails" .=) <$>
_lcmsFanFundingEventDetails,
("hasDisplayContent" .=) <$> _lcmsHasDisplayContent,
("displayMessage" .=) <$> _lcmsDisplayMessage])
-- | A *i18nRegion* resource identifies a region where YouTube is available.
--
-- /See:/ 'i18nRegion' smart constructor.
data I18nRegion =
I18nRegion'
{ _irEtag :: !(Maybe Text)
, _irSnippet :: !(Maybe I18nRegionSnippet)
, _irKind :: !Text
, _irId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nRegion' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'irEtag'
--
-- * 'irSnippet'
--
-- * 'irKind'
--
-- * 'irId'
i18nRegion
:: I18nRegion
i18nRegion =
I18nRegion'
{ _irEtag = Nothing
, _irSnippet = Nothing
, _irKind = "youtube#i18nRegion"
, _irId = Nothing
}
-- | Etag of this resource.
irEtag :: Lens' I18nRegion (Maybe Text)
irEtag = lens _irEtag (\ s a -> s{_irEtag = a})
-- | The snippet object contains basic details about the i18n region, such as
-- region code and human-readable name.
irSnippet :: Lens' I18nRegion (Maybe I18nRegionSnippet)
irSnippet
= lens _irSnippet (\ s a -> s{_irSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#i18nRegion\".
irKind :: Lens' I18nRegion Text
irKind = lens _irKind (\ s a -> s{_irKind = a})
-- | The ID that YouTube uses to uniquely identify the i18n region.
irId :: Lens' I18nRegion (Maybe Text)
irId = lens _irId (\ s a -> s{_irId = a})
instance FromJSON I18nRegion where
parseJSON
= withObject "I18nRegion"
(\ o ->
I18nRegion' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#i18nRegion")
<*> (o .:? "id"))
instance ToJSON I18nRegion where
toJSON I18nRegion'{..}
= object
(catMaybes
[("etag" .=) <$> _irEtag,
("snippet" .=) <$> _irSnippet,
Just ("kind" .= _irKind), ("id" .=) <$> _irId])
-- | Statistics about a channel: number of subscribers, number of videos in
-- the channel, etc.
--
-- /See:/ 'channelStatistics' smart constructor.
data ChannelStatistics =
ChannelStatistics'
{ _csCommentCount :: !(Maybe (Textual Word64))
, _csSubscriberCount :: !(Maybe (Textual Word64))
, _csVideoCount :: !(Maybe (Textual Word64))
, _csHiddenSubscriberCount :: !(Maybe Bool)
, _csViewCount :: !(Maybe (Textual Word64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelStatistics' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csCommentCount'
--
-- * 'csSubscriberCount'
--
-- * 'csVideoCount'
--
-- * 'csHiddenSubscriberCount'
--
-- * 'csViewCount'
channelStatistics
:: ChannelStatistics
channelStatistics =
ChannelStatistics'
{ _csCommentCount = Nothing
, _csSubscriberCount = Nothing
, _csVideoCount = Nothing
, _csHiddenSubscriberCount = Nothing
, _csViewCount = Nothing
}
-- | The number of comments for the channel.
csCommentCount :: Lens' ChannelStatistics (Maybe Word64)
csCommentCount
= lens _csCommentCount
(\ s a -> s{_csCommentCount = a})
. mapping _Coerce
-- | The number of subscribers that the channel has.
csSubscriberCount :: Lens' ChannelStatistics (Maybe Word64)
csSubscriberCount
= lens _csSubscriberCount
(\ s a -> s{_csSubscriberCount = a})
. mapping _Coerce
-- | The number of videos uploaded to the channel.
csVideoCount :: Lens' ChannelStatistics (Maybe Word64)
csVideoCount
= lens _csVideoCount (\ s a -> s{_csVideoCount = a})
. mapping _Coerce
-- | Whether or not the number of subscribers is shown for this user.
csHiddenSubscriberCount :: Lens' ChannelStatistics (Maybe Bool)
csHiddenSubscriberCount
= lens _csHiddenSubscriberCount
(\ s a -> s{_csHiddenSubscriberCount = a})
-- | The number of times the channel has been viewed.
csViewCount :: Lens' ChannelStatistics (Maybe Word64)
csViewCount
= lens _csViewCount (\ s a -> s{_csViewCount = a}) .
mapping _Coerce
instance FromJSON ChannelStatistics where
parseJSON
= withObject "ChannelStatistics"
(\ o ->
ChannelStatistics' <$>
(o .:? "commentCount") <*> (o .:? "subscriberCount")
<*> (o .:? "videoCount")
<*> (o .:? "hiddenSubscriberCount")
<*> (o .:? "viewCount"))
instance ToJSON ChannelStatistics where
toJSON ChannelStatistics'{..}
= object
(catMaybes
[("commentCount" .=) <$> _csCommentCount,
("subscriberCount" .=) <$> _csSubscriberCount,
("videoCount" .=) <$> _csVideoCount,
("hiddenSubscriberCount" .=) <$>
_csHiddenSubscriberCount,
("viewCount" .=) <$> _csViewCount])
--
-- /See:/ 'liveChatFanFundingEventDetails' smart constructor.
data LiveChatFanFundingEventDetails =
LiveChatFanFundingEventDetails'
{ _lcffedUserComment :: !(Maybe Text)
, _lcffedAmountMicros :: !(Maybe (Textual Word64))
, _lcffedAmountDisplayString :: !(Maybe Text)
, _lcffedCurrency :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatFanFundingEventDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcffedUserComment'
--
-- * 'lcffedAmountMicros'
--
-- * 'lcffedAmountDisplayString'
--
-- * 'lcffedCurrency'
liveChatFanFundingEventDetails
:: LiveChatFanFundingEventDetails
liveChatFanFundingEventDetails =
LiveChatFanFundingEventDetails'
{ _lcffedUserComment = Nothing
, _lcffedAmountMicros = Nothing
, _lcffedAmountDisplayString = Nothing
, _lcffedCurrency = Nothing
}
-- | The comment added by the user to this fan funding event.
lcffedUserComment :: Lens' LiveChatFanFundingEventDetails (Maybe Text)
lcffedUserComment
= lens _lcffedUserComment
(\ s a -> s{_lcffedUserComment = a})
-- | The amount of the fund.
lcffedAmountMicros :: Lens' LiveChatFanFundingEventDetails (Maybe Word64)
lcffedAmountMicros
= lens _lcffedAmountMicros
(\ s a -> s{_lcffedAmountMicros = a})
. mapping _Coerce
-- | A rendered string that displays the fund amount and currency to the
-- user.
lcffedAmountDisplayString :: Lens' LiveChatFanFundingEventDetails (Maybe Text)
lcffedAmountDisplayString
= lens _lcffedAmountDisplayString
(\ s a -> s{_lcffedAmountDisplayString = a})
-- | The currency in which the fund was made.
lcffedCurrency :: Lens' LiveChatFanFundingEventDetails (Maybe Text)
lcffedCurrency
= lens _lcffedCurrency
(\ s a -> s{_lcffedCurrency = a})
instance FromJSON LiveChatFanFundingEventDetails
where
parseJSON
= withObject "LiveChatFanFundingEventDetails"
(\ o ->
LiveChatFanFundingEventDetails' <$>
(o .:? "userComment") <*> (o .:? "amountMicros") <*>
(o .:? "amountDisplayString")
<*> (o .:? "currency"))
instance ToJSON LiveChatFanFundingEventDetails where
toJSON LiveChatFanFundingEventDetails'{..}
= object
(catMaybes
[("userComment" .=) <$> _lcffedUserComment,
("amountMicros" .=) <$> _lcffedAmountMicros,
("amountDisplayString" .=) <$>
_lcffedAmountDisplayString,
("currency" .=) <$> _lcffedCurrency])
-- | Details about the content of an activity: the video that was shared, the
-- channel that was subscribed to, etc.
--
-- /See:/ 'activityContentDetails' smart constructor.
data ActivityContentDetails =
ActivityContentDetails'
{ _acdPromotedItem :: !(Maybe ActivityContentDetailsPromotedItem)
, _acdChannelItem :: !(Maybe ActivityContentDetailsChannelItem)
, _acdBulletin :: !(Maybe ActivityContentDetailsBulletin)
, _acdFavorite :: !(Maybe ActivityContentDetailsFavorite)
, _acdUpload :: !(Maybe ActivityContentDetailsUpload)
, _acdComment :: !(Maybe ActivityContentDetailsComment)
, _acdSocial :: !(Maybe ActivityContentDetailsSocial)
, _acdSubscription :: !(Maybe ActivityContentDetailsSubscription)
, _acdPlayListItem :: !(Maybe ActivityContentDetailsPlayListItem)
, _acdLike :: !(Maybe ActivityContentDetailsLike)
, _acdRecommendation :: !(Maybe ActivityContentDetailsRecommendation)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdPromotedItem'
--
-- * 'acdChannelItem'
--
-- * 'acdBulletin'
--
-- * 'acdFavorite'
--
-- * 'acdUpload'
--
-- * 'acdComment'
--
-- * 'acdSocial'
--
-- * 'acdSubscription'
--
-- * 'acdPlayListItem'
--
-- * 'acdLike'
--
-- * 'acdRecommendation'
activityContentDetails
:: ActivityContentDetails
activityContentDetails =
ActivityContentDetails'
{ _acdPromotedItem = Nothing
, _acdChannelItem = Nothing
, _acdBulletin = Nothing
, _acdFavorite = Nothing
, _acdUpload = Nothing
, _acdComment = Nothing
, _acdSocial = Nothing
, _acdSubscription = Nothing
, _acdPlayListItem = Nothing
, _acdLike = Nothing
, _acdRecommendation = Nothing
}
-- | The promotedItem object contains details about a resource which is being
-- promoted. This property is only present if the snippet.type is
-- promotedItem.
acdPromotedItem :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsPromotedItem)
acdPromotedItem
= lens _acdPromotedItem
(\ s a -> s{_acdPromotedItem = a})
-- | The channelItem object contains details about a resource which was added
-- to a channel. This property is only present if the snippet.type is
-- channelItem.
acdChannelItem :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsChannelItem)
acdChannelItem
= lens _acdChannelItem
(\ s a -> s{_acdChannelItem = a})
-- | The bulletin object contains details about a channel bulletin post. This
-- object is only present if the snippet.type is bulletin.
acdBulletin :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsBulletin)
acdBulletin
= lens _acdBulletin (\ s a -> s{_acdBulletin = a})
-- | The favorite object contains information about a video that was marked
-- as a favorite video. This property is only present if the snippet.type
-- is favorite.
acdFavorite :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsFavorite)
acdFavorite
= lens _acdFavorite (\ s a -> s{_acdFavorite = a})
-- | The upload object contains information about the uploaded video. This
-- property is only present if the snippet.type is upload.
acdUpload :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsUpload)
acdUpload
= lens _acdUpload (\ s a -> s{_acdUpload = a})
-- | The comment object contains information about a resource that received a
-- comment. This property is only present if the snippet.type is comment.
acdComment :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsComment)
acdComment
= lens _acdComment (\ s a -> s{_acdComment = a})
-- | The social object contains details about a social network post. This
-- property is only present if the snippet.type is social.
acdSocial :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsSocial)
acdSocial
= lens _acdSocial (\ s a -> s{_acdSocial = a})
-- | The subscription object contains information about a channel that a user
-- subscribed to. This property is only present if the snippet.type is
-- subscription.
acdSubscription :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsSubscription)
acdSubscription
= lens _acdSubscription
(\ s a -> s{_acdSubscription = a})
-- | The playlistItem object contains information about a new playlist item.
-- This property is only present if the snippet.type is playlistItem.
acdPlayListItem :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsPlayListItem)
acdPlayListItem
= lens _acdPlayListItem
(\ s a -> s{_acdPlayListItem = a})
-- | The like object contains information about a resource that received a
-- positive (like) rating. This property is only present if the
-- snippet.type is like.
acdLike :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsLike)
acdLike = lens _acdLike (\ s a -> s{_acdLike = a})
-- | The recommendation object contains information about a recommended
-- resource. This property is only present if the snippet.type is
-- recommendation.
acdRecommendation :: Lens' ActivityContentDetails (Maybe ActivityContentDetailsRecommendation)
acdRecommendation
= lens _acdRecommendation
(\ s a -> s{_acdRecommendation = a})
instance FromJSON ActivityContentDetails where
parseJSON
= withObject "ActivityContentDetails"
(\ o ->
ActivityContentDetails' <$>
(o .:? "promotedItem") <*> (o .:? "channelItem") <*>
(o .:? "bulletin")
<*> (o .:? "favorite")
<*> (o .:? "upload")
<*> (o .:? "comment")
<*> (o .:? "social")
<*> (o .:? "subscription")
<*> (o .:? "playlistItem")
<*> (o .:? "like")
<*> (o .:? "recommendation"))
instance ToJSON ActivityContentDetails where
toJSON ActivityContentDetails'{..}
= object
(catMaybes
[("promotedItem" .=) <$> _acdPromotedItem,
("channelItem" .=) <$> _acdChannelItem,
("bulletin" .=) <$> _acdBulletin,
("favorite" .=) <$> _acdFavorite,
("upload" .=) <$> _acdUpload,
("comment" .=) <$> _acdComment,
("social" .=) <$> _acdSocial,
("subscription" .=) <$> _acdSubscription,
("playlistItem" .=) <$> _acdPlayListItem,
("like" .=) <$> _acdLike,
("recommendation" .=) <$> _acdRecommendation])
-- | A *videoCategory* resource identifies a category that has been or could
-- be associated with uploaded videos.
--
-- /See:/ 'videoCategory' smart constructor.
data VideoCategory =
VideoCategory'
{ _vcEtag :: !(Maybe Text)
, _vcSnippet :: !(Maybe VideoCategorySnippet)
, _vcKind :: !Text
, _vcId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoCategory' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vcEtag'
--
-- * 'vcSnippet'
--
-- * 'vcKind'
--
-- * 'vcId'
videoCategory
:: VideoCategory
videoCategory =
VideoCategory'
{ _vcEtag = Nothing
, _vcSnippet = Nothing
, _vcKind = "youtube#videoCategory"
, _vcId = Nothing
}
-- | Etag of this resource.
vcEtag :: Lens' VideoCategory (Maybe Text)
vcEtag = lens _vcEtag (\ s a -> s{_vcEtag = a})
-- | The snippet object contains basic details about the video category,
-- including its title.
vcSnippet :: Lens' VideoCategory (Maybe VideoCategorySnippet)
vcSnippet
= lens _vcSnippet (\ s a -> s{_vcSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#videoCategory\".
vcKind :: Lens' VideoCategory Text
vcKind = lens _vcKind (\ s a -> s{_vcKind = a})
-- | The ID that YouTube uses to uniquely identify the video category.
vcId :: Lens' VideoCategory (Maybe Text)
vcId = lens _vcId (\ s a -> s{_vcId = a})
instance FromJSON VideoCategory where
parseJSON
= withObject "VideoCategory"
(\ o ->
VideoCategory' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#videoCategory")
<*> (o .:? "id"))
instance ToJSON VideoCategory where
toJSON VideoCategory'{..}
= object
(catMaybes
[("etag" .=) <$> _vcEtag,
("snippet" .=) <$> _vcSnippet,
Just ("kind" .= _vcKind), ("id" .=) <$> _vcId])
-- | The localizations object contains localized versions of the basic
-- details about the video, such as its title and description.
--
-- /See:/ 'videoLocalizations' smart constructor.
newtype VideoLocalizations =
VideoLocalizations'
{ _vlAddtional :: HashMap Text VideoLocalization
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoLocalizations' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vlAddtional'
videoLocalizations
:: HashMap Text VideoLocalization -- ^ 'vlAddtional'
-> VideoLocalizations
videoLocalizations pVlAddtional_ =
VideoLocalizations' {_vlAddtional = _Coerce # pVlAddtional_}
vlAddtional :: Lens' VideoLocalizations (HashMap Text VideoLocalization)
vlAddtional
= lens _vlAddtional (\ s a -> s{_vlAddtional = a}) .
_Coerce
instance FromJSON VideoLocalizations where
parseJSON
= withObject "VideoLocalizations"
(\ o -> VideoLocalizations' <$> (parseJSONObject o))
instance ToJSON VideoLocalizations where
toJSON = toJSON . _vlAddtional
-- | Details about a channelsection, including playlists and channels.
--
-- /See:/ 'channelSectionContentDetails' smart constructor.
data ChannelSectionContentDetails =
ChannelSectionContentDetails'
{ _cscdChannels :: !(Maybe [Text])
, _cscdPlayLists :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSectionContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cscdChannels'
--
-- * 'cscdPlayLists'
channelSectionContentDetails
:: ChannelSectionContentDetails
channelSectionContentDetails =
ChannelSectionContentDetails'
{_cscdChannels = Nothing, _cscdPlayLists = Nothing}
-- | The channel ids for type multiple_channels.
cscdChannels :: Lens' ChannelSectionContentDetails [Text]
cscdChannels
= lens _cscdChannels (\ s a -> s{_cscdChannels = a})
. _Default
. _Coerce
-- | The playlist ids for type single_playlist and multiple_playlists. For
-- singlePlaylist, only one playlistId is allowed.
cscdPlayLists :: Lens' ChannelSectionContentDetails [Text]
cscdPlayLists
= lens _cscdPlayLists
(\ s a -> s{_cscdPlayLists = a})
. _Default
. _Coerce
instance FromJSON ChannelSectionContentDetails where
parseJSON
= withObject "ChannelSectionContentDetails"
(\ o ->
ChannelSectionContentDetails' <$>
(o .:? "channels" .!= mempty) <*>
(o .:? "playlists" .!= mempty))
instance ToJSON ChannelSectionContentDetails where
toJSON ChannelSectionContentDetails'{..}
= object
(catMaybes
[("channels" .=) <$> _cscdChannels,
("playlists" .=) <$> _cscdPlayLists])
-- | A *video* resource represents a YouTube video.
--
-- /See:/ 'video' smart constructor.
data Video =
Video'
{ _vStatus :: !(Maybe VideoStatus)
, _vEtag :: !(Maybe Text)
, _vProjectDetails :: !(Maybe VideoProjectDetails)
, _vRecordingDetails :: !(Maybe VideoRecordingDetails)
, _vSnippet :: !(Maybe VideoSnippet)
, _vKind :: !Text
, _vTopicDetails :: !(Maybe VideoTopicDetails)
, _vContentDetails :: !(Maybe VideoContentDetails)
, _vAgeGating :: !(Maybe VideoAgeGating)
, _vFileDetails :: !(Maybe VideoFileDetails)
, _vSuggestions :: !(Maybe VideoSuggestions)
, _vId :: !(Maybe Text)
, _vStatistics :: !(Maybe VideoStatistics)
, _vLocalizations :: !(Maybe VideoLocalizations)
, _vLiveStreamingDetails :: !(Maybe VideoLiveStreamingDetails)
, _vPlayer :: !(Maybe VideoPlayer)
, _vProcessingDetails :: !(Maybe VideoProcessingDetails)
, _vMonetizationDetails :: !(Maybe VideoMonetizationDetails)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Video' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vStatus'
--
-- * 'vEtag'
--
-- * 'vProjectDetails'
--
-- * 'vRecordingDetails'
--
-- * 'vSnippet'
--
-- * 'vKind'
--
-- * 'vTopicDetails'
--
-- * 'vContentDetails'
--
-- * 'vAgeGating'
--
-- * 'vFileDetails'
--
-- * 'vSuggestions'
--
-- * 'vId'
--
-- * 'vStatistics'
--
-- * 'vLocalizations'
--
-- * 'vLiveStreamingDetails'
--
-- * 'vPlayer'
--
-- * 'vProcessingDetails'
--
-- * 'vMonetizationDetails'
video
:: Video
video =
Video'
{ _vStatus = Nothing
, _vEtag = Nothing
, _vProjectDetails = Nothing
, _vRecordingDetails = Nothing
, _vSnippet = Nothing
, _vKind = "youtube#video"
, _vTopicDetails = Nothing
, _vContentDetails = Nothing
, _vAgeGating = Nothing
, _vFileDetails = Nothing
, _vSuggestions = Nothing
, _vId = Nothing
, _vStatistics = Nothing
, _vLocalizations = Nothing
, _vLiveStreamingDetails = Nothing
, _vPlayer = Nothing
, _vProcessingDetails = Nothing
, _vMonetizationDetails = Nothing
}
-- | The status object contains information about the video\'s uploading,
-- processing, and privacy statuses.
vStatus :: Lens' Video (Maybe VideoStatus)
vStatus = lens _vStatus (\ s a -> s{_vStatus = a})
-- | Etag of this resource.
vEtag :: Lens' Video (Maybe Text)
vEtag = lens _vEtag (\ s a -> s{_vEtag = a})
-- | The projectDetails object contains information about the project
-- specific video metadata. b\/157517979: This part was never populated
-- after it was added. However, it sees non-zero traffic because there is
-- generated client code in the wild that refers to it [1]. We keep this
-- field and do NOT remove it because otherwise V3 would return an error
-- when this part gets requested [2]. [1]
-- https:\/\/developers.google.com\/resources\/api-libraries\/documentation\/youtube\/v3\/csharp\/latest\/classGoogle_1_1Apis_1_1YouTube_1_1v3_1_1Data_1_1VideoProjectDetails.html
-- [2]
-- http:\/\/google3\/video\/youtube\/src\/python\/servers\/data_api\/common.py?l=1565-1569&rcl=344141677
vProjectDetails :: Lens' Video (Maybe VideoProjectDetails)
vProjectDetails
= lens _vProjectDetails
(\ s a -> s{_vProjectDetails = a})
-- | The recordingDetails object encapsulates information about the location,
-- date and address where the video was recorded.
vRecordingDetails :: Lens' Video (Maybe VideoRecordingDetails)
vRecordingDetails
= lens _vRecordingDetails
(\ s a -> s{_vRecordingDetails = a})
-- | The snippet object contains basic details about the video, such as its
-- title, description, and category.
vSnippet :: Lens' Video (Maybe VideoSnippet)
vSnippet = lens _vSnippet (\ s a -> s{_vSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#video\".
vKind :: Lens' Video Text
vKind = lens _vKind (\ s a -> s{_vKind = a})
-- | The topicDetails object encapsulates information about Freebase topics
-- associated with the video.
vTopicDetails :: Lens' Video (Maybe VideoTopicDetails)
vTopicDetails
= lens _vTopicDetails
(\ s a -> s{_vTopicDetails = a})
-- | The contentDetails object contains information about the video content,
-- including the length of the video and its aspect ratio.
vContentDetails :: Lens' Video (Maybe VideoContentDetails)
vContentDetails
= lens _vContentDetails
(\ s a -> s{_vContentDetails = a})
-- | Age restriction details related to a video. This data can only be
-- retrieved by the video owner.
vAgeGating :: Lens' Video (Maybe VideoAgeGating)
vAgeGating
= lens _vAgeGating (\ s a -> s{_vAgeGating = a})
-- | The fileDetails object encapsulates information about the video file
-- that was uploaded to YouTube, including the file\'s resolution,
-- duration, audio and video codecs, stream bitrates, and more. This data
-- can only be retrieved by the video owner.
vFileDetails :: Lens' Video (Maybe VideoFileDetails)
vFileDetails
= lens _vFileDetails (\ s a -> s{_vFileDetails = a})
-- | The suggestions object encapsulates suggestions that identify
-- opportunities to improve the video quality or the metadata for the
-- uploaded video. This data can only be retrieved by the video owner.
vSuggestions :: Lens' Video (Maybe VideoSuggestions)
vSuggestions
= lens _vSuggestions (\ s a -> s{_vSuggestions = a})
-- | The ID that YouTube uses to uniquely identify the video.
vId :: Lens' Video (Maybe Text)
vId = lens _vId (\ s a -> s{_vId = a})
-- | The statistics object contains statistics about the video.
vStatistics :: Lens' Video (Maybe VideoStatistics)
vStatistics
= lens _vStatistics (\ s a -> s{_vStatistics = a})
-- | The localizations object contains localized versions of the basic
-- details about the video, such as its title and description.
vLocalizations :: Lens' Video (Maybe VideoLocalizations)
vLocalizations
= lens _vLocalizations
(\ s a -> s{_vLocalizations = a})
-- | The liveStreamingDetails object contains metadata about a live video
-- broadcast. The object will only be present in a video resource if the
-- video is an upcoming, live, or completed live broadcast.
vLiveStreamingDetails :: Lens' Video (Maybe VideoLiveStreamingDetails)
vLiveStreamingDetails
= lens _vLiveStreamingDetails
(\ s a -> s{_vLiveStreamingDetails = a})
-- | The player object contains information that you would use to play the
-- video in an embedded player.
vPlayer :: Lens' Video (Maybe VideoPlayer)
vPlayer = lens _vPlayer (\ s a -> s{_vPlayer = a})
-- | The processingDetails object encapsulates information about YouTube\'s
-- progress in processing the uploaded video file. The properties in the
-- object identify the current processing status and an estimate of the
-- time remaining until YouTube finishes processing the video. This part
-- also indicates whether different types of data or content, such as file
-- details or thumbnail images, are available for the video. The
-- processingProgress object is designed to be polled so that the video
-- uploaded can track the progress that YouTube has made in processing the
-- uploaded video file. This data can only be retrieved by the video owner.
vProcessingDetails :: Lens' Video (Maybe VideoProcessingDetails)
vProcessingDetails
= lens _vProcessingDetails
(\ s a -> s{_vProcessingDetails = a})
-- | The monetizationDetails object encapsulates information about the
-- monetization status of the video.
vMonetizationDetails :: Lens' Video (Maybe VideoMonetizationDetails)
vMonetizationDetails
= lens _vMonetizationDetails
(\ s a -> s{_vMonetizationDetails = a})
instance FromJSON Video where
parseJSON
= withObject "Video"
(\ o ->
Video' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "projectDetails")
<*> (o .:? "recordingDetails")
<*> (o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#video")
<*> (o .:? "topicDetails")
<*> (o .:? "contentDetails")
<*> (o .:? "ageGating")
<*> (o .:? "fileDetails")
<*> (o .:? "suggestions")
<*> (o .:? "id")
<*> (o .:? "statistics")
<*> (o .:? "localizations")
<*> (o .:? "liveStreamingDetails")
<*> (o .:? "player")
<*> (o .:? "processingDetails")
<*> (o .:? "monetizationDetails"))
instance ToJSON Video where
toJSON Video'{..}
= object
(catMaybes
[("status" .=) <$> _vStatus, ("etag" .=) <$> _vEtag,
("projectDetails" .=) <$> _vProjectDetails,
("recordingDetails" .=) <$> _vRecordingDetails,
("snippet" .=) <$> _vSnippet,
Just ("kind" .= _vKind),
("topicDetails" .=) <$> _vTopicDetails,
("contentDetails" .=) <$> _vContentDetails,
("ageGating" .=) <$> _vAgeGating,
("fileDetails" .=) <$> _vFileDetails,
("suggestions" .=) <$> _vSuggestions,
("id" .=) <$> _vId,
("statistics" .=) <$> _vStatistics,
("localizations" .=) <$> _vLocalizations,
("liveStreamingDetails" .=) <$>
_vLiveStreamingDetails,
("player" .=) <$> _vPlayer,
("processingDetails" .=) <$> _vProcessingDetails,
("monetizationDetails" .=) <$>
_vMonetizationDetails])
-- | A *liveBroadcast* resource represents an event that will be streamed,
-- via live video, on YouTube.
--
-- /See:/ 'liveBroadcast' smart constructor.
data LiveBroadcast =
LiveBroadcast'
{ _lbStatus :: !(Maybe LiveBroadcastStatus)
, _lbEtag :: !(Maybe Text)
, _lbSnippet :: !(Maybe LiveBroadcastSnippet)
, _lbKind :: !Text
, _lbContentDetails :: !(Maybe LiveBroadcastContentDetails)
, _lbId :: !(Maybe Text)
, _lbStatistics :: !(Maybe LiveBroadcastStatistics)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcast' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbStatus'
--
-- * 'lbEtag'
--
-- * 'lbSnippet'
--
-- * 'lbKind'
--
-- * 'lbContentDetails'
--
-- * 'lbId'
--
-- * 'lbStatistics'
liveBroadcast
:: LiveBroadcast
liveBroadcast =
LiveBroadcast'
{ _lbStatus = Nothing
, _lbEtag = Nothing
, _lbSnippet = Nothing
, _lbKind = "youtube#liveBroadcast"
, _lbContentDetails = Nothing
, _lbId = Nothing
, _lbStatistics = Nothing
}
-- | The status object contains information about the event\'s status.
lbStatus :: Lens' LiveBroadcast (Maybe LiveBroadcastStatus)
lbStatus = lens _lbStatus (\ s a -> s{_lbStatus = a})
-- | Etag of this resource.
lbEtag :: Lens' LiveBroadcast (Maybe Text)
lbEtag = lens _lbEtag (\ s a -> s{_lbEtag = a})
-- | The snippet object contains basic details about the event, including its
-- title, description, start time, and end time.
lbSnippet :: Lens' LiveBroadcast (Maybe LiveBroadcastSnippet)
lbSnippet
= lens _lbSnippet (\ s a -> s{_lbSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveBroadcast\".
lbKind :: Lens' LiveBroadcast Text
lbKind = lens _lbKind (\ s a -> s{_lbKind = a})
-- | The contentDetails object contains information about the event\'s video
-- content, such as whether the content can be shown in an embedded video
-- player or if it will be archived and therefore available for viewing
-- after the event has concluded.
lbContentDetails :: Lens' LiveBroadcast (Maybe LiveBroadcastContentDetails)
lbContentDetails
= lens _lbContentDetails
(\ s a -> s{_lbContentDetails = a})
-- | The ID that YouTube assigns to uniquely identify the broadcast.
lbId :: Lens' LiveBroadcast (Maybe Text)
lbId = lens _lbId (\ s a -> s{_lbId = a})
-- | The statistics object contains info about the event\'s current stats.
-- These include concurrent viewers and total chat count. Statistics can
-- change (in either direction) during the lifetime of an event. Statistics
-- are only returned while the event is live.
lbStatistics :: Lens' LiveBroadcast (Maybe LiveBroadcastStatistics)
lbStatistics
= lens _lbStatistics (\ s a -> s{_lbStatistics = a})
instance FromJSON LiveBroadcast where
parseJSON
= withObject "LiveBroadcast"
(\ o ->
LiveBroadcast' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#liveBroadcast")
<*> (o .:? "contentDetails")
<*> (o .:? "id")
<*> (o .:? "statistics"))
instance ToJSON LiveBroadcast where
toJSON LiveBroadcast'{..}
= object
(catMaybes
[("status" .=) <$> _lbStatus,
("etag" .=) <$> _lbEtag,
("snippet" .=) <$> _lbSnippet,
Just ("kind" .= _lbKind),
("contentDetails" .=) <$> _lbContentDetails,
("id" .=) <$> _lbId,
("statistics" .=) <$> _lbStatistics])
-- | A *liveChatModerator* resource represents a moderator for a YouTube live
-- chat. A chat moderator has the ability to ban\/unban users from a chat,
-- remove message, etc.
--
-- /See:/ 'liveChatModerator' smart constructor.
data LiveChatModerator =
LiveChatModerator'
{ _livEtag :: !(Maybe Text)
, _livSnippet :: !(Maybe LiveChatModeratorSnippet)
, _livKind :: !Text
, _livId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatModerator' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'livEtag'
--
-- * 'livSnippet'
--
-- * 'livKind'
--
-- * 'livId'
liveChatModerator
:: LiveChatModerator
liveChatModerator =
LiveChatModerator'
{ _livEtag = Nothing
, _livSnippet = Nothing
, _livKind = "youtube#liveChatModerator"
, _livId = Nothing
}
-- | Etag of this resource.
livEtag :: Lens' LiveChatModerator (Maybe Text)
livEtag = lens _livEtag (\ s a -> s{_livEtag = a})
-- | The snippet object contains basic details about the moderator.
livSnippet :: Lens' LiveChatModerator (Maybe LiveChatModeratorSnippet)
livSnippet
= lens _livSnippet (\ s a -> s{_livSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#liveChatModerator\".
livKind :: Lens' LiveChatModerator Text
livKind = lens _livKind (\ s a -> s{_livKind = a})
-- | The ID that YouTube assigns to uniquely identify the moderator.
livId :: Lens' LiveChatModerator (Maybe Text)
livId = lens _livId (\ s a -> s{_livId = a})
instance FromJSON LiveChatModerator where
parseJSON
= withObject "LiveChatModerator"
(\ o ->
LiveChatModerator' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#liveChatModerator")
<*> (o .:? "id"))
instance ToJSON LiveChatModerator where
toJSON LiveChatModerator'{..}
= object
(catMaybes
[("etag" .=) <$> _livEtag,
("snippet" .=) <$> _livSnippet,
Just ("kind" .= _livKind), ("id" .=) <$> _livId])
-- | Detailed settings of a stream.
--
-- /See:/ 'liveStreamContentDetails' smart constructor.
data LiveStreamContentDetails =
LiveStreamContentDetails'
{ _lscdClosedCaptionsIngestionURL :: !(Maybe Text)
, _lscdIsReusable :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStreamContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lscdClosedCaptionsIngestionURL'
--
-- * 'lscdIsReusable'
liveStreamContentDetails
:: LiveStreamContentDetails
liveStreamContentDetails =
LiveStreamContentDetails'
{_lscdClosedCaptionsIngestionURL = Nothing, _lscdIsReusable = Nothing}
-- | The ingestion URL where the closed captions of this stream are sent.
lscdClosedCaptionsIngestionURL :: Lens' LiveStreamContentDetails (Maybe Text)
lscdClosedCaptionsIngestionURL
= lens _lscdClosedCaptionsIngestionURL
(\ s a -> s{_lscdClosedCaptionsIngestionURL = a})
-- | Indicates whether the stream is reusable, which means that it can be
-- bound to multiple broadcasts. It is common for broadcasters to reuse the
-- same stream for many different broadcasts if those broadcasts occur at
-- different times. If you set this value to false, then the stream will
-- not be reusable, which means that it can only be bound to one broadcast.
-- Non-reusable streams differ from reusable streams in the following ways:
-- - A non-reusable stream can only be bound to one broadcast. - A
-- non-reusable stream might be deleted by an automated process after the
-- broadcast ends. - The liveStreams.list method does not list non-reusable
-- streams if you call the method and set the mine parameter to true. The
-- only way to use that method to retrieve the resource for a non-reusable
-- stream is to use the id parameter to identify the stream.
lscdIsReusable :: Lens' LiveStreamContentDetails (Maybe Bool)
lscdIsReusable
= lens _lscdIsReusable
(\ s a -> s{_lscdIsReusable = a})
instance FromJSON LiveStreamContentDetails where
parseJSON
= withObject "LiveStreamContentDetails"
(\ o ->
LiveStreamContentDetails' <$>
(o .:? "closedCaptionsIngestionUrl") <*>
(o .:? "isReusable"))
instance ToJSON LiveStreamContentDetails where
toJSON LiveStreamContentDetails'{..}
= object
(catMaybes
[("closedCaptionsIngestionUrl" .=) <$>
_lscdClosedCaptionsIngestionURL,
("isReusable" .=) <$> _lscdIsReusable])
-- | The third-party link status object contains information about the status
-- of the link.
--
-- /See:/ 'thirdPartyLinkStatus' smart constructor.
newtype ThirdPartyLinkStatus =
ThirdPartyLinkStatus'
{ _tplsLinkStatus :: Maybe ThirdPartyLinkStatusLinkStatus
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ThirdPartyLinkStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tplsLinkStatus'
thirdPartyLinkStatus
:: ThirdPartyLinkStatus
thirdPartyLinkStatus = ThirdPartyLinkStatus' {_tplsLinkStatus = Nothing}
tplsLinkStatus :: Lens' ThirdPartyLinkStatus (Maybe ThirdPartyLinkStatusLinkStatus)
tplsLinkStatus
= lens _tplsLinkStatus
(\ s a -> s{_tplsLinkStatus = a})
instance FromJSON ThirdPartyLinkStatus where
parseJSON
= withObject "ThirdPartyLinkStatus"
(\ o ->
ThirdPartyLinkStatus' <$> (o .:? "linkStatus"))
instance ToJSON ThirdPartyLinkStatus where
toJSON ThirdPartyLinkStatus'{..}
= object
(catMaybes [("linkStatus" .=) <$> _tplsLinkStatus])
--
-- /See:/ 'liveChatModeratorSnippet' smart constructor.
data LiveChatModeratorSnippet =
LiveChatModeratorSnippet'
{ _lLiveChatId :: !(Maybe Text)
, _lModeratorDetails :: !(Maybe ChannelProFileDetails)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatModeratorSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lLiveChatId'
--
-- * 'lModeratorDetails'
liveChatModeratorSnippet
:: LiveChatModeratorSnippet
liveChatModeratorSnippet =
LiveChatModeratorSnippet'
{_lLiveChatId = Nothing, _lModeratorDetails = Nothing}
-- | The ID of the live chat this moderator can act on.
lLiveChatId :: Lens' LiveChatModeratorSnippet (Maybe Text)
lLiveChatId
= lens _lLiveChatId (\ s a -> s{_lLiveChatId = a})
-- | Details about the moderator.
lModeratorDetails :: Lens' LiveChatModeratorSnippet (Maybe ChannelProFileDetails)
lModeratorDetails
= lens _lModeratorDetails
(\ s a -> s{_lModeratorDetails = a})
instance FromJSON LiveChatModeratorSnippet where
parseJSON
= withObject "LiveChatModeratorSnippet"
(\ o ->
LiveChatModeratorSnippet' <$>
(o .:? "liveChatId") <*> (o .:? "moderatorDetails"))
instance ToJSON LiveChatModeratorSnippet where
toJSON LiveChatModeratorSnippet'{..}
= object
(catMaybes
[("liveChatId" .=) <$> _lLiveChatId,
("moderatorDetails" .=) <$> _lModeratorDetails])
-- | A pair Property \/ Value.
--
-- /See:/ 'propertyValue' smart constructor.
data PropertyValue =
PropertyValue'
{ _pvProperty :: !(Maybe Text)
, _pvValue :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PropertyValue' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pvProperty'
--
-- * 'pvValue'
propertyValue
:: PropertyValue
propertyValue = PropertyValue' {_pvProperty = Nothing, _pvValue = Nothing}
-- | A property.
pvProperty :: Lens' PropertyValue (Maybe Text)
pvProperty
= lens _pvProperty (\ s a -> s{_pvProperty = a})
-- | The property\'s value.
pvValue :: Lens' PropertyValue (Maybe Text)
pvValue = lens _pvValue (\ s a -> s{_pvValue = a})
instance FromJSON PropertyValue where
parseJSON
= withObject "PropertyValue"
(\ o ->
PropertyValue' <$>
(o .:? "property") <*> (o .:? "value"))
instance ToJSON PropertyValue where
toJSON PropertyValue'{..}
= object
(catMaybes
[("property" .=) <$> _pvProperty,
("value" .=) <$> _pvValue])
--
-- /See:/ 'levelDetails' smart constructor.
newtype LevelDetails =
LevelDetails'
{ _ldDisplayName :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LevelDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldDisplayName'
levelDetails
:: LevelDetails
levelDetails = LevelDetails' {_ldDisplayName = Nothing}
-- | The name that should be used when referring to this level.
ldDisplayName :: Lens' LevelDetails (Maybe Text)
ldDisplayName
= lens _ldDisplayName
(\ s a -> s{_ldDisplayName = a})
instance FromJSON LevelDetails where
parseJSON
= withObject "LevelDetails"
(\ o -> LevelDetails' <$> (o .:? "displayName"))
instance ToJSON LevelDetails where
toJSON LevelDetails'{..}
= object
(catMaybes [("displayName" .=) <$> _ldDisplayName])
-- | Basic details about a video, including title, description, uploader,
-- thumbnails and category.
--
-- /See:/ 'videoSnippet' smart constructor.
data VideoSnippet =
VideoSnippet'
{ _vsDefaultAudioLanguage :: !(Maybe Text)
, _vsPublishedAt :: !(Maybe DateTime')
, _vsChannelTitle :: !(Maybe Text)
, _vsChannelId :: !(Maybe Text)
, _vsThumbnails :: !(Maybe ThumbnailDetails)
, _vsLocalized :: !(Maybe VideoLocalization)
, _vsCategoryId :: !(Maybe Text)
, _vsTitle :: !(Maybe Text)
, _vsLiveBroadcastContent :: !(Maybe VideoSnippetLiveBroadcastContent)
, _vsDescription :: !(Maybe Text)
, _vsTags :: !(Maybe [Text])
, _vsDefaultLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vsDefaultAudioLanguage'
--
-- * 'vsPublishedAt'
--
-- * 'vsChannelTitle'
--
-- * 'vsChannelId'
--
-- * 'vsThumbnails'
--
-- * 'vsLocalized'
--
-- * 'vsCategoryId'
--
-- * 'vsTitle'
--
-- * 'vsLiveBroadcastContent'
--
-- * 'vsDescription'
--
-- * 'vsTags'
--
-- * 'vsDefaultLanguage'
videoSnippet
:: VideoSnippet
videoSnippet =
VideoSnippet'
{ _vsDefaultAudioLanguage = Nothing
, _vsPublishedAt = Nothing
, _vsChannelTitle = Nothing
, _vsChannelId = Nothing
, _vsThumbnails = Nothing
, _vsLocalized = Nothing
, _vsCategoryId = Nothing
, _vsTitle = Nothing
, _vsLiveBroadcastContent = Nothing
, _vsDescription = Nothing
, _vsTags = Nothing
, _vsDefaultLanguage = Nothing
}
-- | The default_audio_language property specifies the language spoken in the
-- video\'s default audio track.
vsDefaultAudioLanguage :: Lens' VideoSnippet (Maybe Text)
vsDefaultAudioLanguage
= lens _vsDefaultAudioLanguage
(\ s a -> s{_vsDefaultAudioLanguage = a})
-- | The date and time when the video was uploaded.
vsPublishedAt :: Lens' VideoSnippet (Maybe UTCTime)
vsPublishedAt
= lens _vsPublishedAt
(\ s a -> s{_vsPublishedAt = a})
. mapping _DateTime
-- | Channel title for the channel that the video belongs to.
vsChannelTitle :: Lens' VideoSnippet (Maybe Text)
vsChannelTitle
= lens _vsChannelTitle
(\ s a -> s{_vsChannelTitle = a})
-- | The ID that YouTube uses to uniquely identify the channel that the video
-- was uploaded to.
vsChannelId :: Lens' VideoSnippet (Maybe Text)
vsChannelId
= lens _vsChannelId (\ s a -> s{_vsChannelId = a})
-- | A map of thumbnail images associated with the video. For each object in
-- the map, the key is the name of the thumbnail image, and the value is an
-- object that contains other information about the thumbnail.
vsThumbnails :: Lens' VideoSnippet (Maybe ThumbnailDetails)
vsThumbnails
= lens _vsThumbnails (\ s a -> s{_vsThumbnails = a})
-- | Localized snippet selected with the hl parameter. If no such
-- localization exists, this field is populated with the default snippet.
-- (Read-only)
vsLocalized :: Lens' VideoSnippet (Maybe VideoLocalization)
vsLocalized
= lens _vsLocalized (\ s a -> s{_vsLocalized = a})
-- | The YouTube video category associated with the video.
vsCategoryId :: Lens' VideoSnippet (Maybe Text)
vsCategoryId
= lens _vsCategoryId (\ s a -> s{_vsCategoryId = a})
-- | The video\'s title. \'mutable youtube.videos.insert
-- youtube.videos.update
vsTitle :: Lens' VideoSnippet (Maybe Text)
vsTitle = lens _vsTitle (\ s a -> s{_vsTitle = a})
-- | Indicates if the video is an upcoming\/active live broadcast. Or it\'s
-- \"none\" if the video is not an upcoming\/active live broadcast.
vsLiveBroadcastContent :: Lens' VideoSnippet (Maybe VideoSnippetLiveBroadcastContent)
vsLiveBroadcastContent
= lens _vsLiveBroadcastContent
(\ s a -> s{_vsLiveBroadcastContent = a})
-- | The video\'s description. \'mutable youtube.videos.insert
-- youtube.videos.update
vsDescription :: Lens' VideoSnippet (Maybe Text)
vsDescription
= lens _vsDescription
(\ s a -> s{_vsDescription = a})
-- | A list of keyword tags associated with the video. Tags may contain
-- spaces.
vsTags :: Lens' VideoSnippet [Text]
vsTags
= lens _vsTags (\ s a -> s{_vsTags = a}) . _Default .
_Coerce
-- | The language of the videos\'s default snippet.
vsDefaultLanguage :: Lens' VideoSnippet (Maybe Text)
vsDefaultLanguage
= lens _vsDefaultLanguage
(\ s a -> s{_vsDefaultLanguage = a})
instance FromJSON VideoSnippet where
parseJSON
= withObject "VideoSnippet"
(\ o ->
VideoSnippet' <$>
(o .:? "defaultAudioLanguage") <*>
(o .:? "publishedAt")
<*> (o .:? "channelTitle")
<*> (o .:? "channelId")
<*> (o .:? "thumbnails")
<*> (o .:? "localized")
<*> (o .:? "categoryId")
<*> (o .:? "title")
<*> (o .:? "liveBroadcastContent")
<*> (o .:? "description")
<*> (o .:? "tags" .!= mempty)
<*> (o .:? "defaultLanguage"))
instance ToJSON VideoSnippet where
toJSON VideoSnippet'{..}
= object
(catMaybes
[("defaultAudioLanguage" .=) <$>
_vsDefaultAudioLanguage,
("publishedAt" .=) <$> _vsPublishedAt,
("channelTitle" .=) <$> _vsChannelTitle,
("channelId" .=) <$> _vsChannelId,
("thumbnails" .=) <$> _vsThumbnails,
("localized" .=) <$> _vsLocalized,
("categoryId" .=) <$> _vsCategoryId,
("title" .=) <$> _vsTitle,
("liveBroadcastContent" .=) <$>
_vsLiveBroadcastContent,
("description" .=) <$> _vsDescription,
("tags" .=) <$> _vsTags,
("defaultLanguage" .=) <$> _vsDefaultLanguage])
-- | Basic broadcast information.
--
-- /See:/ 'liveBroadcastSnippet' smart constructor.
data LiveBroadcastSnippet =
LiveBroadcastSnippet'
{ _lbsActualEndTime :: !(Maybe DateTime')
, _lbsLiveChatId :: !(Maybe Text)
, _lbsPublishedAt :: !(Maybe DateTime')
, _lbsScheduledEndTime :: !(Maybe DateTime')
, _lbsChannelId :: !(Maybe Text)
, _lbsScheduledStartTime :: !(Maybe DateTime')
, _lbsThumbnails :: !(Maybe ThumbnailDetails)
, _lbsTitle :: !(Maybe Text)
, _lbsActualStartTime :: !(Maybe DateTime')
, _lbsIsDefaultBroadcast :: !(Maybe Bool)
, _lbsDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbsActualEndTime'
--
-- * 'lbsLiveChatId'
--
-- * 'lbsPublishedAt'
--
-- * 'lbsScheduledEndTime'
--
-- * 'lbsChannelId'
--
-- * 'lbsScheduledStartTime'
--
-- * 'lbsThumbnails'
--
-- * 'lbsTitle'
--
-- * 'lbsActualStartTime'
--
-- * 'lbsIsDefaultBroadcast'
--
-- * 'lbsDescription'
liveBroadcastSnippet
:: LiveBroadcastSnippet
liveBroadcastSnippet =
LiveBroadcastSnippet'
{ _lbsActualEndTime = Nothing
, _lbsLiveChatId = Nothing
, _lbsPublishedAt = Nothing
, _lbsScheduledEndTime = Nothing
, _lbsChannelId = Nothing
, _lbsScheduledStartTime = Nothing
, _lbsThumbnails = Nothing
, _lbsTitle = Nothing
, _lbsActualStartTime = Nothing
, _lbsIsDefaultBroadcast = Nothing
, _lbsDescription = Nothing
}
-- | The date and time that the broadcast actually ended. This information is
-- only available once the broadcast\'s state is complete.
lbsActualEndTime :: Lens' LiveBroadcastSnippet (Maybe UTCTime)
lbsActualEndTime
= lens _lbsActualEndTime
(\ s a -> s{_lbsActualEndTime = a})
. mapping _DateTime
-- | The id of the live chat for this broadcast.
lbsLiveChatId :: Lens' LiveBroadcastSnippet (Maybe Text)
lbsLiveChatId
= lens _lbsLiveChatId
(\ s a -> s{_lbsLiveChatId = a})
-- | The date and time that the broadcast was added to YouTube\'s live
-- broadcast schedule.
lbsPublishedAt :: Lens' LiveBroadcastSnippet (Maybe UTCTime)
lbsPublishedAt
= lens _lbsPublishedAt
(\ s a -> s{_lbsPublishedAt = a})
. mapping _DateTime
-- | The date and time that the broadcast is scheduled to end.
lbsScheduledEndTime :: Lens' LiveBroadcastSnippet (Maybe UTCTime)
lbsScheduledEndTime
= lens _lbsScheduledEndTime
(\ s a -> s{_lbsScheduledEndTime = a})
. mapping _DateTime
-- | The ID that YouTube uses to uniquely identify the channel that is
-- publishing the broadcast.
lbsChannelId :: Lens' LiveBroadcastSnippet (Maybe Text)
lbsChannelId
= lens _lbsChannelId (\ s a -> s{_lbsChannelId = a})
-- | The date and time that the broadcast is scheduled to start.
lbsScheduledStartTime :: Lens' LiveBroadcastSnippet (Maybe UTCTime)
lbsScheduledStartTime
= lens _lbsScheduledStartTime
(\ s a -> s{_lbsScheduledStartTime = a})
. mapping _DateTime
-- | A map of thumbnail images associated with the broadcast. For each nested
-- object in this object, the key is the name of the thumbnail image, and
-- the value is an object that contains other information about the
-- thumbnail.
lbsThumbnails :: Lens' LiveBroadcastSnippet (Maybe ThumbnailDetails)
lbsThumbnails
= lens _lbsThumbnails
(\ s a -> s{_lbsThumbnails = a})
-- | The broadcast\'s title. Note that the broadcast represents exactly one
-- YouTube video. You can set this field by modifying the broadcast
-- resource or by setting the title field of the corresponding video
-- resource.
lbsTitle :: Lens' LiveBroadcastSnippet (Maybe Text)
lbsTitle = lens _lbsTitle (\ s a -> s{_lbsTitle = a})
-- | The date and time that the broadcast actually started. This information
-- is only available once the broadcast\'s state is live.
lbsActualStartTime :: Lens' LiveBroadcastSnippet (Maybe UTCTime)
lbsActualStartTime
= lens _lbsActualStartTime
(\ s a -> s{_lbsActualStartTime = a})
. mapping _DateTime
-- | Indicates whether this broadcast is the default broadcast. Internal
-- only.
lbsIsDefaultBroadcast :: Lens' LiveBroadcastSnippet (Maybe Bool)
lbsIsDefaultBroadcast
= lens _lbsIsDefaultBroadcast
(\ s a -> s{_lbsIsDefaultBroadcast = a})
-- | The broadcast\'s description. As with the title, you can set this field
-- by modifying the broadcast resource or by setting the description field
-- of the corresponding video resource.
lbsDescription :: Lens' LiveBroadcastSnippet (Maybe Text)
lbsDescription
= lens _lbsDescription
(\ s a -> s{_lbsDescription = a})
instance FromJSON LiveBroadcastSnippet where
parseJSON
= withObject "LiveBroadcastSnippet"
(\ o ->
LiveBroadcastSnippet' <$>
(o .:? "actualEndTime") <*> (o .:? "liveChatId") <*>
(o .:? "publishedAt")
<*> (o .:? "scheduledEndTime")
<*> (o .:? "channelId")
<*> (o .:? "scheduledStartTime")
<*> (o .:? "thumbnails")
<*> (o .:? "title")
<*> (o .:? "actualStartTime")
<*> (o .:? "isDefaultBroadcast")
<*> (o .:? "description"))
instance ToJSON LiveBroadcastSnippet where
toJSON LiveBroadcastSnippet'{..}
= object
(catMaybes
[("actualEndTime" .=) <$> _lbsActualEndTime,
("liveChatId" .=) <$> _lbsLiveChatId,
("publishedAt" .=) <$> _lbsPublishedAt,
("scheduledEndTime" .=) <$> _lbsScheduledEndTime,
("channelId" .=) <$> _lbsChannelId,
("scheduledStartTime" .=) <$> _lbsScheduledStartTime,
("thumbnails" .=) <$> _lbsThumbnails,
("title" .=) <$> _lbsTitle,
("actualStartTime" .=) <$> _lbsActualStartTime,
("isDefaultBroadcast" .=) <$> _lbsIsDefaultBroadcast,
("description" .=) <$> _lbsDescription])
-- | Rights management policy for YouTube resources.
--
-- /See:/ 'accessPolicy' smart constructor.
data AccessPolicy =
AccessPolicy'
{ _apException :: !(Maybe [Text])
, _apAllowed :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccessPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'apException'
--
-- * 'apAllowed'
accessPolicy
:: AccessPolicy
accessPolicy = AccessPolicy' {_apException = Nothing, _apAllowed = Nothing}
-- | A list of region codes that identify countries where the default policy
-- do not apply.
apException :: Lens' AccessPolicy [Text]
apException
= lens _apException (\ s a -> s{_apException = a}) .
_Default
. _Coerce
-- | The value of allowed indicates whether the access to the policy is
-- allowed or denied by default.
apAllowed :: Lens' AccessPolicy (Maybe Bool)
apAllowed
= lens _apAllowed (\ s a -> s{_apAllowed = a})
instance FromJSON AccessPolicy where
parseJSON
= withObject "AccessPolicy"
(\ o ->
AccessPolicy' <$>
(o .:? "exception" .!= mempty) <*> (o .:? "allowed"))
instance ToJSON AccessPolicy where
toJSON AccessPolicy'{..}
= object
(catMaybes
[("exception" .=) <$> _apException,
("allowed" .=) <$> _apAllowed])
--
-- /See:/ 'liveChatMessageDeletedDetails' smart constructor.
newtype LiveChatMessageDeletedDetails =
LiveChatMessageDeletedDetails'
{ _lcmddDeletedMessageId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatMessageDeletedDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcmddDeletedMessageId'
liveChatMessageDeletedDetails
:: LiveChatMessageDeletedDetails
liveChatMessageDeletedDetails =
LiveChatMessageDeletedDetails' {_lcmddDeletedMessageId = Nothing}
lcmddDeletedMessageId :: Lens' LiveChatMessageDeletedDetails (Maybe Text)
lcmddDeletedMessageId
= lens _lcmddDeletedMessageId
(\ s a -> s{_lcmddDeletedMessageId = a})
instance FromJSON LiveChatMessageDeletedDetails where
parseJSON
= withObject "LiveChatMessageDeletedDetails"
(\ o ->
LiveChatMessageDeletedDetails' <$>
(o .:? "deletedMessageId"))
instance ToJSON LiveChatMessageDeletedDetails where
toJSON LiveChatMessageDeletedDetails'{..}
= object
(catMaybes
[("deletedMessageId" .=) <$> _lcmddDeletedMessageId])
--
-- /See:/ 'relatedEntity' smart constructor.
newtype RelatedEntity =
RelatedEntity'
{ _reEntity :: Maybe Entity
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RelatedEntity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'reEntity'
relatedEntity
:: RelatedEntity
relatedEntity = RelatedEntity' {_reEntity = Nothing}
reEntity :: Lens' RelatedEntity (Maybe Entity)
reEntity = lens _reEntity (\ s a -> s{_reEntity = a})
instance FromJSON RelatedEntity where
parseJSON
= withObject "RelatedEntity"
(\ o -> RelatedEntity' <$> (o .:? "entity"))
instance ToJSON RelatedEntity where
toJSON RelatedEntity'{..}
= object (catMaybes [("entity" .=) <$> _reEntity])
--
-- /See:/ 'commentThreadListResponse' smart constructor.
data CommentThreadListResponse =
CommentThreadListResponse'
{ _ctlrEtag :: !(Maybe Text)
, _ctlrTokenPagination :: !(Maybe TokenPagination)
, _ctlrNextPageToken :: !(Maybe Text)
, _ctlrPageInfo :: !(Maybe PageInfo)
, _ctlrKind :: !Text
, _ctlrItems :: !(Maybe [CommentThread])
, _ctlrVisitorId :: !(Maybe Text)
, _ctlrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentThreadListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctlrEtag'
--
-- * 'ctlrTokenPagination'
--
-- * 'ctlrNextPageToken'
--
-- * 'ctlrPageInfo'
--
-- * 'ctlrKind'
--
-- * 'ctlrItems'
--
-- * 'ctlrVisitorId'
--
-- * 'ctlrEventId'
commentThreadListResponse
:: CommentThreadListResponse
commentThreadListResponse =
CommentThreadListResponse'
{ _ctlrEtag = Nothing
, _ctlrTokenPagination = Nothing
, _ctlrNextPageToken = Nothing
, _ctlrPageInfo = Nothing
, _ctlrKind = "youtube#commentThreadListResponse"
, _ctlrItems = Nothing
, _ctlrVisitorId = Nothing
, _ctlrEventId = Nothing
}
-- | Etag of this resource.
ctlrEtag :: Lens' CommentThreadListResponse (Maybe Text)
ctlrEtag = lens _ctlrEtag (\ s a -> s{_ctlrEtag = a})
ctlrTokenPagination :: Lens' CommentThreadListResponse (Maybe TokenPagination)
ctlrTokenPagination
= lens _ctlrTokenPagination
(\ s a -> s{_ctlrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
ctlrNextPageToken :: Lens' CommentThreadListResponse (Maybe Text)
ctlrNextPageToken
= lens _ctlrNextPageToken
(\ s a -> s{_ctlrNextPageToken = a})
-- | General pagination information.
ctlrPageInfo :: Lens' CommentThreadListResponse (Maybe PageInfo)
ctlrPageInfo
= lens _ctlrPageInfo (\ s a -> s{_ctlrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#commentThreadListResponse\".
ctlrKind :: Lens' CommentThreadListResponse Text
ctlrKind = lens _ctlrKind (\ s a -> s{_ctlrKind = a})
-- | A list of comment threads that match the request criteria.
ctlrItems :: Lens' CommentThreadListResponse [CommentThread]
ctlrItems
= lens _ctlrItems (\ s a -> s{_ctlrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
ctlrVisitorId :: Lens' CommentThreadListResponse (Maybe Text)
ctlrVisitorId
= lens _ctlrVisitorId
(\ s a -> s{_ctlrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
ctlrEventId :: Lens' CommentThreadListResponse (Maybe Text)
ctlrEventId
= lens _ctlrEventId (\ s a -> s{_ctlrEventId = a})
instance FromJSON CommentThreadListResponse where
parseJSON
= withObject "CommentThreadListResponse"
(\ o ->
CommentThreadListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!=
"youtube#commentThreadListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON CommentThreadListResponse where
toJSON CommentThreadListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _ctlrEtag,
("tokenPagination" .=) <$> _ctlrTokenPagination,
("nextPageToken" .=) <$> _ctlrNextPageToken,
("pageInfo" .=) <$> _ctlrPageInfo,
Just ("kind" .= _ctlrKind),
("items" .=) <$> _ctlrItems,
("visitorId" .=) <$> _ctlrVisitorId,
("eventId" .=) <$> _ctlrEventId])
--
-- /See:/ 'membershipsDurationAtLevel' smart constructor.
data MembershipsDurationAtLevel =
MembershipsDurationAtLevel'
{ _mdalMemberTotalDurationMonths :: !(Maybe (Textual Int32))
, _mdalMemberSince :: !(Maybe Text)
, _mdalLevel :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MembershipsDurationAtLevel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdalMemberTotalDurationMonths'
--
-- * 'mdalMemberSince'
--
-- * 'mdalLevel'
membershipsDurationAtLevel
:: MembershipsDurationAtLevel
membershipsDurationAtLevel =
MembershipsDurationAtLevel'
{ _mdalMemberTotalDurationMonths = Nothing
, _mdalMemberSince = Nothing
, _mdalLevel = Nothing
}
-- | The cumulative time the user has been a member for the given level in
-- complete months (the time is rounded down to the nearest integer).
mdalMemberTotalDurationMonths :: Lens' MembershipsDurationAtLevel (Maybe Int32)
mdalMemberTotalDurationMonths
= lens _mdalMemberTotalDurationMonths
(\ s a -> s{_mdalMemberTotalDurationMonths = a})
. mapping _Coerce
-- | The date and time when the user became a continuous member for the given
-- level.
mdalMemberSince :: Lens' MembershipsDurationAtLevel (Maybe Text)
mdalMemberSince
= lens _mdalMemberSince
(\ s a -> s{_mdalMemberSince = a})
-- | Pricing level ID.
mdalLevel :: Lens' MembershipsDurationAtLevel (Maybe Text)
mdalLevel
= lens _mdalLevel (\ s a -> s{_mdalLevel = a})
instance FromJSON MembershipsDurationAtLevel where
parseJSON
= withObject "MembershipsDurationAtLevel"
(\ o ->
MembershipsDurationAtLevel' <$>
(o .:? "memberTotalDurationMonths") <*>
(o .:? "memberSince")
<*> (o .:? "level"))
instance ToJSON MembershipsDurationAtLevel where
toJSON MembershipsDurationAtLevel'{..}
= object
(catMaybes
[("memberTotalDurationMonths" .=) <$>
_mdalMemberTotalDurationMonths,
("memberSince" .=) <$> _mdalMemberSince,
("level" .=) <$> _mdalLevel])
-- | Branding properties for the watch. All deprecated.
--
-- /See:/ 'watchSettings' smart constructor.
data WatchSettings =
WatchSettings'
{ _wsFeaturedPlayListId :: !(Maybe Text)
, _wsBackgRoundColor :: !(Maybe Text)
, _wsTextColor :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WatchSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wsFeaturedPlayListId'
--
-- * 'wsBackgRoundColor'
--
-- * 'wsTextColor'
watchSettings
:: WatchSettings
watchSettings =
WatchSettings'
{ _wsFeaturedPlayListId = Nothing
, _wsBackgRoundColor = Nothing
, _wsTextColor = Nothing
}
-- | An ID that uniquely identifies a playlist that displays next to the
-- video player.
wsFeaturedPlayListId :: Lens' WatchSettings (Maybe Text)
wsFeaturedPlayListId
= lens _wsFeaturedPlayListId
(\ s a -> s{_wsFeaturedPlayListId = a})
-- | The text color for the video watch page\'s branded area.
wsBackgRoundColor :: Lens' WatchSettings (Maybe Text)
wsBackgRoundColor
= lens _wsBackgRoundColor
(\ s a -> s{_wsBackgRoundColor = a})
-- | The background color for the video watch page\'s branded area.
wsTextColor :: Lens' WatchSettings (Maybe Text)
wsTextColor
= lens _wsTextColor (\ s a -> s{_wsTextColor = a})
instance FromJSON WatchSettings where
parseJSON
= withObject "WatchSettings"
(\ o ->
WatchSettings' <$>
(o .:? "featuredPlaylistId") <*>
(o .:? "backgroundColor")
<*> (o .:? "textColor"))
instance ToJSON WatchSettings where
toJSON WatchSettings'{..}
= object
(catMaybes
[("featuredPlaylistId" .=) <$> _wsFeaturedPlayListId,
("backgroundColor" .=) <$> _wsBackgRoundColor,
("textColor" .=) <$> _wsTextColor])
-- | Brief description of the live stream cdn settings.
--
-- /See:/ 'cdnSettings' smart constructor.
data CdnSettings =
CdnSettings'
{ _csIngestionInfo :: !(Maybe IngestionInfo)
, _csFrameRate :: !(Maybe CdnSettingsFrameRate)
, _csFormat :: !(Maybe Text)
, _csResolution :: !(Maybe CdnSettingsResolution)
, _csIngestionType :: !(Maybe CdnSettingsIngestionType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CdnSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csIngestionInfo'
--
-- * 'csFrameRate'
--
-- * 'csFormat'
--
-- * 'csResolution'
--
-- * 'csIngestionType'
cdnSettings
:: CdnSettings
cdnSettings =
CdnSettings'
{ _csIngestionInfo = Nothing
, _csFrameRate = Nothing
, _csFormat = Nothing
, _csResolution = Nothing
, _csIngestionType = Nothing
}
-- | The ingestionInfo object contains information that YouTube provides that
-- you need to transmit your RTMP or HTTP stream to YouTube.
csIngestionInfo :: Lens' CdnSettings (Maybe IngestionInfo)
csIngestionInfo
= lens _csIngestionInfo
(\ s a -> s{_csIngestionInfo = a})
-- | The frame rate of the inbound video data.
csFrameRate :: Lens' CdnSettings (Maybe CdnSettingsFrameRate)
csFrameRate
= lens _csFrameRate (\ s a -> s{_csFrameRate = a})
-- | The format of the video stream that you are sending to Youtube.
csFormat :: Lens' CdnSettings (Maybe Text)
csFormat = lens _csFormat (\ s a -> s{_csFormat = a})
-- | The resolution of the inbound video data.
csResolution :: Lens' CdnSettings (Maybe CdnSettingsResolution)
csResolution
= lens _csResolution (\ s a -> s{_csResolution = a})
-- | The method or protocol used to transmit the video stream.
csIngestionType :: Lens' CdnSettings (Maybe CdnSettingsIngestionType)
csIngestionType
= lens _csIngestionType
(\ s a -> s{_csIngestionType = a})
instance FromJSON CdnSettings where
parseJSON
= withObject "CdnSettings"
(\ o ->
CdnSettings' <$>
(o .:? "ingestionInfo") <*> (o .:? "frameRate") <*>
(o .:? "format")
<*> (o .:? "resolution")
<*> (o .:? "ingestionType"))
instance ToJSON CdnSettings where
toJSON CdnSettings'{..}
= object
(catMaybes
[("ingestionInfo" .=) <$> _csIngestionInfo,
("frameRate" .=) <$> _csFrameRate,
("format" .=) <$> _csFormat,
("resolution" .=) <$> _csResolution,
("ingestionType" .=) <$> _csIngestionType])
-- | Statistics about the live broadcast. These represent a snapshot of the
-- values at the time of the request. Statistics are only returned for live
-- broadcasts.
--
-- /See:/ 'liveBroadcastStatistics' smart constructor.
newtype LiveBroadcastStatistics =
LiveBroadcastStatistics'
{ _lbsTotalChatCount :: Maybe (Textual Word64)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastStatistics' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbsTotalChatCount'
liveBroadcastStatistics
:: LiveBroadcastStatistics
liveBroadcastStatistics =
LiveBroadcastStatistics' {_lbsTotalChatCount = Nothing}
-- | The total number of live chat messages currently on the broadcast. The
-- property and its value will be present if the broadcast is public, has
-- the live chat feature enabled, and has at least one message. Note that
-- this field will not be filled after the broadcast ends. So this property
-- would not identify the number of chat messages for an archived video of
-- a completed live broadcast.
lbsTotalChatCount :: Lens' LiveBroadcastStatistics (Maybe Word64)
lbsTotalChatCount
= lens _lbsTotalChatCount
(\ s a -> s{_lbsTotalChatCount = a})
. mapping _Coerce
instance FromJSON LiveBroadcastStatistics where
parseJSON
= withObject "LiveBroadcastStatistics"
(\ o ->
LiveBroadcastStatistics' <$>
(o .:? "totalChatCount"))
instance ToJSON LiveBroadcastStatistics where
toJSON LiveBroadcastStatistics'{..}
= object
(catMaybes
[("totalChatCount" .=) <$> _lbsTotalChatCount])
-- | Basic details about a video category, such as its localized title.
--
-- /See:/ 'videoCategorySnippet' smart constructor.
data VideoCategorySnippet =
VideoCategorySnippet'
{ _vcsAssignable :: !(Maybe Bool)
, _vcsChannelId :: !Text
, _vcsTitle :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoCategorySnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vcsAssignable'
--
-- * 'vcsChannelId'
--
-- * 'vcsTitle'
videoCategorySnippet
:: VideoCategorySnippet
videoCategorySnippet =
VideoCategorySnippet'
{ _vcsAssignable = Nothing
, _vcsChannelId = "UCBR8-60-B28hp2BmDPdntcQ"
, _vcsTitle = Nothing
}
vcsAssignable :: Lens' VideoCategorySnippet (Maybe Bool)
vcsAssignable
= lens _vcsAssignable
(\ s a -> s{_vcsAssignable = a})
-- | The YouTube channel that created the video category.
vcsChannelId :: Lens' VideoCategorySnippet Text
vcsChannelId
= lens _vcsChannelId (\ s a -> s{_vcsChannelId = a})
-- | The video category\'s title.
vcsTitle :: Lens' VideoCategorySnippet (Maybe Text)
vcsTitle = lens _vcsTitle (\ s a -> s{_vcsTitle = a})
instance FromJSON VideoCategorySnippet where
parseJSON
= withObject "VideoCategorySnippet"
(\ o ->
VideoCategorySnippet' <$>
(o .:? "assignable") <*>
(o .:? "channelId" .!= "UCBR8-60-B28hp2BmDPdntcQ")
<*> (o .:? "title"))
instance ToJSON VideoCategorySnippet where
toJSON VideoCategorySnippet'{..}
= object
(catMaybes
[("assignable" .=) <$> _vcsAssignable,
Just ("channelId" .= _vcsChannelId),
("title" .=) <$> _vcsTitle])
-- | An *i18nLanguage* resource identifies a UI language currently supported
-- by YouTube.
--
-- /See:/ 'i18nLanguage' smart constructor.
data I18nLanguage =
I18nLanguage'
{ _ilEtag :: !(Maybe Text)
, _ilSnippet :: !(Maybe I18nLanguageSnippet)
, _ilKind :: !Text
, _ilId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nLanguage' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ilEtag'
--
-- * 'ilSnippet'
--
-- * 'ilKind'
--
-- * 'ilId'
i18nLanguage
:: I18nLanguage
i18nLanguage =
I18nLanguage'
{ _ilEtag = Nothing
, _ilSnippet = Nothing
, _ilKind = "youtube#i18nLanguage"
, _ilId = Nothing
}
-- | Etag of this resource.
ilEtag :: Lens' I18nLanguage (Maybe Text)
ilEtag = lens _ilEtag (\ s a -> s{_ilEtag = a})
-- | The snippet object contains basic details about the i18n language, such
-- as language code and human-readable name.
ilSnippet :: Lens' I18nLanguage (Maybe I18nLanguageSnippet)
ilSnippet
= lens _ilSnippet (\ s a -> s{_ilSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#i18nLanguage\".
ilKind :: Lens' I18nLanguage Text
ilKind = lens _ilKind (\ s a -> s{_ilKind = a})
-- | The ID that YouTube uses to uniquely identify the i18n language.
ilId :: Lens' I18nLanguage (Maybe Text)
ilId = lens _ilId (\ s a -> s{_ilId = a})
instance FromJSON I18nLanguage where
parseJSON
= withObject "I18nLanguage"
(\ o ->
I18nLanguage' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#i18nLanguage")
<*> (o .:? "id"))
instance ToJSON I18nLanguage where
toJSON I18nLanguage'{..}
= object
(catMaybes
[("etag" .=) <$> _ilEtag,
("snippet" .=) <$> _ilSnippet,
Just ("kind" .= _ilKind), ("id" .=) <$> _ilId])
-- | Statistics about the video, such as the number of times the video was
-- viewed or liked.
--
-- /See:/ 'videoStatistics' smart constructor.
data VideoStatistics =
VideoStatistics'
{ _vsLikeCount :: !(Maybe (Textual Word64))
, _vsCommentCount :: !(Maybe (Textual Word64))
, _vsFavoriteCount :: !(Maybe (Textual Word64))
, _vsDislikeCount :: !(Maybe (Textual Word64))
, _vsViewCount :: !(Maybe (Textual Word64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoStatistics' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vsLikeCount'
--
-- * 'vsCommentCount'
--
-- * 'vsFavoriteCount'
--
-- * 'vsDislikeCount'
--
-- * 'vsViewCount'
videoStatistics
:: VideoStatistics
videoStatistics =
VideoStatistics'
{ _vsLikeCount = Nothing
, _vsCommentCount = Nothing
, _vsFavoriteCount = Nothing
, _vsDislikeCount = Nothing
, _vsViewCount = Nothing
}
-- | The number of users who have indicated that they liked the video by
-- giving it a positive rating.
vsLikeCount :: Lens' VideoStatistics (Maybe Word64)
vsLikeCount
= lens _vsLikeCount (\ s a -> s{_vsLikeCount = a}) .
mapping _Coerce
-- | The number of comments for the video.
vsCommentCount :: Lens' VideoStatistics (Maybe Word64)
vsCommentCount
= lens _vsCommentCount
(\ s a -> s{_vsCommentCount = a})
. mapping _Coerce
-- | The number of users who currently have the video marked as a favorite
-- video.
vsFavoriteCount :: Lens' VideoStatistics (Maybe Word64)
vsFavoriteCount
= lens _vsFavoriteCount
(\ s a -> s{_vsFavoriteCount = a})
. mapping _Coerce
-- | The number of users who have indicated that they disliked the video by
-- giving it a negative rating.
vsDislikeCount :: Lens' VideoStatistics (Maybe Word64)
vsDislikeCount
= lens _vsDislikeCount
(\ s a -> s{_vsDislikeCount = a})
. mapping _Coerce
-- | The number of times the video has been viewed.
vsViewCount :: Lens' VideoStatistics (Maybe Word64)
vsViewCount
= lens _vsViewCount (\ s a -> s{_vsViewCount = a}) .
mapping _Coerce
instance FromJSON VideoStatistics where
parseJSON
= withObject "VideoStatistics"
(\ o ->
VideoStatistics' <$>
(o .:? "likeCount") <*> (o .:? "commentCount") <*>
(o .:? "favoriteCount")
<*> (o .:? "dislikeCount")
<*> (o .:? "viewCount"))
instance ToJSON VideoStatistics where
toJSON VideoStatistics'{..}
= object
(catMaybes
[("likeCount" .=) <$> _vsLikeCount,
("commentCount" .=) <$> _vsCommentCount,
("favoriteCount" .=) <$> _vsFavoriteCount,
("dislikeCount" .=) <$> _vsDislikeCount,
("viewCount" .=) <$> _vsViewCount])
--
-- /See:/ 'activityListResponse' smart constructor.
data ActivityListResponse =
ActivityListResponse'
{ _alrEtag :: !(Maybe Text)
, _alrTokenPagination :: !(Maybe TokenPagination)
, _alrNextPageToken :: !(Maybe Text)
, _alrPageInfo :: !(Maybe PageInfo)
, _alrKind :: !Text
, _alrItems :: !(Maybe [Activity])
, _alrVisitorId :: !(Maybe Text)
, _alrEventId :: !(Maybe Text)
, _alrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'alrEtag'
--
-- * 'alrTokenPagination'
--
-- * 'alrNextPageToken'
--
-- * 'alrPageInfo'
--
-- * 'alrKind'
--
-- * 'alrItems'
--
-- * 'alrVisitorId'
--
-- * 'alrEventId'
--
-- * 'alrPrevPageToken'
activityListResponse
:: ActivityListResponse
activityListResponse =
ActivityListResponse'
{ _alrEtag = Nothing
, _alrTokenPagination = Nothing
, _alrNextPageToken = Nothing
, _alrPageInfo = Nothing
, _alrKind = "youtube#activityListResponse"
, _alrItems = Nothing
, _alrVisitorId = Nothing
, _alrEventId = Nothing
, _alrPrevPageToken = Nothing
}
-- | Etag of this resource.
alrEtag :: Lens' ActivityListResponse (Maybe Text)
alrEtag = lens _alrEtag (\ s a -> s{_alrEtag = a})
alrTokenPagination :: Lens' ActivityListResponse (Maybe TokenPagination)
alrTokenPagination
= lens _alrTokenPagination
(\ s a -> s{_alrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
alrNextPageToken :: Lens' ActivityListResponse (Maybe Text)
alrNextPageToken
= lens _alrNextPageToken
(\ s a -> s{_alrNextPageToken = a})
-- | General pagination information.
alrPageInfo :: Lens' ActivityListResponse (Maybe PageInfo)
alrPageInfo
= lens _alrPageInfo (\ s a -> s{_alrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#activityListResponse\".
alrKind :: Lens' ActivityListResponse Text
alrKind = lens _alrKind (\ s a -> s{_alrKind = a})
alrItems :: Lens' ActivityListResponse [Activity]
alrItems
= lens _alrItems (\ s a -> s{_alrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
alrVisitorId :: Lens' ActivityListResponse (Maybe Text)
alrVisitorId
= lens _alrVisitorId (\ s a -> s{_alrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
alrEventId :: Lens' ActivityListResponse (Maybe Text)
alrEventId
= lens _alrEventId (\ s a -> s{_alrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
alrPrevPageToken :: Lens' ActivityListResponse (Maybe Text)
alrPrevPageToken
= lens _alrPrevPageToken
(\ s a -> s{_alrPrevPageToken = a})
instance FromJSON ActivityListResponse where
parseJSON
= withObject "ActivityListResponse"
(\ o ->
ActivityListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#activityListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON ActivityListResponse where
toJSON ActivityListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _alrEtag,
("tokenPagination" .=) <$> _alrTokenPagination,
("nextPageToken" .=) <$> _alrNextPageToken,
("pageInfo" .=) <$> _alrPageInfo,
Just ("kind" .= _alrKind),
("items" .=) <$> _alrItems,
("visitorId" .=) <$> _alrVisitorId,
("eventId" .=) <$> _alrEventId,
("prevPageToken" .=) <$> _alrPrevPageToken])
-- | Details about a channel bulletin post.
--
-- /See:/ 'activityContentDetailsBulletin' smart constructor.
newtype ActivityContentDetailsBulletin =
ActivityContentDetailsBulletin'
{ _acdbResourceId :: Maybe ResourceId
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsBulletin' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdbResourceId'
activityContentDetailsBulletin
:: ActivityContentDetailsBulletin
activityContentDetailsBulletin =
ActivityContentDetailsBulletin' {_acdbResourceId = Nothing}
-- | The resourceId object contains information that identifies the resource
-- associated with a bulletin post. \'mutable youtube.activities.insert
acdbResourceId :: Lens' ActivityContentDetailsBulletin (Maybe ResourceId)
acdbResourceId
= lens _acdbResourceId
(\ s a -> s{_acdbResourceId = a})
instance FromJSON ActivityContentDetailsBulletin
where
parseJSON
= withObject "ActivityContentDetailsBulletin"
(\ o ->
ActivityContentDetailsBulletin' <$>
(o .:? "resourceId"))
instance ToJSON ActivityContentDetailsBulletin where
toJSON ActivityContentDetailsBulletin'{..}
= object
(catMaybes [("resourceId" .=) <$> _acdbResourceId])
--
-- /See:/ 'videoAbuseReport' smart constructor.
data VideoAbuseReport =
VideoAbuseReport'
{ _varSecondaryReasonId :: !(Maybe Text)
, _varReasonId :: !(Maybe Text)
, _varVideoId :: !(Maybe Text)
, _varLanguage :: !(Maybe Text)
, _varComments :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoAbuseReport' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'varSecondaryReasonId'
--
-- * 'varReasonId'
--
-- * 'varVideoId'
--
-- * 'varLanguage'
--
-- * 'varComments'
videoAbuseReport
:: VideoAbuseReport
videoAbuseReport =
VideoAbuseReport'
{ _varSecondaryReasonId = Nothing
, _varReasonId = Nothing
, _varVideoId = Nothing
, _varLanguage = Nothing
, _varComments = Nothing
}
-- | The ID of this abuse report secondary reason.
varSecondaryReasonId :: Lens' VideoAbuseReport (Maybe Text)
varSecondaryReasonId
= lens _varSecondaryReasonId
(\ s a -> s{_varSecondaryReasonId = a})
-- | The high-level, or primary, reason that the content is abusive. The
-- value is an abuse report reason ID.
varReasonId :: Lens' VideoAbuseReport (Maybe Text)
varReasonId
= lens _varReasonId (\ s a -> s{_varReasonId = a})
-- | The ID that YouTube uses to uniquely identify the video.
varVideoId :: Lens' VideoAbuseReport (Maybe Text)
varVideoId
= lens _varVideoId (\ s a -> s{_varVideoId = a})
-- | The language that the content was viewed in.
varLanguage :: Lens' VideoAbuseReport (Maybe Text)
varLanguage
= lens _varLanguage (\ s a -> s{_varLanguage = a})
-- | Additional comments regarding the abuse report.
varComments :: Lens' VideoAbuseReport (Maybe Text)
varComments
= lens _varComments (\ s a -> s{_varComments = a})
instance FromJSON VideoAbuseReport where
parseJSON
= withObject "VideoAbuseReport"
(\ o ->
VideoAbuseReport' <$>
(o .:? "secondaryReasonId") <*> (o .:? "reasonId")
<*> (o .:? "videoId")
<*> (o .:? "language")
<*> (o .:? "comments"))
instance ToJSON VideoAbuseReport where
toJSON VideoAbuseReport'{..}
= object
(catMaybes
[("secondaryReasonId" .=) <$> _varSecondaryReasonId,
("reasonId" .=) <$> _varReasonId,
("videoId" .=) <$> _varVideoId,
("language" .=) <$> _varLanguage,
("comments" .=) <$> _varComments])
-- | Information about an audio stream.
--
-- /See:/ 'videoFileDetailsAudioStream' smart constructor.
data VideoFileDetailsAudioStream =
VideoFileDetailsAudioStream'
{ _vfdasBitrateBps :: !(Maybe (Textual Word64))
, _vfdasVendor :: !(Maybe Text)
, _vfdasCodec :: !(Maybe Text)
, _vfdasChannelCount :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoFileDetailsAudioStream' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vfdasBitrateBps'
--
-- * 'vfdasVendor'
--
-- * 'vfdasCodec'
--
-- * 'vfdasChannelCount'
videoFileDetailsAudioStream
:: VideoFileDetailsAudioStream
videoFileDetailsAudioStream =
VideoFileDetailsAudioStream'
{ _vfdasBitrateBps = Nothing
, _vfdasVendor = Nothing
, _vfdasCodec = Nothing
, _vfdasChannelCount = Nothing
}
-- | The audio stream\'s bitrate, in bits per second.
vfdasBitrateBps :: Lens' VideoFileDetailsAudioStream (Maybe Word64)
vfdasBitrateBps
= lens _vfdasBitrateBps
(\ s a -> s{_vfdasBitrateBps = a})
. mapping _Coerce
-- | A value that uniquely identifies a video vendor. Typically, the value is
-- a four-letter vendor code.
vfdasVendor :: Lens' VideoFileDetailsAudioStream (Maybe Text)
vfdasVendor
= lens _vfdasVendor (\ s a -> s{_vfdasVendor = a})
-- | The audio codec that the stream uses.
vfdasCodec :: Lens' VideoFileDetailsAudioStream (Maybe Text)
vfdasCodec
= lens _vfdasCodec (\ s a -> s{_vfdasCodec = a})
-- | The number of audio channels that the stream contains.
vfdasChannelCount :: Lens' VideoFileDetailsAudioStream (Maybe Word32)
vfdasChannelCount
= lens _vfdasChannelCount
(\ s a -> s{_vfdasChannelCount = a})
. mapping _Coerce
instance FromJSON VideoFileDetailsAudioStream where
parseJSON
= withObject "VideoFileDetailsAudioStream"
(\ o ->
VideoFileDetailsAudioStream' <$>
(o .:? "bitrateBps") <*> (o .:? "vendor") <*>
(o .:? "codec")
<*> (o .:? "channelCount"))
instance ToJSON VideoFileDetailsAudioStream where
toJSON VideoFileDetailsAudioStream'{..}
= object
(catMaybes
[("bitrateBps" .=) <$> _vfdasBitrateBps,
("vendor" .=) <$> _vfdasVendor,
("codec" .=) <$> _vfdasCodec,
("channelCount" .=) <$> _vfdasChannelCount])
--
-- /See:/ 'i18nRegionListResponse' smart constructor.
data I18nRegionListResponse =
I18nRegionListResponse'
{ _irlrEtag :: !(Maybe Text)
, _irlrKind :: !Text
, _irlrItems :: !(Maybe [I18nRegion])
, _irlrVisitorId :: !(Maybe Text)
, _irlrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nRegionListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'irlrEtag'
--
-- * 'irlrKind'
--
-- * 'irlrItems'
--
-- * 'irlrVisitorId'
--
-- * 'irlrEventId'
i18nRegionListResponse
:: I18nRegionListResponse
i18nRegionListResponse =
I18nRegionListResponse'
{ _irlrEtag = Nothing
, _irlrKind = "youtube#i18nRegionListResponse"
, _irlrItems = Nothing
, _irlrVisitorId = Nothing
, _irlrEventId = Nothing
}
-- | Etag of this resource.
irlrEtag :: Lens' I18nRegionListResponse (Maybe Text)
irlrEtag = lens _irlrEtag (\ s a -> s{_irlrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#i18nRegionListResponse\".
irlrKind :: Lens' I18nRegionListResponse Text
irlrKind = lens _irlrKind (\ s a -> s{_irlrKind = a})
-- | A list of regions where YouTube is available. In this map, the i18n
-- region ID is the map key, and its value is the corresponding i18nRegion
-- resource.
irlrItems :: Lens' I18nRegionListResponse [I18nRegion]
irlrItems
= lens _irlrItems (\ s a -> s{_irlrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
irlrVisitorId :: Lens' I18nRegionListResponse (Maybe Text)
irlrVisitorId
= lens _irlrVisitorId
(\ s a -> s{_irlrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
irlrEventId :: Lens' I18nRegionListResponse (Maybe Text)
irlrEventId
= lens _irlrEventId (\ s a -> s{_irlrEventId = a})
instance FromJSON I18nRegionListResponse where
parseJSON
= withObject "I18nRegionListResponse"
(\ o ->
I18nRegionListResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "youtube#i18nRegionListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON I18nRegionListResponse where
toJSON I18nRegionListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _irlrEtag,
Just ("kind" .= _irlrKind),
("items" .=) <$> _irlrItems,
("visitorId" .=) <$> _irlrVisitorId,
("eventId" .=) <$> _irlrEventId])
--
-- /See:/ 'membershipsDuration' smart constructor.
data MembershipsDuration =
MembershipsDuration'
{ _mdMemberTotalDurationMonths :: !(Maybe (Textual Int32))
, _mdMemberSince :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MembershipsDuration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdMemberTotalDurationMonths'
--
-- * 'mdMemberSince'
membershipsDuration
:: MembershipsDuration
membershipsDuration =
MembershipsDuration'
{_mdMemberTotalDurationMonths = Nothing, _mdMemberSince = Nothing}
-- | The cumulative time the user has been a member across all levels in
-- complete months (the time is rounded down to the nearest integer).
mdMemberTotalDurationMonths :: Lens' MembershipsDuration (Maybe Int32)
mdMemberTotalDurationMonths
= lens _mdMemberTotalDurationMonths
(\ s a -> s{_mdMemberTotalDurationMonths = a})
. mapping _Coerce
-- | The date and time when the user became a continuous member across all
-- levels.
mdMemberSince :: Lens' MembershipsDuration (Maybe Text)
mdMemberSince
= lens _mdMemberSince
(\ s a -> s{_mdMemberSince = a})
instance FromJSON MembershipsDuration where
parseJSON
= withObject "MembershipsDuration"
(\ o ->
MembershipsDuration' <$>
(o .:? "memberTotalDurationMonths") <*>
(o .:? "memberSince"))
instance ToJSON MembershipsDuration where
toJSON MembershipsDuration'{..}
= object
(catMaybes
[("memberTotalDurationMonths" .=) <$>
_mdMemberTotalDurationMonths,
("memberSince" .=) <$> _mdMemberSince])
--
-- /See:/ 'captionListResponse' smart constructor.
data CaptionListResponse =
CaptionListResponse'
{ _cEtag :: !(Maybe Text)
, _cKind :: !Text
, _cItems :: !(Maybe [Caption])
, _cVisitorId :: !(Maybe Text)
, _cEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CaptionListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cEtag'
--
-- * 'cKind'
--
-- * 'cItems'
--
-- * 'cVisitorId'
--
-- * 'cEventId'
captionListResponse
:: CaptionListResponse
captionListResponse =
CaptionListResponse'
{ _cEtag = Nothing
, _cKind = "youtube#captionListResponse"
, _cItems = Nothing
, _cVisitorId = Nothing
, _cEventId = Nothing
}
-- | Etag of this resource.
cEtag :: Lens' CaptionListResponse (Maybe Text)
cEtag = lens _cEtag (\ s a -> s{_cEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#captionListResponse\".
cKind :: Lens' CaptionListResponse Text
cKind = lens _cKind (\ s a -> s{_cKind = a})
-- | A list of captions that match the request criteria.
cItems :: Lens' CaptionListResponse [Caption]
cItems
= lens _cItems (\ s a -> s{_cItems = a}) . _Default .
_Coerce
-- | The visitorId identifies the visitor.
cVisitorId :: Lens' CaptionListResponse (Maybe Text)
cVisitorId
= lens _cVisitorId (\ s a -> s{_cVisitorId = a})
-- | Serialized EventId of the request which produced this response.
cEventId :: Lens' CaptionListResponse (Maybe Text)
cEventId = lens _cEventId (\ s a -> s{_cEventId = a})
instance FromJSON CaptionListResponse where
parseJSON
= withObject "CaptionListResponse"
(\ o ->
CaptionListResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "youtube#captionListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON CaptionListResponse where
toJSON CaptionListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _cEtag, Just ("kind" .= _cKind),
("items" .=) <$> _cItems,
("visitorId" .=) <$> _cVisitorId,
("eventId" .=) <$> _cEventId])
-- | Information about the playlist item\'s privacy status.
--
-- /See:/ 'playListItemStatus' smart constructor.
newtype PlayListItemStatus =
PlayListItemStatus'
{ _plisPrivacyStatus :: Maybe PlayListItemStatusPrivacyStatus
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListItemStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plisPrivacyStatus'
playListItemStatus
:: PlayListItemStatus
playListItemStatus = PlayListItemStatus' {_plisPrivacyStatus = Nothing}
-- | This resource\'s privacy status.
plisPrivacyStatus :: Lens' PlayListItemStatus (Maybe PlayListItemStatusPrivacyStatus)
plisPrivacyStatus
= lens _plisPrivacyStatus
(\ s a -> s{_plisPrivacyStatus = a})
instance FromJSON PlayListItemStatus where
parseJSON
= withObject "PlayListItemStatus"
(\ o ->
PlayListItemStatus' <$> (o .:? "privacyStatus"))
instance ToJSON PlayListItemStatus where
toJSON PlayListItemStatus'{..}
= object
(catMaybes
[("privacyStatus" .=) <$> _plisPrivacyStatus])
-- | Describes the spatial position of a visual widget inside a video. It is
-- a union of various position types, out of which only will be set one.
--
-- /See:/ 'invideoPosition' smart constructor.
data InvideoPosition =
InvideoPosition'
{ _ipCornerPosition :: !(Maybe InvideoPositionCornerPosition)
, _ipType :: !(Maybe InvideoPositionType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InvideoPosition' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ipCornerPosition'
--
-- * 'ipType'
invideoPosition
:: InvideoPosition
invideoPosition =
InvideoPosition' {_ipCornerPosition = Nothing, _ipType = Nothing}
-- | Describes in which corner of the video the visual widget will appear.
ipCornerPosition :: Lens' InvideoPosition (Maybe InvideoPositionCornerPosition)
ipCornerPosition
= lens _ipCornerPosition
(\ s a -> s{_ipCornerPosition = a})
-- | Defines the position type.
ipType :: Lens' InvideoPosition (Maybe InvideoPositionType)
ipType = lens _ipType (\ s a -> s{_ipType = a})
instance FromJSON InvideoPosition where
parseJSON
= withObject "InvideoPosition"
(\ o ->
InvideoPosition' <$>
(o .:? "cornerPosition") <*> (o .:? "type"))
instance ToJSON InvideoPosition where
toJSON InvideoPosition'{..}
= object
(catMaybes
[("cornerPosition" .=) <$> _ipCornerPosition,
("type" .=) <$> _ipType])
--
-- /See:/ 'liveChatSuperStickerDetails' smart constructor.
data LiveChatSuperStickerDetails =
LiveChatSuperStickerDetails'
{ _lcssdSuperStickerMetadata :: !(Maybe SuperStickerMetadata)
, _lcssdAmountMicros :: !(Maybe (Textual Word64))
, _lcssdAmountDisplayString :: !(Maybe Text)
, _lcssdCurrency :: !(Maybe Text)
, _lcssdTier :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatSuperStickerDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcssdSuperStickerMetadata'
--
-- * 'lcssdAmountMicros'
--
-- * 'lcssdAmountDisplayString'
--
-- * 'lcssdCurrency'
--
-- * 'lcssdTier'
liveChatSuperStickerDetails
:: LiveChatSuperStickerDetails
liveChatSuperStickerDetails =
LiveChatSuperStickerDetails'
{ _lcssdSuperStickerMetadata = Nothing
, _lcssdAmountMicros = Nothing
, _lcssdAmountDisplayString = Nothing
, _lcssdCurrency = Nothing
, _lcssdTier = Nothing
}
-- | Information about the Super Sticker.
lcssdSuperStickerMetadata :: Lens' LiveChatSuperStickerDetails (Maybe SuperStickerMetadata)
lcssdSuperStickerMetadata
= lens _lcssdSuperStickerMetadata
(\ s a -> s{_lcssdSuperStickerMetadata = a})
-- | The amount purchased by the user, in micros (1,750,000 micros = 1.75).
lcssdAmountMicros :: Lens' LiveChatSuperStickerDetails (Maybe Word64)
lcssdAmountMicros
= lens _lcssdAmountMicros
(\ s a -> s{_lcssdAmountMicros = a})
. mapping _Coerce
-- | A rendered string that displays the fund amount and currency to the
-- user.
lcssdAmountDisplayString :: Lens' LiveChatSuperStickerDetails (Maybe Text)
lcssdAmountDisplayString
= lens _lcssdAmountDisplayString
(\ s a -> s{_lcssdAmountDisplayString = a})
-- | The currency in which the purchase was made.
lcssdCurrency :: Lens' LiveChatSuperStickerDetails (Maybe Text)
lcssdCurrency
= lens _lcssdCurrency
(\ s a -> s{_lcssdCurrency = a})
-- | The tier in which the amount belongs. Lower amounts belong to lower
-- tiers. The lowest tier is 1.
lcssdTier :: Lens' LiveChatSuperStickerDetails (Maybe Word32)
lcssdTier
= lens _lcssdTier (\ s a -> s{_lcssdTier = a}) .
mapping _Coerce
instance FromJSON LiveChatSuperStickerDetails where
parseJSON
= withObject "LiveChatSuperStickerDetails"
(\ o ->
LiveChatSuperStickerDetails' <$>
(o .:? "superStickerMetadata") <*>
(o .:? "amountMicros")
<*> (o .:? "amountDisplayString")
<*> (o .:? "currency")
<*> (o .:? "tier"))
instance ToJSON LiveChatSuperStickerDetails where
toJSON LiveChatSuperStickerDetails'{..}
= object
(catMaybes
[("superStickerMetadata" .=) <$>
_lcssdSuperStickerMetadata,
("amountMicros" .=) <$> _lcssdAmountMicros,
("amountDisplayString" .=) <$>
_lcssdAmountDisplayString,
("currency" .=) <$> _lcssdCurrency,
("tier" .=) <$> _lcssdTier])
--
-- /See:/ 'liveStreamHealthStatus' smart constructor.
data LiveStreamHealthStatus =
LiveStreamHealthStatus'
{ _lshsStatus :: !(Maybe LiveStreamHealthStatusStatus)
, _lshsConfigurationIssues :: !(Maybe [LiveStreamConfigurationIssue])
, _lshsLastUpdateTimeSeconds :: !(Maybe (Textual Word64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStreamHealthStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lshsStatus'
--
-- * 'lshsConfigurationIssues'
--
-- * 'lshsLastUpdateTimeSeconds'
liveStreamHealthStatus
:: LiveStreamHealthStatus
liveStreamHealthStatus =
LiveStreamHealthStatus'
{ _lshsStatus = Nothing
, _lshsConfigurationIssues = Nothing
, _lshsLastUpdateTimeSeconds = Nothing
}
-- | The status code of this stream
lshsStatus :: Lens' LiveStreamHealthStatus (Maybe LiveStreamHealthStatusStatus)
lshsStatus
= lens _lshsStatus (\ s a -> s{_lshsStatus = a})
-- | The configurations issues on this stream
lshsConfigurationIssues :: Lens' LiveStreamHealthStatus [LiveStreamConfigurationIssue]
lshsConfigurationIssues
= lens _lshsConfigurationIssues
(\ s a -> s{_lshsConfigurationIssues = a})
. _Default
. _Coerce
-- | The last time this status was updated (in seconds)
lshsLastUpdateTimeSeconds :: Lens' LiveStreamHealthStatus (Maybe Word64)
lshsLastUpdateTimeSeconds
= lens _lshsLastUpdateTimeSeconds
(\ s a -> s{_lshsLastUpdateTimeSeconds = a})
. mapping _Coerce
instance FromJSON LiveStreamHealthStatus where
parseJSON
= withObject "LiveStreamHealthStatus"
(\ o ->
LiveStreamHealthStatus' <$>
(o .:? "status") <*>
(o .:? "configurationIssues" .!= mempty)
<*> (o .:? "lastUpdateTimeSeconds"))
instance ToJSON LiveStreamHealthStatus where
toJSON LiveStreamHealthStatus'{..}
= object
(catMaybes
[("status" .=) <$> _lshsStatus,
("configurationIssues" .=) <$>
_lshsConfigurationIssues,
("lastUpdateTimeSeconds" .=) <$>
_lshsLastUpdateTimeSeconds])
-- | Localizations for different languages
--
-- /See:/ 'channelSectionLocalizations' smart constructor.
newtype ChannelSectionLocalizations =
ChannelSectionLocalizations'
{ _cslAddtional :: HashMap Text ChannelSectionLocalization
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSectionLocalizations' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cslAddtional'
channelSectionLocalizations
:: HashMap Text ChannelSectionLocalization -- ^ 'cslAddtional'
-> ChannelSectionLocalizations
channelSectionLocalizations pCslAddtional_ =
ChannelSectionLocalizations' {_cslAddtional = _Coerce # pCslAddtional_}
cslAddtional :: Lens' ChannelSectionLocalizations (HashMap Text ChannelSectionLocalization)
cslAddtional
= lens _cslAddtional (\ s a -> s{_cslAddtional = a})
. _Coerce
instance FromJSON ChannelSectionLocalizations where
parseJSON
= withObject "ChannelSectionLocalizations"
(\ o ->
ChannelSectionLocalizations' <$> (parseJSONObject o))
instance ToJSON ChannelSectionLocalizations where
toJSON = toJSON . _cslAddtional
--
-- /See:/ 'subscriptionListResponse' smart constructor.
data SubscriptionListResponse =
SubscriptionListResponse'
{ _sEtag :: !(Maybe Text)
, _sTokenPagination :: !(Maybe TokenPagination)
, _sNextPageToken :: !(Maybe Text)
, _sPageInfo :: !(Maybe PageInfo)
, _sKind :: !Text
, _sItems :: !(Maybe [Subscription])
, _sVisitorId :: !(Maybe Text)
, _sEventId :: !(Maybe Text)
, _sPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SubscriptionListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sEtag'
--
-- * 'sTokenPagination'
--
-- * 'sNextPageToken'
--
-- * 'sPageInfo'
--
-- * 'sKind'
--
-- * 'sItems'
--
-- * 'sVisitorId'
--
-- * 'sEventId'
--
-- * 'sPrevPageToken'
subscriptionListResponse
:: SubscriptionListResponse
subscriptionListResponse =
SubscriptionListResponse'
{ _sEtag = Nothing
, _sTokenPagination = Nothing
, _sNextPageToken = Nothing
, _sPageInfo = Nothing
, _sKind = "youtube#subscriptionListResponse"
, _sItems = Nothing
, _sVisitorId = Nothing
, _sEventId = Nothing
, _sPrevPageToken = Nothing
}
-- | Etag of this resource.
sEtag :: Lens' SubscriptionListResponse (Maybe Text)
sEtag = lens _sEtag (\ s a -> s{_sEtag = a})
sTokenPagination :: Lens' SubscriptionListResponse (Maybe TokenPagination)
sTokenPagination
= lens _sTokenPagination
(\ s a -> s{_sTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
sNextPageToken :: Lens' SubscriptionListResponse (Maybe Text)
sNextPageToken
= lens _sNextPageToken
(\ s a -> s{_sNextPageToken = a})
sPageInfo :: Lens' SubscriptionListResponse (Maybe PageInfo)
sPageInfo
= lens _sPageInfo (\ s a -> s{_sPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#subscriptionListResponse\".
sKind :: Lens' SubscriptionListResponse Text
sKind = lens _sKind (\ s a -> s{_sKind = a})
-- | A list of subscriptions that match the request criteria.
sItems :: Lens' SubscriptionListResponse [Subscription]
sItems
= lens _sItems (\ s a -> s{_sItems = a}) . _Default .
_Coerce
-- | The visitorId identifies the visitor.
sVisitorId :: Lens' SubscriptionListResponse (Maybe Text)
sVisitorId
= lens _sVisitorId (\ s a -> s{_sVisitorId = a})
-- | Serialized EventId of the request which produced this response.
sEventId :: Lens' SubscriptionListResponse (Maybe Text)
sEventId = lens _sEventId (\ s a -> s{_sEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
sPrevPageToken :: Lens' SubscriptionListResponse (Maybe Text)
sPrevPageToken
= lens _sPrevPageToken
(\ s a -> s{_sPrevPageToken = a})
instance FromJSON SubscriptionListResponse where
parseJSON
= withObject "SubscriptionListResponse"
(\ o ->
SubscriptionListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!= "youtube#subscriptionListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON SubscriptionListResponse where
toJSON SubscriptionListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _sEtag,
("tokenPagination" .=) <$> _sTokenPagination,
("nextPageToken" .=) <$> _sNextPageToken,
("pageInfo" .=) <$> _sPageInfo,
Just ("kind" .= _sKind), ("items" .=) <$> _sItems,
("visitorId" .=) <$> _sVisitorId,
("eventId" .=) <$> _sEventId,
("prevPageToken" .=) <$> _sPrevPageToken])
-- | Localized versions of certain video properties (e.g. title).
--
-- /See:/ 'videoLocalization' smart constructor.
data VideoLocalization =
VideoLocalization'
{ _vlTitle :: !(Maybe Text)
, _vlDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoLocalization' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vlTitle'
--
-- * 'vlDescription'
videoLocalization
:: VideoLocalization
videoLocalization =
VideoLocalization' {_vlTitle = Nothing, _vlDescription = Nothing}
-- | Localized version of the video\'s title.
vlTitle :: Lens' VideoLocalization (Maybe Text)
vlTitle = lens _vlTitle (\ s a -> s{_vlTitle = a})
-- | Localized version of the video\'s description.
vlDescription :: Lens' VideoLocalization (Maybe Text)
vlDescription
= lens _vlDescription
(\ s a -> s{_vlDescription = a})
instance FromJSON VideoLocalization where
parseJSON
= withObject "VideoLocalization"
(\ o ->
VideoLocalization' <$>
(o .:? "title") <*> (o .:? "description"))
instance ToJSON VideoLocalization where
toJSON VideoLocalization'{..}
= object
(catMaybes
[("title" .=) <$> _vlTitle,
("description" .=) <$> _vlDescription])
--
-- /See:/ 'commentListResponse' smart constructor.
data CommentListResponse =
CommentListResponse'
{ _comEtag :: !(Maybe Text)
, _comTokenPagination :: !(Maybe TokenPagination)
, _comNextPageToken :: !(Maybe Text)
, _comPageInfo :: !(Maybe PageInfo)
, _comKind :: !Text
, _comItems :: !(Maybe [Comment])
, _comVisitorId :: !(Maybe Text)
, _comEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'comEtag'
--
-- * 'comTokenPagination'
--
-- * 'comNextPageToken'
--
-- * 'comPageInfo'
--
-- * 'comKind'
--
-- * 'comItems'
--
-- * 'comVisitorId'
--
-- * 'comEventId'
commentListResponse
:: CommentListResponse
commentListResponse =
CommentListResponse'
{ _comEtag = Nothing
, _comTokenPagination = Nothing
, _comNextPageToken = Nothing
, _comPageInfo = Nothing
, _comKind = "youtube#commentListResponse"
, _comItems = Nothing
, _comVisitorId = Nothing
, _comEventId = Nothing
}
-- | Etag of this resource.
comEtag :: Lens' CommentListResponse (Maybe Text)
comEtag = lens _comEtag (\ s a -> s{_comEtag = a})
comTokenPagination :: Lens' CommentListResponse (Maybe TokenPagination)
comTokenPagination
= lens _comTokenPagination
(\ s a -> s{_comTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
comNextPageToken :: Lens' CommentListResponse (Maybe Text)
comNextPageToken
= lens _comNextPageToken
(\ s a -> s{_comNextPageToken = a})
-- | General pagination information.
comPageInfo :: Lens' CommentListResponse (Maybe PageInfo)
comPageInfo
= lens _comPageInfo (\ s a -> s{_comPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#commentListResponse\".
comKind :: Lens' CommentListResponse Text
comKind = lens _comKind (\ s a -> s{_comKind = a})
-- | A list of comments that match the request criteria.
comItems :: Lens' CommentListResponse [Comment]
comItems
= lens _comItems (\ s a -> s{_comItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
comVisitorId :: Lens' CommentListResponse (Maybe Text)
comVisitorId
= lens _comVisitorId (\ s a -> s{_comVisitorId = a})
-- | Serialized EventId of the request which produced this response.
comEventId :: Lens' CommentListResponse (Maybe Text)
comEventId
= lens _comEventId (\ s a -> s{_comEventId = a})
instance FromJSON CommentListResponse where
parseJSON
= withObject "CommentListResponse"
(\ o ->
CommentListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#commentListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON CommentListResponse where
toJSON CommentListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _comEtag,
("tokenPagination" .=) <$> _comTokenPagination,
("nextPageToken" .=) <$> _comNextPageToken,
("pageInfo" .=) <$> _comPageInfo,
Just ("kind" .= _comKind),
("items" .=) <$> _comItems,
("visitorId" .=) <$> _comVisitorId,
("eventId" .=) <$> _comEventId])
-- | Player to be used for a video playback.
--
-- /See:/ 'videoPlayer' smart constructor.
data VideoPlayer =
VideoPlayer'
{ _vpEmbedHeight :: !(Maybe (Textual Int64))
, _vpEmbedWidth :: !(Maybe (Textual Int64))
, _vpEmbedHTML :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoPlayer' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vpEmbedHeight'
--
-- * 'vpEmbedWidth'
--
-- * 'vpEmbedHTML'
videoPlayer
:: VideoPlayer
videoPlayer =
VideoPlayer'
{_vpEmbedHeight = Nothing, _vpEmbedWidth = Nothing, _vpEmbedHTML = Nothing}
vpEmbedHeight :: Lens' VideoPlayer (Maybe Int64)
vpEmbedHeight
= lens _vpEmbedHeight
(\ s a -> s{_vpEmbedHeight = a})
. mapping _Coerce
-- | The embed width
vpEmbedWidth :: Lens' VideoPlayer (Maybe Int64)
vpEmbedWidth
= lens _vpEmbedWidth (\ s a -> s{_vpEmbedWidth = a})
. mapping _Coerce
-- | An
-- tag that embeds a player that will play the video.
vpEmbedHTML :: Lens' VideoPlayer (Maybe Text)
vpEmbedHTML
= lens _vpEmbedHTML (\ s a -> s{_vpEmbedHTML = a})
instance FromJSON VideoPlayer where
parseJSON
= withObject "VideoPlayer"
(\ o ->
VideoPlayer' <$>
(o .:? "embedHeight") <*> (o .:? "embedWidth") <*>
(o .:? "embedHtml"))
instance ToJSON VideoPlayer where
toJSON VideoPlayer'{..}
= object
(catMaybes
[("embedHeight" .=) <$> _vpEmbedHeight,
("embedWidth" .=) <$> _vpEmbedWidth,
("embedHtml" .=) <$> _vpEmbedHTML])
--
-- /See:/ 'localizedString' smart constructor.
data LocalizedString =
LocalizedString'
{ _lsValue :: !(Maybe Text)
, _lsLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LocalizedString' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lsValue'
--
-- * 'lsLanguage'
localizedString
:: LocalizedString
localizedString = LocalizedString' {_lsValue = Nothing, _lsLanguage = Nothing}
lsValue :: Lens' LocalizedString (Maybe Text)
lsValue = lens _lsValue (\ s a -> s{_lsValue = a})
lsLanguage :: Lens' LocalizedString (Maybe Text)
lsLanguage
= lens _lsLanguage (\ s a -> s{_lsLanguage = a})
instance FromJSON LocalizedString where
parseJSON
= withObject "LocalizedString"
(\ o ->
LocalizedString' <$>
(o .:? "value") <*> (o .:? "language"))
instance ToJSON LocalizedString where
toJSON LocalizedString'{..}
= object
(catMaybes
[("value" .=) <$> _lsValue,
("language" .=) <$> _lsLanguage])
--
-- /See:/ 'membershipsLevelSnippet' smart constructor.
data MembershipsLevelSnippet =
MembershipsLevelSnippet'
{ _mlsLevelDetails :: !(Maybe LevelDetails)
, _mlsCreatorChannelId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MembershipsLevelSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mlsLevelDetails'
--
-- * 'mlsCreatorChannelId'
membershipsLevelSnippet
:: MembershipsLevelSnippet
membershipsLevelSnippet =
MembershipsLevelSnippet'
{_mlsLevelDetails = Nothing, _mlsCreatorChannelId = Nothing}
-- | Details about the pricing level.
mlsLevelDetails :: Lens' MembershipsLevelSnippet (Maybe LevelDetails)
mlsLevelDetails
= lens _mlsLevelDetails
(\ s a -> s{_mlsLevelDetails = a})
-- | The id of the channel that\'s offering channel memberships.
mlsCreatorChannelId :: Lens' MembershipsLevelSnippet (Maybe Text)
mlsCreatorChannelId
= lens _mlsCreatorChannelId
(\ s a -> s{_mlsCreatorChannelId = a})
instance FromJSON MembershipsLevelSnippet where
parseJSON
= withObject "MembershipsLevelSnippet"
(\ o ->
MembershipsLevelSnippet' <$>
(o .:? "levelDetails") <*>
(o .:? "creatorChannelId"))
instance ToJSON MembershipsLevelSnippet where
toJSON MembershipsLevelSnippet'{..}
= object
(catMaybes
[("levelDetails" .=) <$> _mlsLevelDetails,
("creatorChannelId" .=) <$> _mlsCreatorChannelId])
--
-- /See:/ 'playListItemListResponse' smart constructor.
data PlayListItemListResponse =
PlayListItemListResponse'
{ _plilrEtag :: !(Maybe Text)
, _plilrTokenPagination :: !(Maybe TokenPagination)
, _plilrNextPageToken :: !(Maybe Text)
, _plilrPageInfo :: !(Maybe PageInfo)
, _plilrKind :: !Text
, _plilrItems :: !(Maybe [PlayListItem])
, _plilrVisitorId :: !(Maybe Text)
, _plilrEventId :: !(Maybe Text)
, _plilrPrevPageToken :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListItemListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plilrEtag'
--
-- * 'plilrTokenPagination'
--
-- * 'plilrNextPageToken'
--
-- * 'plilrPageInfo'
--
-- * 'plilrKind'
--
-- * 'plilrItems'
--
-- * 'plilrVisitorId'
--
-- * 'plilrEventId'
--
-- * 'plilrPrevPageToken'
playListItemListResponse
:: PlayListItemListResponse
playListItemListResponse =
PlayListItemListResponse'
{ _plilrEtag = Nothing
, _plilrTokenPagination = Nothing
, _plilrNextPageToken = Nothing
, _plilrPageInfo = Nothing
, _plilrKind = "youtube#playlistItemListResponse"
, _plilrItems = Nothing
, _plilrVisitorId = Nothing
, _plilrEventId = Nothing
, _plilrPrevPageToken = Nothing
}
plilrEtag :: Lens' PlayListItemListResponse (Maybe Text)
plilrEtag
= lens _plilrEtag (\ s a -> s{_plilrEtag = a})
plilrTokenPagination :: Lens' PlayListItemListResponse (Maybe TokenPagination)
plilrTokenPagination
= lens _plilrTokenPagination
(\ s a -> s{_plilrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
plilrNextPageToken :: Lens' PlayListItemListResponse (Maybe Text)
plilrNextPageToken
= lens _plilrNextPageToken
(\ s a -> s{_plilrNextPageToken = a})
-- | General pagination information.
plilrPageInfo :: Lens' PlayListItemListResponse (Maybe PageInfo)
plilrPageInfo
= lens _plilrPageInfo
(\ s a -> s{_plilrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#playlistItemListResponse\". Etag of this resource.
plilrKind :: Lens' PlayListItemListResponse Text
plilrKind
= lens _plilrKind (\ s a -> s{_plilrKind = a})
-- | A list of playlist items that match the request criteria.
plilrItems :: Lens' PlayListItemListResponse [PlayListItem]
plilrItems
= lens _plilrItems (\ s a -> s{_plilrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
plilrVisitorId :: Lens' PlayListItemListResponse (Maybe Text)
plilrVisitorId
= lens _plilrVisitorId
(\ s a -> s{_plilrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
plilrEventId :: Lens' PlayListItemListResponse (Maybe Text)
plilrEventId
= lens _plilrEventId (\ s a -> s{_plilrEventId = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the previous page in the result set.
plilrPrevPageToken :: Lens' PlayListItemListResponse (Maybe Text)
plilrPrevPageToken
= lens _plilrPrevPageToken
(\ s a -> s{_plilrPrevPageToken = a})
instance FromJSON PlayListItemListResponse where
parseJSON
= withObject "PlayListItemListResponse"
(\ o ->
PlayListItemListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*>
(o .:? "kind" .!= "youtube#playlistItemListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId")
<*> (o .:? "prevPageToken"))
instance ToJSON PlayListItemListResponse where
toJSON PlayListItemListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _plilrEtag,
("tokenPagination" .=) <$> _plilrTokenPagination,
("nextPageToken" .=) <$> _plilrNextPageToken,
("pageInfo" .=) <$> _plilrPageInfo,
Just ("kind" .= _plilrKind),
("items" .=) <$> _plilrItems,
("visitorId" .=) <$> _plilrVisitorId,
("eventId" .=) <$> _plilrEventId,
("prevPageToken" .=) <$> _plilrPrevPageToken])
-- | Basic details about a search result, including title, description and
-- thumbnails of the item referenced by the search result.
--
-- /See:/ 'searchResultSnippet' smart constructor.
data SearchResultSnippet =
SearchResultSnippet'
{ _srsPublishedAt :: !(Maybe DateTime')
, _srsChannelTitle :: !(Maybe Text)
, _srsChannelId :: !(Maybe Text)
, _srsThumbnails :: !(Maybe ThumbnailDetails)
, _srsTitle :: !(Maybe Text)
, _srsLiveBroadcastContent :: !(Maybe SearchResultSnippetLiveBroadcastContent)
, _srsDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SearchResultSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'srsPublishedAt'
--
-- * 'srsChannelTitle'
--
-- * 'srsChannelId'
--
-- * 'srsThumbnails'
--
-- * 'srsTitle'
--
-- * 'srsLiveBroadcastContent'
--
-- * 'srsDescription'
searchResultSnippet
:: SearchResultSnippet
searchResultSnippet =
SearchResultSnippet'
{ _srsPublishedAt = Nothing
, _srsChannelTitle = Nothing
, _srsChannelId = Nothing
, _srsThumbnails = Nothing
, _srsTitle = Nothing
, _srsLiveBroadcastContent = Nothing
, _srsDescription = Nothing
}
-- | The creation date and time of the resource that the search result
-- identifies.
srsPublishedAt :: Lens' SearchResultSnippet (Maybe UTCTime)
srsPublishedAt
= lens _srsPublishedAt
(\ s a -> s{_srsPublishedAt = a})
. mapping _DateTime
-- | The title of the channel that published the resource that the search
-- result identifies.
srsChannelTitle :: Lens' SearchResultSnippet (Maybe Text)
srsChannelTitle
= lens _srsChannelTitle
(\ s a -> s{_srsChannelTitle = a})
-- | The value that YouTube uses to uniquely identify the channel that
-- published the resource that the search result identifies.
srsChannelId :: Lens' SearchResultSnippet (Maybe Text)
srsChannelId
= lens _srsChannelId (\ s a -> s{_srsChannelId = a})
-- | A map of thumbnail images associated with the search result. For each
-- object in the map, the key is the name of the thumbnail image, and the
-- value is an object that contains other information about the thumbnail.
srsThumbnails :: Lens' SearchResultSnippet (Maybe ThumbnailDetails)
srsThumbnails
= lens _srsThumbnails
(\ s a -> s{_srsThumbnails = a})
-- | The title of the search result.
srsTitle :: Lens' SearchResultSnippet (Maybe Text)
srsTitle = lens _srsTitle (\ s a -> s{_srsTitle = a})
-- | It indicates if the resource (video or channel) has upcoming\/active
-- live broadcast content. Or it\'s \"none\" if there is not any
-- upcoming\/active live broadcasts.
srsLiveBroadcastContent :: Lens' SearchResultSnippet (Maybe SearchResultSnippetLiveBroadcastContent)
srsLiveBroadcastContent
= lens _srsLiveBroadcastContent
(\ s a -> s{_srsLiveBroadcastContent = a})
-- | A description of the search result.
srsDescription :: Lens' SearchResultSnippet (Maybe Text)
srsDescription
= lens _srsDescription
(\ s a -> s{_srsDescription = a})
instance FromJSON SearchResultSnippet where
parseJSON
= withObject "SearchResultSnippet"
(\ o ->
SearchResultSnippet' <$>
(o .:? "publishedAt") <*> (o .:? "channelTitle") <*>
(o .:? "channelId")
<*> (o .:? "thumbnails")
<*> (o .:? "title")
<*> (o .:? "liveBroadcastContent")
<*> (o .:? "description"))
instance ToJSON SearchResultSnippet where
toJSON SearchResultSnippet'{..}
= object
(catMaybes
[("publishedAt" .=) <$> _srsPublishedAt,
("channelTitle" .=) <$> _srsChannelTitle,
("channelId" .=) <$> _srsChannelId,
("thumbnails" .=) <$> _srsThumbnails,
("title" .=) <$> _srsTitle,
("liveBroadcastContent" .=) <$>
_srsLiveBroadcastContent,
("description" .=) <$> _srsDescription])
-- | An *activity* resource contains information about an action that a
-- particular channel, or user, has taken on YouTube.The actions reported
-- in activity feeds include rating a video, sharing a video, marking a
-- video as a favorite, commenting on a video, uploading a video, and so
-- forth. Each activity resource identifies the type of action, the channel
-- associated with the action, and the resource(s) associated with the
-- action, such as the video that was rated or uploaded.
--
-- /See:/ 'activity' smart constructor.
data Activity =
Activity'
{ _aEtag :: !(Maybe Text)
, _aSnippet :: !(Maybe ActivitySnippet)
, _aKind :: !Text
, _aContentDetails :: !(Maybe ActivityContentDetails)
, _aId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Activity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aEtag'
--
-- * 'aSnippet'
--
-- * 'aKind'
--
-- * 'aContentDetails'
--
-- * 'aId'
activity
:: Activity
activity =
Activity'
{ _aEtag = Nothing
, _aSnippet = Nothing
, _aKind = "youtube#activity"
, _aContentDetails = Nothing
, _aId = Nothing
}
-- | Etag of this resource
aEtag :: Lens' Activity (Maybe Text)
aEtag = lens _aEtag (\ s a -> s{_aEtag = a})
-- | The snippet object contains basic details about the activity, including
-- the activity\'s type and group ID.
aSnippet :: Lens' Activity (Maybe ActivitySnippet)
aSnippet = lens _aSnippet (\ s a -> s{_aSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#activity\".
aKind :: Lens' Activity Text
aKind = lens _aKind (\ s a -> s{_aKind = a})
-- | The contentDetails object contains information about the content
-- associated with the activity. For example, if the snippet.type value is
-- videoRated, then the contentDetails object\'s content identifies the
-- rated video.
aContentDetails :: Lens' Activity (Maybe ActivityContentDetails)
aContentDetails
= lens _aContentDetails
(\ s a -> s{_aContentDetails = a})
-- | The ID that YouTube uses to uniquely identify the activity.
aId :: Lens' Activity (Maybe Text)
aId = lens _aId (\ s a -> s{_aId = a})
instance FromJSON Activity where
parseJSON
= withObject "Activity"
(\ o ->
Activity' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#activity")
<*> (o .:? "contentDetails")
<*> (o .:? "id"))
instance ToJSON Activity where
toJSON Activity'{..}
= object
(catMaybes
[("etag" .=) <$> _aEtag,
("snippet" .=) <$> _aSnippet,
Just ("kind" .= _aKind),
("contentDetails" .=) <$> _aContentDetails,
("id" .=) <$> _aId])
-- | LINT.IfChange Describes an invideo branding.
--
-- /See:/ 'invideoBranding' smart constructor.
data InvideoBranding =
InvideoBranding'
{ _ibImageURL :: !(Maybe Text)
, _ibTargetChannelId :: !(Maybe Text)
, _ibTiming :: !(Maybe InvideoTiming)
, _ibImageBytes :: !(Maybe Bytes)
, _ibPosition :: !(Maybe InvideoPosition)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InvideoBranding' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ibImageURL'
--
-- * 'ibTargetChannelId'
--
-- * 'ibTiming'
--
-- * 'ibImageBytes'
--
-- * 'ibPosition'
invideoBranding
:: InvideoBranding
invideoBranding =
InvideoBranding'
{ _ibImageURL = Nothing
, _ibTargetChannelId = Nothing
, _ibTiming = Nothing
, _ibImageBytes = Nothing
, _ibPosition = Nothing
}
-- | The url of the uploaded image. Only used in apiary to api communication.
ibImageURL :: Lens' InvideoBranding (Maybe Text)
ibImageURL
= lens _ibImageURL (\ s a -> s{_ibImageURL = a})
-- | The channel to which this branding links. If not present it defaults to
-- the current channel.
ibTargetChannelId :: Lens' InvideoBranding (Maybe Text)
ibTargetChannelId
= lens _ibTargetChannelId
(\ s a -> s{_ibTargetChannelId = a})
-- | The temporal position within the video where watermark will be
-- displayed.
ibTiming :: Lens' InvideoBranding (Maybe InvideoTiming)
ibTiming = lens _ibTiming (\ s a -> s{_ibTiming = a})
-- | The bytes the uploaded image. Only used in api to youtube communication.
ibImageBytes :: Lens' InvideoBranding (Maybe ByteString)
ibImageBytes
= lens _ibImageBytes (\ s a -> s{_ibImageBytes = a})
. mapping _Bytes
-- | The spatial position within the video where the branding watermark will
-- be displayed.
ibPosition :: Lens' InvideoBranding (Maybe InvideoPosition)
ibPosition
= lens _ibPosition (\ s a -> s{_ibPosition = a})
instance FromJSON InvideoBranding where
parseJSON
= withObject "InvideoBranding"
(\ o ->
InvideoBranding' <$>
(o .:? "imageUrl") <*> (o .:? "targetChannelId") <*>
(o .:? "timing")
<*> (o .:? "imageBytes")
<*> (o .:? "position"))
instance ToJSON InvideoBranding where
toJSON InvideoBranding'{..}
= object
(catMaybes
[("imageUrl" .=) <$> _ibImageURL,
("targetChannelId" .=) <$> _ibTargetChannelId,
("timing" .=) <$> _ibTiming,
("imageBytes" .=) <$> _ibImageBytes,
("position" .=) <$> _ibPosition])
-- | A channel banner returned as the response to a channel_banner.insert
-- call.
--
-- /See:/ 'channelBannerResource' smart constructor.
data ChannelBannerResource =
ChannelBannerResource'
{ _cbrEtag :: !(Maybe Text)
, _cbrKind :: !Text
, _cbrURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelBannerResource' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbrEtag'
--
-- * 'cbrKind'
--
-- * 'cbrURL'
channelBannerResource
:: ChannelBannerResource
channelBannerResource =
ChannelBannerResource'
{ _cbrEtag = Nothing
, _cbrKind = "youtube#channelBannerResource"
, _cbrURL = Nothing
}
cbrEtag :: Lens' ChannelBannerResource (Maybe Text)
cbrEtag = lens _cbrEtag (\ s a -> s{_cbrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#channelBannerResource\".
cbrKind :: Lens' ChannelBannerResource Text
cbrKind = lens _cbrKind (\ s a -> s{_cbrKind = a})
-- | The URL of this banner image.
cbrURL :: Lens' ChannelBannerResource (Maybe Text)
cbrURL = lens _cbrURL (\ s a -> s{_cbrURL = a})
instance FromJSON ChannelBannerResource where
parseJSON
= withObject "ChannelBannerResource"
(\ o ->
ChannelBannerResource' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "youtube#channelBannerResource")
<*> (o .:? "url"))
instance ToJSON ChannelBannerResource where
toJSON ChannelBannerResource'{..}
= object
(catMaybes
[("etag" .=) <$> _cbrEtag, Just ("kind" .= _cbrKind),
("url" .=) <$> _cbrURL])
--
-- /See:/ 'i18nLanguageListResponse' smart constructor.
data I18nLanguageListResponse =
I18nLanguageListResponse'
{ _illrEtag :: !(Maybe Text)
, _illrKind :: !Text
, _illrItems :: !(Maybe [I18nLanguage])
, _illrVisitorId :: !(Maybe Text)
, _illrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nLanguageListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'illrEtag'
--
-- * 'illrKind'
--
-- * 'illrItems'
--
-- * 'illrVisitorId'
--
-- * 'illrEventId'
i18nLanguageListResponse
:: I18nLanguageListResponse
i18nLanguageListResponse =
I18nLanguageListResponse'
{ _illrEtag = Nothing
, _illrKind = "youtube#i18nLanguageListResponse"
, _illrItems = Nothing
, _illrVisitorId = Nothing
, _illrEventId = Nothing
}
-- | Etag of this resource.
illrEtag :: Lens' I18nLanguageListResponse (Maybe Text)
illrEtag = lens _illrEtag (\ s a -> s{_illrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#i18nLanguageListResponse\".
illrKind :: Lens' I18nLanguageListResponse Text
illrKind = lens _illrKind (\ s a -> s{_illrKind = a})
-- | A list of supported i18n languages. In this map, the i18n language ID is
-- the map key, and its value is the corresponding i18nLanguage resource.
illrItems :: Lens' I18nLanguageListResponse [I18nLanguage]
illrItems
= lens _illrItems (\ s a -> s{_illrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
illrVisitorId :: Lens' I18nLanguageListResponse (Maybe Text)
illrVisitorId
= lens _illrVisitorId
(\ s a -> s{_illrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
illrEventId :: Lens' I18nLanguageListResponse (Maybe Text)
illrEventId
= lens _illrEventId (\ s a -> s{_illrEventId = a})
instance FromJSON I18nLanguageListResponse where
parseJSON
= withObject "I18nLanguageListResponse"
(\ o ->
I18nLanguageListResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "youtube#i18nLanguageListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON I18nLanguageListResponse where
toJSON I18nLanguageListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _illrEtag,
Just ("kind" .= _illrKind),
("items" .=) <$> _illrItems,
("visitorId" .=) <$> _illrVisitorId,
("eventId" .=) <$> _illrEventId])
--
-- /See:/ 'playListPlayer' smart constructor.
newtype PlayListPlayer =
PlayListPlayer'
{ _plpEmbedHTML :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListPlayer' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plpEmbedHTML'
playListPlayer
:: PlayListPlayer
playListPlayer = PlayListPlayer' {_plpEmbedHTML = Nothing}
-- | An
-- tag that embeds a player that will play the playlist.
plpEmbedHTML :: Lens' PlayListPlayer (Maybe Text)
plpEmbedHTML
= lens _plpEmbedHTML (\ s a -> s{_plpEmbedHTML = a})
instance FromJSON PlayListPlayer where
parseJSON
= withObject "PlayListPlayer"
(\ o -> PlayListPlayer' <$> (o .:? "embedHtml"))
instance ToJSON PlayListPlayer where
toJSON PlayListPlayer'{..}
= object
(catMaybes [("embedHtml" .=) <$> _plpEmbedHTML])
-- | The id of the author\'s YouTube channel, if any.
--
-- /See:/ 'commentSnippetAuthorChannelId' smart constructor.
newtype CommentSnippetAuthorChannelId =
CommentSnippetAuthorChannelId'
{ _csaciValue :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentSnippetAuthorChannelId' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csaciValue'
commentSnippetAuthorChannelId
:: CommentSnippetAuthorChannelId
commentSnippetAuthorChannelId =
CommentSnippetAuthorChannelId' {_csaciValue = Nothing}
csaciValue :: Lens' CommentSnippetAuthorChannelId (Maybe Text)
csaciValue
= lens _csaciValue (\ s a -> s{_csaciValue = a})
instance FromJSON CommentSnippetAuthorChannelId where
parseJSON
= withObject "CommentSnippetAuthorChannelId"
(\ o ->
CommentSnippetAuthorChannelId' <$> (o .:? "value"))
instance ToJSON CommentSnippetAuthorChannelId where
toJSON CommentSnippetAuthorChannelId'{..}
= object (catMaybes [("value" .=) <$> _csaciValue])
-- | Branding properties of a YouTube channel.
--
-- /See:/ 'channelBrandingSettings' smart constructor.
data ChannelBrandingSettings =
ChannelBrandingSettings'
{ _cbsImage :: !(Maybe ImageSettings)
, _cbsHints :: !(Maybe [PropertyValue])
, _cbsChannel :: !(Maybe ChannelSettings)
, _cbsWatch :: !(Maybe WatchSettings)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelBrandingSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbsImage'
--
-- * 'cbsHints'
--
-- * 'cbsChannel'
--
-- * 'cbsWatch'
channelBrandingSettings
:: ChannelBrandingSettings
channelBrandingSettings =
ChannelBrandingSettings'
{ _cbsImage = Nothing
, _cbsHints = Nothing
, _cbsChannel = Nothing
, _cbsWatch = Nothing
}
-- | Branding properties for branding images.
cbsImage :: Lens' ChannelBrandingSettings (Maybe ImageSettings)
cbsImage = lens _cbsImage (\ s a -> s{_cbsImage = a})
-- | Additional experimental branding properties.
cbsHints :: Lens' ChannelBrandingSettings [PropertyValue]
cbsHints
= lens _cbsHints (\ s a -> s{_cbsHints = a}) .
_Default
. _Coerce
-- | Branding properties for the channel view.
cbsChannel :: Lens' ChannelBrandingSettings (Maybe ChannelSettings)
cbsChannel
= lens _cbsChannel (\ s a -> s{_cbsChannel = a})
-- | Branding properties for the watch page.
cbsWatch :: Lens' ChannelBrandingSettings (Maybe WatchSettings)
cbsWatch = lens _cbsWatch (\ s a -> s{_cbsWatch = a})
instance FromJSON ChannelBrandingSettings where
parseJSON
= withObject "ChannelBrandingSettings"
(\ o ->
ChannelBrandingSettings' <$>
(o .:? "image") <*> (o .:? "hints" .!= mempty) <*>
(o .:? "channel")
<*> (o .:? "watch"))
instance ToJSON ChannelBrandingSettings where
toJSON ChannelBrandingSettings'{..}
= object
(catMaybes
[("image" .=) <$> _cbsImage,
("hints" .=) <$> _cbsHints,
("channel" .=) <$> _cbsChannel,
("watch" .=) <$> _cbsWatch])
-- | A *comment thread* represents information that applies to a top level
-- comment and all its replies. It can also include the top level comment
-- itself and some of the replies.
--
-- /See:/ 'commentThread' smart constructor.
data CommentThread =
CommentThread'
{ _ctEtag :: !(Maybe Text)
, _ctSnippet :: !(Maybe CommentThreadSnippet)
, _ctKind :: !Text
, _ctReplies :: !(Maybe CommentThreadReplies)
, _ctId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentThread' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctEtag'
--
-- * 'ctSnippet'
--
-- * 'ctKind'
--
-- * 'ctReplies'
--
-- * 'ctId'
commentThread
:: CommentThread
commentThread =
CommentThread'
{ _ctEtag = Nothing
, _ctSnippet = Nothing
, _ctKind = "youtube#commentThread"
, _ctReplies = Nothing
, _ctId = Nothing
}
-- | Etag of this resource.
ctEtag :: Lens' CommentThread (Maybe Text)
ctEtag = lens _ctEtag (\ s a -> s{_ctEtag = a})
-- | The snippet object contains basic details about the comment thread and
-- also the top level comment.
ctSnippet :: Lens' CommentThread (Maybe CommentThreadSnippet)
ctSnippet
= lens _ctSnippet (\ s a -> s{_ctSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#commentThread\".
ctKind :: Lens' CommentThread Text
ctKind = lens _ctKind (\ s a -> s{_ctKind = a})
-- | The replies object contains a limited number of replies (if any) to the
-- top level comment found in the snippet.
ctReplies :: Lens' CommentThread (Maybe CommentThreadReplies)
ctReplies
= lens _ctReplies (\ s a -> s{_ctReplies = a})
-- | The ID that YouTube uses to uniquely identify the comment thread.
ctId :: Lens' CommentThread (Maybe Text)
ctId = lens _ctId (\ s a -> s{_ctId = a})
instance FromJSON CommentThread where
parseJSON
= withObject "CommentThread"
(\ o ->
CommentThread' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#commentThread")
<*> (o .:? "replies")
<*> (o .:? "id"))
instance ToJSON CommentThread where
toJSON CommentThread'{..}
= object
(catMaybes
[("etag" .=) <$> _ctEtag,
("snippet" .=) <$> _ctSnippet,
Just ("kind" .= _ctKind),
("replies" .=) <$> _ctReplies, ("id" .=) <$> _ctId])
-- | Playlist localization setting
--
-- /See:/ 'playListLocalization' smart constructor.
data PlayListLocalization =
PlayListLocalization'
{ _pllTitle :: !(Maybe Text)
, _pllDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListLocalization' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllTitle'
--
-- * 'pllDescription'
playListLocalization
:: PlayListLocalization
playListLocalization =
PlayListLocalization' {_pllTitle = Nothing, _pllDescription = Nothing}
-- | The localized strings for playlist\'s title.
pllTitle :: Lens' PlayListLocalization (Maybe Text)
pllTitle = lens _pllTitle (\ s a -> s{_pllTitle = a})
-- | The localized strings for playlist\'s description.
pllDescription :: Lens' PlayListLocalization (Maybe Text)
pllDescription
= lens _pllDescription
(\ s a -> s{_pllDescription = a})
instance FromJSON PlayListLocalization where
parseJSON
= withObject "PlayListLocalization"
(\ o ->
PlayListLocalization' <$>
(o .:? "title") <*> (o .:? "description"))
instance ToJSON PlayListLocalization where
toJSON PlayListLocalization'{..}
= object
(catMaybes
[("title" .=) <$> _pllTitle,
("description" .=) <$> _pllDescription])
-- | Information specific to a store on a merchandising platform linked to a
-- YouTube channel.
--
-- /See:/ 'channelToStoreLinkDetails' smart constructor.
data ChannelToStoreLinkDetails =
ChannelToStoreLinkDetails'
{ _ctsldStoreURL :: !(Maybe Text)
, _ctsldStoreName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelToStoreLinkDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctsldStoreURL'
--
-- * 'ctsldStoreName'
channelToStoreLinkDetails
:: ChannelToStoreLinkDetails
channelToStoreLinkDetails =
ChannelToStoreLinkDetails'
{_ctsldStoreURL = Nothing, _ctsldStoreName = Nothing}
-- | Landing page of the store.
ctsldStoreURL :: Lens' ChannelToStoreLinkDetails (Maybe Text)
ctsldStoreURL
= lens _ctsldStoreURL
(\ s a -> s{_ctsldStoreURL = a})
-- | Name of the store.
ctsldStoreName :: Lens' ChannelToStoreLinkDetails (Maybe Text)
ctsldStoreName
= lens _ctsldStoreName
(\ s a -> s{_ctsldStoreName = a})
instance FromJSON ChannelToStoreLinkDetails where
parseJSON
= withObject "ChannelToStoreLinkDetails"
(\ o ->
ChannelToStoreLinkDetails' <$>
(o .:? "storeUrl") <*> (o .:? "storeName"))
instance ToJSON ChannelToStoreLinkDetails where
toJSON ChannelToStoreLinkDetails'{..}
= object
(catMaybes
[("storeUrl" .=) <$> _ctsldStoreURL,
("storeName" .=) <$> _ctsldStoreName])
--
-- /See:/ 'memberSnippet' smart constructor.
data MemberSnippet =
MemberSnippet'
{ _msMemberDetails :: !(Maybe ChannelProFileDetails)
, _msCreatorChannelId :: !(Maybe Text)
, _msMembershipsDetails :: !(Maybe MembershipsDetails)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MemberSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'msMemberDetails'
--
-- * 'msCreatorChannelId'
--
-- * 'msMembershipsDetails'
memberSnippet
:: MemberSnippet
memberSnippet =
MemberSnippet'
{ _msMemberDetails = Nothing
, _msCreatorChannelId = Nothing
, _msMembershipsDetails = Nothing
}
-- | Details about the member.
msMemberDetails :: Lens' MemberSnippet (Maybe ChannelProFileDetails)
msMemberDetails
= lens _msMemberDetails
(\ s a -> s{_msMemberDetails = a})
-- | The id of the channel that\'s offering memberships.
msCreatorChannelId :: Lens' MemberSnippet (Maybe Text)
msCreatorChannelId
= lens _msCreatorChannelId
(\ s a -> s{_msCreatorChannelId = a})
-- | Details about the user\'s membership.
msMembershipsDetails :: Lens' MemberSnippet (Maybe MembershipsDetails)
msMembershipsDetails
= lens _msMembershipsDetails
(\ s a -> s{_msMembershipsDetails = a})
instance FromJSON MemberSnippet where
parseJSON
= withObject "MemberSnippet"
(\ o ->
MemberSnippet' <$>
(o .:? "memberDetails") <*>
(o .:? "creatorChannelId")
<*> (o .:? "membershipsDetails"))
instance ToJSON MemberSnippet where
toJSON MemberSnippet'{..}
= object
(catMaybes
[("memberDetails" .=) <$> _msMemberDetails,
("creatorChannelId" .=) <$> _msCreatorChannelId,
("membershipsDetails" .=) <$> _msMembershipsDetails])
--
-- /See:/ 'liveChatBanSnippet' smart constructor.
data LiveChatBanSnippet =
LiveChatBanSnippet'
{ _lcbsLiveChatId :: !(Maybe Text)
, _lcbsBannedUserDetails :: !(Maybe ChannelProFileDetails)
, _lcbsBanDurationSeconds :: !(Maybe (Textual Word64))
, _lcbsType :: !(Maybe LiveChatBanSnippetType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveChatBanSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcbsLiveChatId'
--
-- * 'lcbsBannedUserDetails'
--
-- * 'lcbsBanDurationSeconds'
--
-- * 'lcbsType'
liveChatBanSnippet
:: LiveChatBanSnippet
liveChatBanSnippet =
LiveChatBanSnippet'
{ _lcbsLiveChatId = Nothing
, _lcbsBannedUserDetails = Nothing
, _lcbsBanDurationSeconds = Nothing
, _lcbsType = Nothing
}
-- | The chat this ban is pertinent to.
lcbsLiveChatId :: Lens' LiveChatBanSnippet (Maybe Text)
lcbsLiveChatId
= lens _lcbsLiveChatId
(\ s a -> s{_lcbsLiveChatId = a})
lcbsBannedUserDetails :: Lens' LiveChatBanSnippet (Maybe ChannelProFileDetails)
lcbsBannedUserDetails
= lens _lcbsBannedUserDetails
(\ s a -> s{_lcbsBannedUserDetails = a})
-- | The duration of a ban, only filled if the ban has type TEMPORARY.
lcbsBanDurationSeconds :: Lens' LiveChatBanSnippet (Maybe Word64)
lcbsBanDurationSeconds
= lens _lcbsBanDurationSeconds
(\ s a -> s{_lcbsBanDurationSeconds = a})
. mapping _Coerce
-- | The type of ban.
lcbsType :: Lens' LiveChatBanSnippet (Maybe LiveChatBanSnippetType)
lcbsType = lens _lcbsType (\ s a -> s{_lcbsType = a})
instance FromJSON LiveChatBanSnippet where
parseJSON
= withObject "LiveChatBanSnippet"
(\ o ->
LiveChatBanSnippet' <$>
(o .:? "liveChatId") <*> (o .:? "bannedUserDetails")
<*> (o .:? "banDurationSeconds")
<*> (o .:? "type"))
instance ToJSON LiveChatBanSnippet where
toJSON LiveChatBanSnippet'{..}
= object
(catMaybes
[("liveChatId" .=) <$> _lcbsLiveChatId,
("bannedUserDetails" .=) <$> _lcbsBannedUserDetails,
("banDurationSeconds" .=) <$>
_lcbsBanDurationSeconds,
("type" .=) <$> _lcbsType])
-- | Details about the content to witch a subscription refers.
--
-- /See:/ 'subscriptionContentDetails' smart constructor.
data SubscriptionContentDetails =
SubscriptionContentDetails'
{ _scdActivityType :: !(Maybe SubscriptionContentDetailsActivityType)
, _scdTotalItemCount :: !(Maybe (Textual Word32))
, _scdNewItemCount :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SubscriptionContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scdActivityType'
--
-- * 'scdTotalItemCount'
--
-- * 'scdNewItemCount'
subscriptionContentDetails
:: SubscriptionContentDetails
subscriptionContentDetails =
SubscriptionContentDetails'
{ _scdActivityType = Nothing
, _scdTotalItemCount = Nothing
, _scdNewItemCount = Nothing
}
-- | The type of activity this subscription is for (only uploads,
-- everything).
scdActivityType :: Lens' SubscriptionContentDetails (Maybe SubscriptionContentDetailsActivityType)
scdActivityType
= lens _scdActivityType
(\ s a -> s{_scdActivityType = a})
-- | The approximate number of items that the subscription points to.
scdTotalItemCount :: Lens' SubscriptionContentDetails (Maybe Word32)
scdTotalItemCount
= lens _scdTotalItemCount
(\ s a -> s{_scdTotalItemCount = a})
. mapping _Coerce
-- | The number of new items in the subscription since its content was last
-- read.
scdNewItemCount :: Lens' SubscriptionContentDetails (Maybe Word32)
scdNewItemCount
= lens _scdNewItemCount
(\ s a -> s{_scdNewItemCount = a})
. mapping _Coerce
instance FromJSON SubscriptionContentDetails where
parseJSON
= withObject "SubscriptionContentDetails"
(\ o ->
SubscriptionContentDetails' <$>
(o .:? "activityType") <*> (o .:? "totalItemCount")
<*> (o .:? "newItemCount"))
instance ToJSON SubscriptionContentDetails where
toJSON SubscriptionContentDetails'{..}
= object
(catMaybes
[("activityType" .=) <$> _scdActivityType,
("totalItemCount" .=) <$> _scdTotalItemCount,
("newItemCount" .=) <$> _scdNewItemCount])
-- | The conversionPings object encapsulates information about conversion
-- pings that need to be respected by the channel.
--
-- /See:/ 'channelConversionPings' smart constructor.
newtype ChannelConversionPings =
ChannelConversionPings'
{ _ccpPings :: Maybe [ChannelConversionPing]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelConversionPings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccpPings'
channelConversionPings
:: ChannelConversionPings
channelConversionPings = ChannelConversionPings' {_ccpPings = Nothing}
-- | Pings that the app shall fire (authenticated by biscotti cookie). Each
-- ping has a context, in which the app must fire the ping, and a url
-- identifying the ping.
ccpPings :: Lens' ChannelConversionPings [ChannelConversionPing]
ccpPings
= lens _ccpPings (\ s a -> s{_ccpPings = a}) .
_Default
. _Coerce
instance FromJSON ChannelConversionPings where
parseJSON
= withObject "ChannelConversionPings"
(\ o ->
ChannelConversionPings' <$>
(o .:? "pings" .!= mempty))
instance ToJSON ChannelConversionPings where
toJSON ChannelConversionPings'{..}
= object (catMaybes [("pings" .=) <$> _ccpPings])
--
-- /See:/ 'localizedProperty' smart constructor.
data LocalizedProperty =
LocalizedProperty'
{ _lpDefault :: !(Maybe Text)
, _lpLocalized :: !(Maybe [LocalizedString])
, _lpDefaultLanguage :: !(Maybe LanguageTag)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LocalizedProperty' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lpDefault'
--
-- * 'lpLocalized'
--
-- * 'lpDefaultLanguage'
localizedProperty
:: LocalizedProperty
localizedProperty =
LocalizedProperty'
{_lpDefault = Nothing, _lpLocalized = Nothing, _lpDefaultLanguage = Nothing}
lpDefault :: Lens' LocalizedProperty (Maybe Text)
lpDefault
= lens _lpDefault (\ s a -> s{_lpDefault = a})
lpLocalized :: Lens' LocalizedProperty [LocalizedString]
lpLocalized
= lens _lpLocalized (\ s a -> s{_lpLocalized = a}) .
_Default
. _Coerce
-- | The language of the default property.
lpDefaultLanguage :: Lens' LocalizedProperty (Maybe LanguageTag)
lpDefaultLanguage
= lens _lpDefaultLanguage
(\ s a -> s{_lpDefaultLanguage = a})
instance FromJSON LocalizedProperty where
parseJSON
= withObject "LocalizedProperty"
(\ o ->
LocalizedProperty' <$>
(o .:? "default") <*> (o .:? "localized" .!= mempty)
<*> (o .:? "defaultLanguage"))
instance ToJSON LocalizedProperty where
toJSON LocalizedProperty'{..}
= object
(catMaybes
[("default" .=) <$> _lpDefault,
("localized" .=) <$> _lpLocalized,
("defaultLanguage" .=) <$> _lpDefaultLanguage])
-- | Basic information about a third party account link, including its type
-- and type-specific information.
--
-- /See:/ 'thirdPartyLinkSnippet' smart constructor.
data ThirdPartyLinkSnippet =
ThirdPartyLinkSnippet'
{ _tplsChannelToStoreLink :: !(Maybe ChannelToStoreLinkDetails)
, _tplsType :: !(Maybe ThirdPartyLinkSnippetType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ThirdPartyLinkSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tplsChannelToStoreLink'
--
-- * 'tplsType'
thirdPartyLinkSnippet
:: ThirdPartyLinkSnippet
thirdPartyLinkSnippet =
ThirdPartyLinkSnippet'
{_tplsChannelToStoreLink = Nothing, _tplsType = Nothing}
-- | Information specific to a link between a channel and a store on a
-- merchandising platform.
tplsChannelToStoreLink :: Lens' ThirdPartyLinkSnippet (Maybe ChannelToStoreLinkDetails)
tplsChannelToStoreLink
= lens _tplsChannelToStoreLink
(\ s a -> s{_tplsChannelToStoreLink = a})
-- | Type of the link named after the entities that are being linked.
tplsType :: Lens' ThirdPartyLinkSnippet (Maybe ThirdPartyLinkSnippetType)
tplsType = lens _tplsType (\ s a -> s{_tplsType = a})
instance FromJSON ThirdPartyLinkSnippet where
parseJSON
= withObject "ThirdPartyLinkSnippet"
(\ o ->
ThirdPartyLinkSnippet' <$>
(o .:? "channelToStoreLink") <*> (o .:? "type"))
instance ToJSON ThirdPartyLinkSnippet where
toJSON ThirdPartyLinkSnippet'{..}
= object
(catMaybes
[("channelToStoreLink" .=) <$>
_tplsChannelToStoreLink,
("type" .=) <$> _tplsType])
-- | A *member* resource represents a member for a YouTube channel. A member
-- provides recurring monetary support to a creator and receives special
-- benefits.
--
-- /See:/ 'member' smart constructor.
data Member =
Member'
{ _mEtag :: !(Maybe Text)
, _mSnippet :: !(Maybe MemberSnippet)
, _mKind :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Member' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mEtag'
--
-- * 'mSnippet'
--
-- * 'mKind'
member
:: Member
member =
Member' {_mEtag = Nothing, _mSnippet = Nothing, _mKind = "youtube#member"}
-- | Etag of this resource.
mEtag :: Lens' Member (Maybe Text)
mEtag = lens _mEtag (\ s a -> s{_mEtag = a})
-- | The snippet object contains basic details about the member.
mSnippet :: Lens' Member (Maybe MemberSnippet)
mSnippet = lens _mSnippet (\ s a -> s{_mSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#member\".
mKind :: Lens' Member Text
mKind = lens _mKind (\ s a -> s{_mKind = a})
instance FromJSON Member where
parseJSON
= withObject "Member"
(\ o ->
Member' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#member"))
instance ToJSON Member where
toJSON Member'{..}
= object
(catMaybes
[("etag" .=) <$> _mEtag,
("snippet" .=) <$> _mSnippet,
Just ("kind" .= _mKind)])
-- | Channel localization setting
--
-- /See:/ 'channelLocalization' smart constructor.
data ChannelLocalization =
ChannelLocalization'
{ _clTitle :: !(Maybe Text)
, _clDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelLocalization' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clTitle'
--
-- * 'clDescription'
channelLocalization
:: ChannelLocalization
channelLocalization =
ChannelLocalization' {_clTitle = Nothing, _clDescription = Nothing}
-- | The localized strings for channel\'s title.
clTitle :: Lens' ChannelLocalization (Maybe Text)
clTitle = lens _clTitle (\ s a -> s{_clTitle = a})
-- | The localized strings for channel\'s description.
clDescription :: Lens' ChannelLocalization (Maybe Text)
clDescription
= lens _clDescription
(\ s a -> s{_clDescription = a})
instance FromJSON ChannelLocalization where
parseJSON
= withObject "ChannelLocalization"
(\ o ->
ChannelLocalization' <$>
(o .:? "title") <*> (o .:? "description"))
instance ToJSON ChannelLocalization where
toJSON ChannelLocalization'{..}
= object
(catMaybes
[("title" .=) <$> _clTitle,
("description" .=) <$> _clDescription])
--
-- /See:/ 'playListItemContentDetails' smart constructor.
data PlayListItemContentDetails =
PlayListItemContentDetails'
{ _plicdStartAt :: !(Maybe Text)
, _plicdNote :: !(Maybe Text)
, _plicdVideoPublishedAt :: !(Maybe DateTime')
, _plicdVideoId :: !(Maybe Text)
, _plicdEndAt :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListItemContentDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plicdStartAt'
--
-- * 'plicdNote'
--
-- * 'plicdVideoPublishedAt'
--
-- * 'plicdVideoId'
--
-- * 'plicdEndAt'
playListItemContentDetails
:: PlayListItemContentDetails
playListItemContentDetails =
PlayListItemContentDetails'
{ _plicdStartAt = Nothing
, _plicdNote = Nothing
, _plicdVideoPublishedAt = Nothing
, _plicdVideoId = Nothing
, _plicdEndAt = Nothing
}
-- | The time, measured in seconds from the start of the video, when the
-- video should start playing. (The playlist owner can specify the times
-- when the video should start and stop playing when the video is played in
-- the context of the playlist.) The default value is 0.
plicdStartAt :: Lens' PlayListItemContentDetails (Maybe Text)
plicdStartAt
= lens _plicdStartAt (\ s a -> s{_plicdStartAt = a})
-- | A user-generated note for this item.
plicdNote :: Lens' PlayListItemContentDetails (Maybe Text)
plicdNote
= lens _plicdNote (\ s a -> s{_plicdNote = a})
-- | The date and time that the video was published to YouTube.
plicdVideoPublishedAt :: Lens' PlayListItemContentDetails (Maybe UTCTime)
plicdVideoPublishedAt
= lens _plicdVideoPublishedAt
(\ s a -> s{_plicdVideoPublishedAt = a})
. mapping _DateTime
-- | The ID that YouTube uses to uniquely identify a video. To retrieve the
-- video resource, set the id query parameter to this value in your API
-- request.
plicdVideoId :: Lens' PlayListItemContentDetails (Maybe Text)
plicdVideoId
= lens _plicdVideoId (\ s a -> s{_plicdVideoId = a})
-- | The time, measured in seconds from the start of the video, when the
-- video should stop playing. (The playlist owner can specify the times
-- when the video should start and stop playing when the video is played in
-- the context of the playlist.) By default, assume that the video.endTime
-- is the end of the video.
plicdEndAt :: Lens' PlayListItemContentDetails (Maybe Text)
plicdEndAt
= lens _plicdEndAt (\ s a -> s{_plicdEndAt = a})
instance FromJSON PlayListItemContentDetails where
parseJSON
= withObject "PlayListItemContentDetails"
(\ o ->
PlayListItemContentDetails' <$>
(o .:? "startAt") <*> (o .:? "note") <*>
(o .:? "videoPublishedAt")
<*> (o .:? "videoId")
<*> (o .:? "endAt"))
instance ToJSON PlayListItemContentDetails where
toJSON PlayListItemContentDetails'{..}
= object
(catMaybes
[("startAt" .=) <$> _plicdStartAt,
("note" .=) <$> _plicdNote,
("videoPublishedAt" .=) <$> _plicdVideoPublishedAt,
("videoId" .=) <$> _plicdVideoId,
("endAt" .=) <$> _plicdEndAt])
--
-- /See:/ 'videoAgeGating' smart constructor.
data VideoAgeGating =
VideoAgeGating'
{ _vagAlcoholContent :: !(Maybe Bool)
, _vagRestricted :: !(Maybe Bool)
, _vagVideoGameRating :: !(Maybe VideoAgeGatingVideoGameRating)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoAgeGating' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vagAlcoholContent'
--
-- * 'vagRestricted'
--
-- * 'vagVideoGameRating'
videoAgeGating
:: VideoAgeGating
videoAgeGating =
VideoAgeGating'
{ _vagAlcoholContent = Nothing
, _vagRestricted = Nothing
, _vagVideoGameRating = Nothing
}
-- | Indicates whether or not the video has alcoholic beverage content. Only
-- users of legal purchasing age in a particular country, as identified by
-- ICAP, can view the content.
vagAlcoholContent :: Lens' VideoAgeGating (Maybe Bool)
vagAlcoholContent
= lens _vagAlcoholContent
(\ s a -> s{_vagAlcoholContent = a})
-- | Age-restricted trailers. For redband trailers and adult-rated
-- video-games. Only users aged 18+ can view the content. The the field is
-- true the content is restricted to viewers aged 18+. Otherwise The field
-- won\'t be present.
vagRestricted :: Lens' VideoAgeGating (Maybe Bool)
vagRestricted
= lens _vagRestricted
(\ s a -> s{_vagRestricted = a})
-- | Video game rating, if any.
vagVideoGameRating :: Lens' VideoAgeGating (Maybe VideoAgeGatingVideoGameRating)
vagVideoGameRating
= lens _vagVideoGameRating
(\ s a -> s{_vagVideoGameRating = a})
instance FromJSON VideoAgeGating where
parseJSON
= withObject "VideoAgeGating"
(\ o ->
VideoAgeGating' <$>
(o .:? "alcoholContent") <*> (o .:? "restricted") <*>
(o .:? "videoGameRating"))
instance ToJSON VideoAgeGating where
toJSON VideoAgeGating'{..}
= object
(catMaybes
[("alcoholContent" .=) <$> _vagAlcoholContent,
("restricted" .=) <$> _vagRestricted,
("videoGameRating" .=) <$> _vagVideoGameRating])
--
-- /See:/ 'languageTag' smart constructor.
newtype LanguageTag =
LanguageTag'
{ _ltValue :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LanguageTag' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltValue'
languageTag
:: LanguageTag
languageTag = LanguageTag' {_ltValue = Nothing}
ltValue :: Lens' LanguageTag (Maybe Text)
ltValue = lens _ltValue (\ s a -> s{_ltValue = a})
instance FromJSON LanguageTag where
parseJSON
= withObject "LanguageTag"
(\ o -> LanguageTag' <$> (o .:? "value"))
instance ToJSON LanguageTag where
toJSON LanguageTag'{..}
= object (catMaybes [("value" .=) <$> _ltValue])
-- | Information about a video stream.
--
-- /See:/ 'videoFileDetailsVideoStream' smart constructor.
data VideoFileDetailsVideoStream =
VideoFileDetailsVideoStream'
{ _vfdvsHeightPixels :: !(Maybe (Textual Word32))
, _vfdvsBitrateBps :: !(Maybe (Textual Word64))
, _vfdvsVendor :: !(Maybe Text)
, _vfdvsRotation :: !(Maybe VideoFileDetailsVideoStreamRotation)
, _vfdvsFrameRateFps :: !(Maybe (Textual Double))
, _vfdvsCodec :: !(Maybe Text)
, _vfdvsAspectRatio :: !(Maybe (Textual Double))
, _vfdvsWidthPixels :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoFileDetailsVideoStream' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vfdvsHeightPixels'
--
-- * 'vfdvsBitrateBps'
--
-- * 'vfdvsVendor'
--
-- * 'vfdvsRotation'
--
-- * 'vfdvsFrameRateFps'
--
-- * 'vfdvsCodec'
--
-- * 'vfdvsAspectRatio'
--
-- * 'vfdvsWidthPixels'
videoFileDetailsVideoStream
:: VideoFileDetailsVideoStream
videoFileDetailsVideoStream =
VideoFileDetailsVideoStream'
{ _vfdvsHeightPixels = Nothing
, _vfdvsBitrateBps = Nothing
, _vfdvsVendor = Nothing
, _vfdvsRotation = Nothing
, _vfdvsFrameRateFps = Nothing
, _vfdvsCodec = Nothing
, _vfdvsAspectRatio = Nothing
, _vfdvsWidthPixels = Nothing
}
-- | The encoded video content\'s height in pixels.
vfdvsHeightPixels :: Lens' VideoFileDetailsVideoStream (Maybe Word32)
vfdvsHeightPixels
= lens _vfdvsHeightPixels
(\ s a -> s{_vfdvsHeightPixels = a})
. mapping _Coerce
-- | The video stream\'s bitrate, in bits per second.
vfdvsBitrateBps :: Lens' VideoFileDetailsVideoStream (Maybe Word64)
vfdvsBitrateBps
= lens _vfdvsBitrateBps
(\ s a -> s{_vfdvsBitrateBps = a})
. mapping _Coerce
-- | A value that uniquely identifies a video vendor. Typically, the value is
-- a four-letter vendor code.
vfdvsVendor :: Lens' VideoFileDetailsVideoStream (Maybe Text)
vfdvsVendor
= lens _vfdvsVendor (\ s a -> s{_vfdvsVendor = a})
-- | The amount that YouTube needs to rotate the original source content to
-- properly display the video.
vfdvsRotation :: Lens' VideoFileDetailsVideoStream (Maybe VideoFileDetailsVideoStreamRotation)
vfdvsRotation
= lens _vfdvsRotation
(\ s a -> s{_vfdvsRotation = a})
-- | The video stream\'s frame rate, in frames per second.
vfdvsFrameRateFps :: Lens' VideoFileDetailsVideoStream (Maybe Double)
vfdvsFrameRateFps
= lens _vfdvsFrameRateFps
(\ s a -> s{_vfdvsFrameRateFps = a})
. mapping _Coerce
-- | The video codec that the stream uses.
vfdvsCodec :: Lens' VideoFileDetailsVideoStream (Maybe Text)
vfdvsCodec
= lens _vfdvsCodec (\ s a -> s{_vfdvsCodec = a})
-- | The video content\'s display aspect ratio, which specifies the aspect
-- ratio in which the video should be displayed.
vfdvsAspectRatio :: Lens' VideoFileDetailsVideoStream (Maybe Double)
vfdvsAspectRatio
= lens _vfdvsAspectRatio
(\ s a -> s{_vfdvsAspectRatio = a})
. mapping _Coerce
-- | The encoded video content\'s width in pixels. You can calculate the
-- video\'s encoding aspect ratio as width_pixels \/ height_pixels.
vfdvsWidthPixels :: Lens' VideoFileDetailsVideoStream (Maybe Word32)
vfdvsWidthPixels
= lens _vfdvsWidthPixels
(\ s a -> s{_vfdvsWidthPixels = a})
. mapping _Coerce
instance FromJSON VideoFileDetailsVideoStream where
parseJSON
= withObject "VideoFileDetailsVideoStream"
(\ o ->
VideoFileDetailsVideoStream' <$>
(o .:? "heightPixels") <*> (o .:? "bitrateBps") <*>
(o .:? "vendor")
<*> (o .:? "rotation")
<*> (o .:? "frameRateFps")
<*> (o .:? "codec")
<*> (o .:? "aspectRatio")
<*> (o .:? "widthPixels"))
instance ToJSON VideoFileDetailsVideoStream where
toJSON VideoFileDetailsVideoStream'{..}
= object
(catMaybes
[("heightPixels" .=) <$> _vfdvsHeightPixels,
("bitrateBps" .=) <$> _vfdvsBitrateBps,
("vendor" .=) <$> _vfdvsVendor,
("rotation" .=) <$> _vfdvsRotation,
("frameRateFps" .=) <$> _vfdvsFrameRateFps,
("codec" .=) <$> _vfdvsCodec,
("aspectRatio" .=) <$> _vfdvsAspectRatio,
("widthPixels" .=) <$> _vfdvsWidthPixels])
-- | Pings that the app shall fire (authenticated by biscotti cookie). Each
-- ping has a context, in which the app must fire the ping, and a url
-- identifying the ping.
--
-- /See:/ 'channelConversionPing' smart constructor.
data ChannelConversionPing =
ChannelConversionPing'
{ _ccpContext :: !(Maybe ChannelConversionPingContext)
, _ccpConversionURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelConversionPing' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccpContext'
--
-- * 'ccpConversionURL'
channelConversionPing
:: ChannelConversionPing
channelConversionPing =
ChannelConversionPing' {_ccpContext = Nothing, _ccpConversionURL = Nothing}
-- | Defines the context of the ping.
ccpContext :: Lens' ChannelConversionPing (Maybe ChannelConversionPingContext)
ccpContext
= lens _ccpContext (\ s a -> s{_ccpContext = a})
-- | The url (without the schema) that the player shall send the ping to.
-- It\'s at caller\'s descretion to decide which schema to use (http vs
-- https) Example of a returned url:
-- \/\/googleads.g.doubleclick.net\/pagead\/
-- viewthroughconversion\/962985656\/?data=path%3DtHe_path%3Btype%3D
-- cview%3Butuid%3DGISQtTNGYqaYl4sKxoVvKA&labe=default The caller must
-- append biscotti authentication (ms param in case of mobile, for example)
-- to this ping.
ccpConversionURL :: Lens' ChannelConversionPing (Maybe Text)
ccpConversionURL
= lens _ccpConversionURL
(\ s a -> s{_ccpConversionURL = a})
instance FromJSON ChannelConversionPing where
parseJSON
= withObject "ChannelConversionPing"
(\ o ->
ChannelConversionPing' <$>
(o .:? "context") <*> (o .:? "conversionUrl"))
instance ToJSON ChannelConversionPing where
toJSON ChannelConversionPing'{..}
= object
(catMaybes
[("context" .=) <$> _ccpContext,
("conversionUrl" .=) <$> _ccpConversionURL])
-- | A *playlistItem* resource identifies another resource, such as a video,
-- that is included in a playlist. In addition, the playlistItem resource
-- contains details about the included resource that pertain specifically
-- to how that resource is used in that playlist. YouTube uses playlists to
-- identify special collections of videos for a channel, such as: -
-- uploaded videos - favorite videos - positively rated (liked) videos -
-- watch history - watch later To be more specific, these lists are
-- associated with a channel, which is a collection of a person, group, or
-- company\'s videos, playlists, and other YouTube information. You can
-- retrieve the playlist IDs for each of these lists from the channel
-- resource for a given channel. You can then use the playlistItems.list
-- method to retrieve any of those lists. You can also add or remove items
-- from those lists by calling the playlistItems.insert and
-- playlistItems.delete methods. For example, if a user gives a positive
-- rating to a video, you would insert that video into the liked videos
-- playlist for that user\'s channel.
--
-- /See:/ 'playListItem' smart constructor.
data PlayListItem =
PlayListItem'
{ _pliStatus :: !(Maybe PlayListItemStatus)
, _pliEtag :: !(Maybe Text)
, _pliSnippet :: !(Maybe PlayListItemSnippet)
, _pliKind :: !Text
, _pliContentDetails :: !(Maybe PlayListItemContentDetails)
, _pliId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pliStatus'
--
-- * 'pliEtag'
--
-- * 'pliSnippet'
--
-- * 'pliKind'
--
-- * 'pliContentDetails'
--
-- * 'pliId'
playListItem
:: PlayListItem
playListItem =
PlayListItem'
{ _pliStatus = Nothing
, _pliEtag = Nothing
, _pliSnippet = Nothing
, _pliKind = "youtube#playlistItem"
, _pliContentDetails = Nothing
, _pliId = Nothing
}
-- | The status object contains information about the playlist item\'s
-- privacy status.
pliStatus :: Lens' PlayListItem (Maybe PlayListItemStatus)
pliStatus
= lens _pliStatus (\ s a -> s{_pliStatus = a})
-- | Etag of this resource.
pliEtag :: Lens' PlayListItem (Maybe Text)
pliEtag = lens _pliEtag (\ s a -> s{_pliEtag = a})
-- | The snippet object contains basic details about the playlist item, such
-- as its title and position in the playlist.
pliSnippet :: Lens' PlayListItem (Maybe PlayListItemSnippet)
pliSnippet
= lens _pliSnippet (\ s a -> s{_pliSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#playlistItem\".
pliKind :: Lens' PlayListItem Text
pliKind = lens _pliKind (\ s a -> s{_pliKind = a})
-- | The contentDetails object is included in the resource if the included
-- item is a YouTube video. The object contains additional information
-- about the video.
pliContentDetails :: Lens' PlayListItem (Maybe PlayListItemContentDetails)
pliContentDetails
= lens _pliContentDetails
(\ s a -> s{_pliContentDetails = a})
-- | The ID that YouTube uses to uniquely identify the playlist item.
pliId :: Lens' PlayListItem (Maybe Text)
pliId = lens _pliId (\ s a -> s{_pliId = a})
instance FromJSON PlayListItem where
parseJSON
= withObject "PlayListItem"
(\ o ->
PlayListItem' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#playlistItem")
<*> (o .:? "contentDetails")
<*> (o .:? "id"))
instance ToJSON PlayListItem where
toJSON PlayListItem'{..}
= object
(catMaybes
[("status" .=) <$> _pliStatus,
("etag" .=) <$> _pliEtag,
("snippet" .=) <$> _pliSnippet,
Just ("kind" .= _pliKind),
("contentDetails" .=) <$> _pliContentDetails,
("id" .=) <$> _pliId])
--
-- /See:/ 'membershipsDetails' smart constructor.
data MembershipsDetails =
MembershipsDetails'
{ _mdHighestAccessibleLevel :: !(Maybe Text)
, _mdMembershipsDurationAtLevels :: !(Maybe [MembershipsDurationAtLevel])
, _mdMembershipsDuration :: !(Maybe MembershipsDuration)
, _mdAccessibleLevels :: !(Maybe [Text])
, _mdHighestAccessibleLevelDisplayName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MembershipsDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdHighestAccessibleLevel'
--
-- * 'mdMembershipsDurationAtLevels'
--
-- * 'mdMembershipsDuration'
--
-- * 'mdAccessibleLevels'
--
-- * 'mdHighestAccessibleLevelDisplayName'
membershipsDetails
:: MembershipsDetails
membershipsDetails =
MembershipsDetails'
{ _mdHighestAccessibleLevel = Nothing
, _mdMembershipsDurationAtLevels = Nothing
, _mdMembershipsDuration = Nothing
, _mdAccessibleLevels = Nothing
, _mdHighestAccessibleLevelDisplayName = Nothing
}
-- | Id of the highest level that the user has access to at the moment.
mdHighestAccessibleLevel :: Lens' MembershipsDetails (Maybe Text)
mdHighestAccessibleLevel
= lens _mdHighestAccessibleLevel
(\ s a -> s{_mdHighestAccessibleLevel = a})
-- | Data about memberships duration on particular pricing levels.
mdMembershipsDurationAtLevels :: Lens' MembershipsDetails [MembershipsDurationAtLevel]
mdMembershipsDurationAtLevels
= lens _mdMembershipsDurationAtLevels
(\ s a -> s{_mdMembershipsDurationAtLevels = a})
. _Default
. _Coerce
-- | Data about memberships duration without taking into consideration
-- pricing levels.
mdMembershipsDuration :: Lens' MembershipsDetails (Maybe MembershipsDuration)
mdMembershipsDuration
= lens _mdMembershipsDuration
(\ s a -> s{_mdMembershipsDuration = a})
-- | Ids of all levels that the user has access to. This includes the
-- currently active level and all other levels that are included because of
-- a higher purchase.
mdAccessibleLevels :: Lens' MembershipsDetails [Text]
mdAccessibleLevels
= lens _mdAccessibleLevels
(\ s a -> s{_mdAccessibleLevels = a})
. _Default
. _Coerce
-- | Display name for the highest level that the user has access to at the
-- moment.
mdHighestAccessibleLevelDisplayName :: Lens' MembershipsDetails (Maybe Text)
mdHighestAccessibleLevelDisplayName
= lens _mdHighestAccessibleLevelDisplayName
(\ s a ->
s{_mdHighestAccessibleLevelDisplayName = a})
instance FromJSON MembershipsDetails where
parseJSON
= withObject "MembershipsDetails"
(\ o ->
MembershipsDetails' <$>
(o .:? "highestAccessibleLevel") <*>
(o .:? "membershipsDurationAtLevels" .!= mempty)
<*> (o .:? "membershipsDuration")
<*> (o .:? "accessibleLevels" .!= mempty)
<*> (o .:? "highestAccessibleLevelDisplayName"))
instance ToJSON MembershipsDetails where
toJSON MembershipsDetails'{..}
= object
(catMaybes
[("highestAccessibleLevel" .=) <$>
_mdHighestAccessibleLevel,
("membershipsDurationAtLevels" .=) <$>
_mdMembershipsDurationAtLevels,
("membershipsDuration" .=) <$>
_mdMembershipsDuration,
("accessibleLevels" .=) <$> _mdAccessibleLevels,
("highestAccessibleLevelDisplayName" .=) <$>
_mdHighestAccessibleLevelDisplayName])
-- | Basic details about a caption track, such as its language and name.
--
-- /See:/ 'captionSnippet' smart constructor.
data CaptionSnippet =
CaptionSnippet'
{ _csFailureReason :: !(Maybe CaptionSnippetFailureReason)
, _csStatus :: !(Maybe CaptionSnippetStatus)
, _csLastUpdated :: !(Maybe DateTime')
, _csTrackKind :: !(Maybe CaptionSnippetTrackKind)
, _csIsDraft :: !(Maybe Bool)
, _csIsCC :: !(Maybe Bool)
, _csVideoId :: !(Maybe Text)
, _csName :: !(Maybe Text)
, _csIsLarge :: !(Maybe Bool)
, _csLanguage :: !(Maybe Text)
, _csIsAutoSynced :: !(Maybe Bool)
, _csIsEasyReader :: !(Maybe Bool)
, _csAudioTrackType :: !(Maybe CaptionSnippetAudioTrackType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CaptionSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csFailureReason'
--
-- * 'csStatus'
--
-- * 'csLastUpdated'
--
-- * 'csTrackKind'
--
-- * 'csIsDraft'
--
-- * 'csIsCC'
--
-- * 'csVideoId'
--
-- * 'csName'
--
-- * 'csIsLarge'
--
-- * 'csLanguage'
--
-- * 'csIsAutoSynced'
--
-- * 'csIsEasyReader'
--
-- * 'csAudioTrackType'
captionSnippet
:: CaptionSnippet
captionSnippet =
CaptionSnippet'
{ _csFailureReason = Nothing
, _csStatus = Nothing
, _csLastUpdated = Nothing
, _csTrackKind = Nothing
, _csIsDraft = Nothing
, _csIsCC = Nothing
, _csVideoId = Nothing
, _csName = Nothing
, _csIsLarge = Nothing
, _csLanguage = Nothing
, _csIsAutoSynced = Nothing
, _csIsEasyReader = Nothing
, _csAudioTrackType = Nothing
}
-- | The reason that YouTube failed to process the caption track. This
-- property is only present if the state property\'s value is failed.
csFailureReason :: Lens' CaptionSnippet (Maybe CaptionSnippetFailureReason)
csFailureReason
= lens _csFailureReason
(\ s a -> s{_csFailureReason = a})
-- | The caption track\'s status.
csStatus :: Lens' CaptionSnippet (Maybe CaptionSnippetStatus)
csStatus = lens _csStatus (\ s a -> s{_csStatus = a})
-- | The date and time when the caption track was last updated.
csLastUpdated :: Lens' CaptionSnippet (Maybe UTCTime)
csLastUpdated
= lens _csLastUpdated
(\ s a -> s{_csLastUpdated = a})
. mapping _DateTime
-- | The caption track\'s type.
csTrackKind :: Lens' CaptionSnippet (Maybe CaptionSnippetTrackKind)
csTrackKind
= lens _csTrackKind (\ s a -> s{_csTrackKind = a})
-- | Indicates whether the caption track is a draft. If the value is true,
-- then the track is not publicly visible. The default value is false.
-- \'mutable youtube.captions.insert youtube.captions.update
csIsDraft :: Lens' CaptionSnippet (Maybe Bool)
csIsDraft
= lens _csIsDraft (\ s a -> s{_csIsDraft = a})
-- | Indicates whether the track contains closed captions for the deaf and
-- hard of hearing. The default value is false.
csIsCC :: Lens' CaptionSnippet (Maybe Bool)
csIsCC = lens _csIsCC (\ s a -> s{_csIsCC = a})
-- | The ID that YouTube uses to uniquely identify the video associated with
-- the caption track. \'mutable youtube.captions.insert
csVideoId :: Lens' CaptionSnippet (Maybe Text)
csVideoId
= lens _csVideoId (\ s a -> s{_csVideoId = a})
-- | The name of the caption track. The name is intended to be visible to the
-- user as an option during playback.
csName :: Lens' CaptionSnippet (Maybe Text)
csName = lens _csName (\ s a -> s{_csName = a})
-- | Indicates whether the caption track uses large text for the
-- vision-impaired. The default value is false.
csIsLarge :: Lens' CaptionSnippet (Maybe Bool)
csIsLarge
= lens _csIsLarge (\ s a -> s{_csIsLarge = a})
-- | The language of the caption track. The property value is a BCP-47
-- language tag.
csLanguage :: Lens' CaptionSnippet (Maybe Text)
csLanguage
= lens _csLanguage (\ s a -> s{_csLanguage = a})
-- | Indicates whether YouTube synchronized the caption track to the audio
-- track in the video. The value will be true if a sync was explicitly
-- requested when the caption track was uploaded. For example, when calling
-- the captions.insert or captions.update methods, you can set the sync
-- parameter to true to instruct YouTube to sync the uploaded track to the
-- video. If the value is false, YouTube uses the time codes in the
-- uploaded caption track to determine when to display captions.
csIsAutoSynced :: Lens' CaptionSnippet (Maybe Bool)
csIsAutoSynced
= lens _csIsAutoSynced
(\ s a -> s{_csIsAutoSynced = a})
-- | Indicates whether caption track is formatted for \"easy reader,\"
-- meaning it is at a third-grade level for language learners. The default
-- value is false.
csIsEasyReader :: Lens' CaptionSnippet (Maybe Bool)
csIsEasyReader
= lens _csIsEasyReader
(\ s a -> s{_csIsEasyReader = a})
-- | The type of audio track associated with the caption track.
csAudioTrackType :: Lens' CaptionSnippet (Maybe CaptionSnippetAudioTrackType)
csAudioTrackType
= lens _csAudioTrackType
(\ s a -> s{_csAudioTrackType = a})
instance FromJSON CaptionSnippet where
parseJSON
= withObject "CaptionSnippet"
(\ o ->
CaptionSnippet' <$>
(o .:? "failureReason") <*> (o .:? "status") <*>
(o .:? "lastUpdated")
<*> (o .:? "trackKind")
<*> (o .:? "isDraft")
<*> (o .:? "isCC")
<*> (o .:? "videoId")
<*> (o .:? "name")
<*> (o .:? "isLarge")
<*> (o .:? "language")
<*> (o .:? "isAutoSynced")
<*> (o .:? "isEasyReader")
<*> (o .:? "audioTrackType"))
instance ToJSON CaptionSnippet where
toJSON CaptionSnippet'{..}
= object
(catMaybes
[("failureReason" .=) <$> _csFailureReason,
("status" .=) <$> _csStatus,
("lastUpdated" .=) <$> _csLastUpdated,
("trackKind" .=) <$> _csTrackKind,
("isDraft" .=) <$> _csIsDraft,
("isCC" .=) <$> _csIsCC,
("videoId" .=) <$> _csVideoId,
("name" .=) <$> _csName,
("isLarge" .=) <$> _csIsLarge,
("language" .=) <$> _csLanguage,
("isAutoSynced" .=) <$> _csIsAutoSynced,
("isEasyReader" .=) <$> _csIsEasyReader,
("audioTrackType" .=) <$> _csAudioTrackType])
-- | A *comment* represents a single YouTube comment.
--
-- /See:/ 'comment' smart constructor.
data Comment =
Comment'
{ _ccEtag :: !(Maybe Text)
, _ccSnippet :: !(Maybe CommentSnippet)
, _ccKind :: !Text
, _ccId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Comment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccEtag'
--
-- * 'ccSnippet'
--
-- * 'ccKind'
--
-- * 'ccId'
comment
:: Comment
comment =
Comment'
{ _ccEtag = Nothing
, _ccSnippet = Nothing
, _ccKind = "youtube#comment"
, _ccId = Nothing
}
-- | Etag of this resource.
ccEtag :: Lens' Comment (Maybe Text)
ccEtag = lens _ccEtag (\ s a -> s{_ccEtag = a})
-- | The snippet object contains basic details about the comment.
ccSnippet :: Lens' Comment (Maybe CommentSnippet)
ccSnippet
= lens _ccSnippet (\ s a -> s{_ccSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#comment\".
ccKind :: Lens' Comment Text
ccKind = lens _ccKind (\ s a -> s{_ccKind = a})
-- | The ID that YouTube uses to uniquely identify the comment.
ccId :: Lens' Comment (Maybe Text)
ccId = lens _ccId (\ s a -> s{_ccId = a})
instance FromJSON Comment where
parseJSON
= withObject "Comment"
(\ o ->
Comment' <$>
(o .:? "etag") <*> (o .:? "snippet") <*>
(o .:? "kind" .!= "youtube#comment")
<*> (o .:? "id"))
instance ToJSON Comment where
toJSON Comment'{..}
= object
(catMaybes
[("etag" .=) <$> _ccEtag,
("snippet" .=) <$> _ccSnippet,
Just ("kind" .= _ccKind), ("id" .=) <$> _ccId])
-- | Basic details about an i18n region, such as region code and
-- human-readable name.
--
-- /See:/ 'i18nRegionSnippet' smart constructor.
data I18nRegionSnippet =
I18nRegionSnippet'
{ _irsName :: !(Maybe Text)
, _irsGl :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nRegionSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'irsName'
--
-- * 'irsGl'
i18nRegionSnippet
:: I18nRegionSnippet
i18nRegionSnippet = I18nRegionSnippet' {_irsName = Nothing, _irsGl = Nothing}
-- | The human-readable name of the region.
irsName :: Lens' I18nRegionSnippet (Maybe Text)
irsName = lens _irsName (\ s a -> s{_irsName = a})
-- | The region code as a 2-letter ISO country code.
irsGl :: Lens' I18nRegionSnippet (Maybe Text)
irsGl = lens _irsGl (\ s a -> s{_irsGl = a})
instance FromJSON I18nRegionSnippet where
parseJSON
= withObject "I18nRegionSnippet"
(\ o ->
I18nRegionSnippet' <$>
(o .:? "name") <*> (o .:? "gl"))
instance ToJSON I18nRegionSnippet where
toJSON I18nRegionSnippet'{..}
= object
(catMaybes
[("name" .=) <$> _irsName, ("gl" .=) <$> _irsGl])
-- | A *subscription* resource contains information about a YouTube user
-- subscription. A subscription notifies a user when new videos are added
-- to a channel or when another user takes one of several actions on
-- YouTube, such as uploading a video, rating a video, or commenting on a
-- video.
--
-- /See:/ 'subscription' smart constructor.
data Subscription =
Subscription'
{ _subEtag :: !(Maybe Text)
, _subSubscriberSnippet :: !(Maybe SubscriptionSubscriberSnippet)
, _subSnippet :: !(Maybe SubscriptionSnippet)
, _subKind :: !Text
, _subContentDetails :: !(Maybe SubscriptionContentDetails)
, _subId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Subscription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'subEtag'
--
-- * 'subSubscriberSnippet'
--
-- * 'subSnippet'
--
-- * 'subKind'
--
-- * 'subContentDetails'
--
-- * 'subId'
subscription
:: Subscription
subscription =
Subscription'
{ _subEtag = Nothing
, _subSubscriberSnippet = Nothing
, _subSnippet = Nothing
, _subKind = "youtube#subscription"
, _subContentDetails = Nothing
, _subId = Nothing
}
-- | Etag of this resource.
subEtag :: Lens' Subscription (Maybe Text)
subEtag = lens _subEtag (\ s a -> s{_subEtag = a})
-- | The subscriberSnippet object contains basic details about the
-- subscriber.
subSubscriberSnippet :: Lens' Subscription (Maybe SubscriptionSubscriberSnippet)
subSubscriberSnippet
= lens _subSubscriberSnippet
(\ s a -> s{_subSubscriberSnippet = a})
-- | The snippet object contains basic details about the subscription,
-- including its title and the channel that the user subscribed to.
subSnippet :: Lens' Subscription (Maybe SubscriptionSnippet)
subSnippet
= lens _subSnippet (\ s a -> s{_subSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#subscription\".
subKind :: Lens' Subscription Text
subKind = lens _subKind (\ s a -> s{_subKind = a})
-- | The contentDetails object contains basic statistics about the
-- subscription.
subContentDetails :: Lens' Subscription (Maybe SubscriptionContentDetails)
subContentDetails
= lens _subContentDetails
(\ s a -> s{_subContentDetails = a})
-- | The ID that YouTube uses to uniquely identify the subscription.
subId :: Lens' Subscription (Maybe Text)
subId = lens _subId (\ s a -> s{_subId = a})
instance FromJSON Subscription where
parseJSON
= withObject "Subscription"
(\ o ->
Subscription' <$>
(o .:? "etag") <*> (o .:? "subscriberSnippet") <*>
(o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#subscription")
<*> (o .:? "contentDetails")
<*> (o .:? "id"))
instance ToJSON Subscription where
toJSON Subscription'{..}
= object
(catMaybes
[("etag" .=) <$> _subEtag,
("subscriberSnippet" .=) <$> _subSubscriberSnippet,
("snippet" .=) <$> _subSnippet,
Just ("kind" .= _subKind),
("contentDetails" .=) <$> _subContentDetails,
("id" .=) <$> _subId])
--
-- /See:/ 'entity' smart constructor.
data Entity =
Entity'
{ _eTypeId :: !(Maybe Text)
, _eURL :: !(Maybe Text)
, _eId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Entity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eTypeId'
--
-- * 'eURL'
--
-- * 'eId'
entity
:: Entity
entity = Entity' {_eTypeId = Nothing, _eURL = Nothing, _eId = Nothing}
eTypeId :: Lens' Entity (Maybe Text)
eTypeId = lens _eTypeId (\ s a -> s{_eTypeId = a})
eURL :: Lens' Entity (Maybe Text)
eURL = lens _eURL (\ s a -> s{_eURL = a})
eId :: Lens' Entity (Maybe Text)
eId = lens _eId (\ s a -> s{_eId = a})
instance FromJSON Entity where
parseJSON
= withObject "Entity"
(\ o ->
Entity' <$>
(o .:? "typeId") <*> (o .:? "url") <*> (o .:? "id"))
instance ToJSON Entity where
toJSON Entity'{..}
= object
(catMaybes
[("typeId" .=) <$> _eTypeId, ("url" .=) <$> _eURL,
("id" .=) <$> _eId])
--
-- /See:/ 'abuseReport' smart constructor.
data AbuseReport =
AbuseReport'
{ _arSubject :: !(Maybe Entity)
, _arRelatedEntities :: !(Maybe [RelatedEntity])
, _arAbuseTypes :: !(Maybe [AbuseType])
, _arDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AbuseReport' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'arSubject'
--
-- * 'arRelatedEntities'
--
-- * 'arAbuseTypes'
--
-- * 'arDescription'
abuseReport
:: AbuseReport
abuseReport =
AbuseReport'
{ _arSubject = Nothing
, _arRelatedEntities = Nothing
, _arAbuseTypes = Nothing
, _arDescription = Nothing
}
arSubject :: Lens' AbuseReport (Maybe Entity)
arSubject
= lens _arSubject (\ s a -> s{_arSubject = a})
arRelatedEntities :: Lens' AbuseReport [RelatedEntity]
arRelatedEntities
= lens _arRelatedEntities
(\ s a -> s{_arRelatedEntities = a})
. _Default
. _Coerce
arAbuseTypes :: Lens' AbuseReport [AbuseType]
arAbuseTypes
= lens _arAbuseTypes (\ s a -> s{_arAbuseTypes = a})
. _Default
. _Coerce
arDescription :: Lens' AbuseReport (Maybe Text)
arDescription
= lens _arDescription
(\ s a -> s{_arDescription = a})
instance FromJSON AbuseReport where
parseJSON
= withObject "AbuseReport"
(\ o ->
AbuseReport' <$>
(o .:? "subject") <*>
(o .:? "relatedEntities" .!= mempty)
<*> (o .:? "abuseTypes" .!= mempty)
<*> (o .:? "description"))
instance ToJSON AbuseReport where
toJSON AbuseReport'{..}
= object
(catMaybes
[("subject" .=) <$> _arSubject,
("relatedEntities" .=) <$> _arRelatedEntities,
("abuseTypes" .=) <$> _arAbuseTypes,
("description" .=) <$> _arDescription])
-- | Recording information associated with the video.
--
-- /See:/ 'videoRecordingDetails' smart constructor.
data VideoRecordingDetails =
VideoRecordingDetails'
{ _vrdLocation :: !(Maybe GeoPoint)
, _vrdLocationDescription :: !(Maybe Text)
, _vrdRecordingDate :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoRecordingDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vrdLocation'
--
-- * 'vrdLocationDescription'
--
-- * 'vrdRecordingDate'
videoRecordingDetails
:: VideoRecordingDetails
videoRecordingDetails =
VideoRecordingDetails'
{ _vrdLocation = Nothing
, _vrdLocationDescription = Nothing
, _vrdRecordingDate = Nothing
}
-- | The geolocation information associated with the video.
vrdLocation :: Lens' VideoRecordingDetails (Maybe GeoPoint)
vrdLocation
= lens _vrdLocation (\ s a -> s{_vrdLocation = a})
-- | The text description of the location where the video was recorded.
vrdLocationDescription :: Lens' VideoRecordingDetails (Maybe Text)
vrdLocationDescription
= lens _vrdLocationDescription
(\ s a -> s{_vrdLocationDescription = a})
-- | The date and time when the video was recorded.
vrdRecordingDate :: Lens' VideoRecordingDetails (Maybe UTCTime)
vrdRecordingDate
= lens _vrdRecordingDate
(\ s a -> s{_vrdRecordingDate = a})
. mapping _DateTime
instance FromJSON VideoRecordingDetails where
parseJSON
= withObject "VideoRecordingDetails"
(\ o ->
VideoRecordingDetails' <$>
(o .:? "location") <*> (o .:? "locationDescription")
<*> (o .:? "recordingDate"))
instance ToJSON VideoRecordingDetails where
toJSON VideoRecordingDetails'{..}
= object
(catMaybes
[("location" .=) <$> _vrdLocation,
("locationDescription" .=) <$>
_vrdLocationDescription,
("recordingDate" .=) <$> _vrdRecordingDate])
-- | Basic details about rating of a video.
--
-- /See:/ 'videoRating' smart constructor.
data VideoRating =
VideoRating'
{ _vRating :: !(Maybe VideoRatingRating)
, _vVideoId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoRating' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vRating'
--
-- * 'vVideoId'
videoRating
:: VideoRating
videoRating = VideoRating' {_vRating = Nothing, _vVideoId = Nothing}
-- | Rating of a video.
vRating :: Lens' VideoRating (Maybe VideoRatingRating)
vRating = lens _vRating (\ s a -> s{_vRating = a})
-- | The ID that YouTube uses to uniquely identify the video.
vVideoId :: Lens' VideoRating (Maybe Text)
vVideoId = lens _vVideoId (\ s a -> s{_vVideoId = a})
instance FromJSON VideoRating where
parseJSON
= withObject "VideoRating"
(\ o ->
VideoRating' <$>
(o .:? "rating") <*> (o .:? "videoId"))
instance ToJSON VideoRating where
toJSON VideoRating'{..}
= object
(catMaybes
[("rating" .=) <$> _vRating,
("videoId" .=) <$> _vVideoId])
-- | Basic details about a comment, such as its author and text.
--
-- /See:/ 'commentSnippet' smart constructor.
data CommentSnippet =
CommentSnippet'
{ _cViewerRating :: !(Maybe CommentSnippetViewerRating)
, _cPublishedAt :: !(Maybe DateTime')
, _cAuthorChannelURL :: !(Maybe Text)
, _cModerationStatus :: !(Maybe CommentSnippetModerationStatus)
, _cLikeCount :: !(Maybe (Textual Word32))
, _cChannelId :: !(Maybe Text)
, _cTextOriginal :: !(Maybe Text)
, _cVideoId :: !(Maybe Text)
, _cTextDisplay :: !(Maybe Text)
, _cAuthorProFileImageURL :: !(Maybe Text)
, _cAuthorDisplayName :: !(Maybe Text)
, _cUpdatedAt :: !(Maybe DateTime')
, _cAuthorChannelId :: !(Maybe CommentSnippetAuthorChannelId)
, _cCanRate :: !(Maybe Bool)
, _cParentId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cViewerRating'
--
-- * 'cPublishedAt'
--
-- * 'cAuthorChannelURL'
--
-- * 'cModerationStatus'
--
-- * 'cLikeCount'
--
-- * 'cChannelId'
--
-- * 'cTextOriginal'
--
-- * 'cVideoId'
--
-- * 'cTextDisplay'
--
-- * 'cAuthorProFileImageURL'
--
-- * 'cAuthorDisplayName'
--
-- * 'cUpdatedAt'
--
-- * 'cAuthorChannelId'
--
-- * 'cCanRate'
--
-- * 'cParentId'
commentSnippet
:: CommentSnippet
commentSnippet =
CommentSnippet'
{ _cViewerRating = Nothing
, _cPublishedAt = Nothing
, _cAuthorChannelURL = Nothing
, _cModerationStatus = Nothing
, _cLikeCount = Nothing
, _cChannelId = Nothing
, _cTextOriginal = Nothing
, _cVideoId = Nothing
, _cTextDisplay = Nothing
, _cAuthorProFileImageURL = Nothing
, _cAuthorDisplayName = Nothing
, _cUpdatedAt = Nothing
, _cAuthorChannelId = Nothing
, _cCanRate = Nothing
, _cParentId = Nothing
}
-- | The rating the viewer has given to this comment. For the time being this
-- will never return RATE_TYPE_DISLIKE and instead return RATE_TYPE_NONE.
-- This may change in the future.
cViewerRating :: Lens' CommentSnippet (Maybe CommentSnippetViewerRating)
cViewerRating
= lens _cViewerRating
(\ s a -> s{_cViewerRating = a})
-- | The date and time when the comment was originally published.
cPublishedAt :: Lens' CommentSnippet (Maybe UTCTime)
cPublishedAt
= lens _cPublishedAt (\ s a -> s{_cPublishedAt = a})
. mapping _DateTime
-- | Link to the author\'s YouTube channel, if any.
cAuthorChannelURL :: Lens' CommentSnippet (Maybe Text)
cAuthorChannelURL
= lens _cAuthorChannelURL
(\ s a -> s{_cAuthorChannelURL = a})
-- | The comment\'s moderation status. Will not be set if the comments were
-- requested through the id filter.
cModerationStatus :: Lens' CommentSnippet (Maybe CommentSnippetModerationStatus)
cModerationStatus
= lens _cModerationStatus
(\ s a -> s{_cModerationStatus = a})
-- | The total number of likes this comment has received.
cLikeCount :: Lens' CommentSnippet (Maybe Word32)
cLikeCount
= lens _cLikeCount (\ s a -> s{_cLikeCount = a}) .
mapping _Coerce
-- | The id of the corresponding YouTube channel. In case of a channel
-- comment this is the channel the comment refers to. In case of a video
-- comment it\'s the video\'s channel.
cChannelId :: Lens' CommentSnippet (Maybe Text)
cChannelId
= lens _cChannelId (\ s a -> s{_cChannelId = a})
-- | The comment\'s original raw text as initially posted or last updated.
-- The original text will only be returned if it is accessible to the
-- viewer, which is only guaranteed if the viewer is the comment\'s author.
cTextOriginal :: Lens' CommentSnippet (Maybe Text)
cTextOriginal
= lens _cTextOriginal
(\ s a -> s{_cTextOriginal = a})
-- | The ID of the video the comment refers to, if any.
cVideoId :: Lens' CommentSnippet (Maybe Text)
cVideoId = lens _cVideoId (\ s a -> s{_cVideoId = a})
-- | The comment\'s text. The format is either plain text or HTML dependent
-- on what has been requested. Even the plain text representation may
-- differ from the text originally posted in that it may replace video
-- links with video titles etc.
cTextDisplay :: Lens' CommentSnippet (Maybe Text)
cTextDisplay
= lens _cTextDisplay (\ s a -> s{_cTextDisplay = a})
-- | The URL for the avatar of the user who posted the comment.
cAuthorProFileImageURL :: Lens' CommentSnippet (Maybe Text)
cAuthorProFileImageURL
= lens _cAuthorProFileImageURL
(\ s a -> s{_cAuthorProFileImageURL = a})
-- | The name of the user who posted the comment.
cAuthorDisplayName :: Lens' CommentSnippet (Maybe Text)
cAuthorDisplayName
= lens _cAuthorDisplayName
(\ s a -> s{_cAuthorDisplayName = a})
-- | The date and time when the comment was last updated.
cUpdatedAt :: Lens' CommentSnippet (Maybe UTCTime)
cUpdatedAt
= lens _cUpdatedAt (\ s a -> s{_cUpdatedAt = a}) .
mapping _DateTime
cAuthorChannelId :: Lens' CommentSnippet (Maybe CommentSnippetAuthorChannelId)
cAuthorChannelId
= lens _cAuthorChannelId
(\ s a -> s{_cAuthorChannelId = a})
-- | Whether the current viewer can rate this comment.
cCanRate :: Lens' CommentSnippet (Maybe Bool)
cCanRate = lens _cCanRate (\ s a -> s{_cCanRate = a})
-- | The unique id of the parent comment, only set for replies.
cParentId :: Lens' CommentSnippet (Maybe Text)
cParentId
= lens _cParentId (\ s a -> s{_cParentId = a})
instance FromJSON CommentSnippet where
parseJSON
= withObject "CommentSnippet"
(\ o ->
CommentSnippet' <$>
(o .:? "viewerRating") <*> (o .:? "publishedAt") <*>
(o .:? "authorChannelUrl")
<*> (o .:? "moderationStatus")
<*> (o .:? "likeCount")
<*> (o .:? "channelId")
<*> (o .:? "textOriginal")
<*> (o .:? "videoId")
<*> (o .:? "textDisplay")
<*> (o .:? "authorProfileImageUrl")
<*> (o .:? "authorDisplayName")
<*> (o .:? "updatedAt")
<*> (o .:? "authorChannelId")
<*> (o .:? "canRate")
<*> (o .:? "parentId"))
instance ToJSON CommentSnippet where
toJSON CommentSnippet'{..}
= object
(catMaybes
[("viewerRating" .=) <$> _cViewerRating,
("publishedAt" .=) <$> _cPublishedAt,
("authorChannelUrl" .=) <$> _cAuthorChannelURL,
("moderationStatus" .=) <$> _cModerationStatus,
("likeCount" .=) <$> _cLikeCount,
("channelId" .=) <$> _cChannelId,
("textOriginal" .=) <$> _cTextOriginal,
("videoId" .=) <$> _cVideoId,
("textDisplay" .=) <$> _cTextDisplay,
("authorProfileImageUrl" .=) <$>
_cAuthorProFileImageURL,
("authorDisplayName" .=) <$> _cAuthorDisplayName,
("updatedAt" .=) <$> _cUpdatedAt,
("authorChannelId" .=) <$> _cAuthorChannelId,
("canRate" .=) <$> _cCanRate,
("parentId" .=) <$> _cParentId])
-- | Brief description of the live stream status.
--
-- /See:/ 'liveStreamStatus' smart constructor.
data LiveStreamStatus =
LiveStreamStatus'
{ _lssStreamStatus :: !(Maybe LiveStreamStatusStreamStatus)
, _lssHealthStatus :: !(Maybe LiveStreamHealthStatus)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveStreamStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lssStreamStatus'
--
-- * 'lssHealthStatus'
liveStreamStatus
:: LiveStreamStatus
liveStreamStatus =
LiveStreamStatus' {_lssStreamStatus = Nothing, _lssHealthStatus = Nothing}
lssStreamStatus :: Lens' LiveStreamStatus (Maybe LiveStreamStatusStreamStatus)
lssStreamStatus
= lens _lssStreamStatus
(\ s a -> s{_lssStreamStatus = a})
-- | The health status of the stream.
lssHealthStatus :: Lens' LiveStreamStatus (Maybe LiveStreamHealthStatus)
lssHealthStatus
= lens _lssHealthStatus
(\ s a -> s{_lssHealthStatus = a})
instance FromJSON LiveStreamStatus where
parseJSON
= withObject "LiveStreamStatus"
(\ o ->
LiveStreamStatus' <$>
(o .:? "streamStatus") <*> (o .:? "healthStatus"))
instance ToJSON LiveStreamStatus where
toJSON LiveStreamStatus'{..}
= object
(catMaybes
[("streamStatus" .=) <$> _lssStreamStatus,
("healthStatus" .=) <$> _lssHealthStatus])
-- | Specifies suggestions on how to improve video content, including
-- encoding hints, tag suggestions, and editor suggestions.
--
-- /See:/ 'videoSuggestions' smart constructor.
data VideoSuggestions =
VideoSuggestions'
{ _vsProcessingErrors :: !(Maybe [VideoSuggestionsProcessingErrorsItem])
, _vsProcessingHints :: !(Maybe [VideoSuggestionsProcessingHintsItem])
, _vsEditorSuggestions :: !(Maybe [VideoSuggestionsEditorSuggestionsItem])
, _vsProcessingWarnings :: !(Maybe [VideoSuggestionsProcessingWarningsItem])
, _vsTagSuggestions :: !(Maybe [VideoSuggestionsTagSuggestion])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoSuggestions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vsProcessingErrors'
--
-- * 'vsProcessingHints'
--
-- * 'vsEditorSuggestions'
--
-- * 'vsProcessingWarnings'
--
-- * 'vsTagSuggestions'
videoSuggestions
:: VideoSuggestions
videoSuggestions =
VideoSuggestions'
{ _vsProcessingErrors = Nothing
, _vsProcessingHints = Nothing
, _vsEditorSuggestions = Nothing
, _vsProcessingWarnings = Nothing
, _vsTagSuggestions = Nothing
}
-- | A list of errors that will prevent YouTube from successfully processing
-- the uploaded video video. These errors indicate that, regardless of the
-- video\'s current processing status, eventually, that status will almost
-- certainly be failed.
vsProcessingErrors :: Lens' VideoSuggestions [VideoSuggestionsProcessingErrorsItem]
vsProcessingErrors
= lens _vsProcessingErrors
(\ s a -> s{_vsProcessingErrors = a})
. _Default
. _Coerce
-- | A list of suggestions that may improve YouTube\'s ability to process the
-- video.
vsProcessingHints :: Lens' VideoSuggestions [VideoSuggestionsProcessingHintsItem]
vsProcessingHints
= lens _vsProcessingHints
(\ s a -> s{_vsProcessingHints = a})
. _Default
. _Coerce
-- | A list of video editing operations that might improve the video quality
-- or playback experience of the uploaded video.
vsEditorSuggestions :: Lens' VideoSuggestions [VideoSuggestionsEditorSuggestionsItem]
vsEditorSuggestions
= lens _vsEditorSuggestions
(\ s a -> s{_vsEditorSuggestions = a})
. _Default
. _Coerce
-- | A list of reasons why YouTube may have difficulty transcoding the
-- uploaded video or that might result in an erroneous transcoding. These
-- warnings are generated before YouTube actually processes the uploaded
-- video file. In addition, they identify issues that are unlikely to cause
-- the video processing to fail but that might cause problems such as sync
-- issues, video artifacts, or a missing audio track.
vsProcessingWarnings :: Lens' VideoSuggestions [VideoSuggestionsProcessingWarningsItem]
vsProcessingWarnings
= lens _vsProcessingWarnings
(\ s a -> s{_vsProcessingWarnings = a})
. _Default
. _Coerce
-- | A list of keyword tags that could be added to the video\'s metadata to
-- increase the likelihood that users will locate your video when searching
-- or browsing on YouTube.
vsTagSuggestions :: Lens' VideoSuggestions [VideoSuggestionsTagSuggestion]
vsTagSuggestions
= lens _vsTagSuggestions
(\ s a -> s{_vsTagSuggestions = a})
. _Default
. _Coerce
instance FromJSON VideoSuggestions where
parseJSON
= withObject "VideoSuggestions"
(\ o ->
VideoSuggestions' <$>
(o .:? "processingErrors" .!= mempty) <*>
(o .:? "processingHints" .!= mempty)
<*> (o .:? "editorSuggestions" .!= mempty)
<*> (o .:? "processingWarnings" .!= mempty)
<*> (o .:? "tagSuggestions" .!= mempty))
instance ToJSON VideoSuggestions where
toJSON VideoSuggestions'{..}
= object
(catMaybes
[("processingErrors" .=) <$> _vsProcessingErrors,
("processingHints" .=) <$> _vsProcessingHints,
("editorSuggestions" .=) <$> _vsEditorSuggestions,
("processingWarnings" .=) <$> _vsProcessingWarnings,
("tagSuggestions" .=) <$> _vsTagSuggestions])
--
-- /See:/ 'membershipsLevelListResponse' smart constructor.
data MembershipsLevelListResponse =
MembershipsLevelListResponse'
{ _mllrEtag :: !(Maybe Text)
, _mllrKind :: !Text
, _mllrItems :: !(Maybe [MembershipsLevel])
, _mllrVisitorId :: !(Maybe Text)
, _mllrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MembershipsLevelListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mllrEtag'
--
-- * 'mllrKind'
--
-- * 'mllrItems'
--
-- * 'mllrVisitorId'
--
-- * 'mllrEventId'
membershipsLevelListResponse
:: MembershipsLevelListResponse
membershipsLevelListResponse =
MembershipsLevelListResponse'
{ _mllrEtag = Nothing
, _mllrKind = "youtube#membershipsLevelListResponse"
, _mllrItems = Nothing
, _mllrVisitorId = Nothing
, _mllrEventId = Nothing
}
-- | Etag of this resource.
mllrEtag :: Lens' MembershipsLevelListResponse (Maybe Text)
mllrEtag = lens _mllrEtag (\ s a -> s{_mllrEtag = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#membershipsLevelListResponse\".
mllrKind :: Lens' MembershipsLevelListResponse Text
mllrKind = lens _mllrKind (\ s a -> s{_mllrKind = a})
-- | A list of pricing levels offered by a creator to the fans.
mllrItems :: Lens' MembershipsLevelListResponse [MembershipsLevel]
mllrItems
= lens _mllrItems (\ s a -> s{_mllrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
mllrVisitorId :: Lens' MembershipsLevelListResponse (Maybe Text)
mllrVisitorId
= lens _mllrVisitorId
(\ s a -> s{_mllrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
mllrEventId :: Lens' MembershipsLevelListResponse (Maybe Text)
mllrEventId
= lens _mllrEventId (\ s a -> s{_mllrEventId = a})
instance FromJSON MembershipsLevelListResponse where
parseJSON
= withObject "MembershipsLevelListResponse"
(\ o ->
MembershipsLevelListResponse' <$>
(o .:? "etag") <*>
(o .:? "kind" .!=
"youtube#membershipsLevelListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON MembershipsLevelListResponse where
toJSON MembershipsLevelListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _mllrEtag,
Just ("kind" .= _mllrKind),
("items" .=) <$> _mllrItems,
("visitorId" .=) <$> _mllrVisitorId,
("eventId" .=) <$> _mllrEventId])
-- | Basic details about a playlist, including title, description and
-- thumbnails. Basic details of a YouTube Playlist item provided by the
-- author. Next ID: 15
--
-- /See:/ 'playListItemSnippet' smart constructor.
data PlayListItemSnippet =
PlayListItemSnippet'
{ _plisResourceId :: !(Maybe ResourceId)
, _plisPublishedAt :: !(Maybe DateTime')
, _plisChannelTitle :: !(Maybe Text)
, _plisChannelId :: !(Maybe Text)
, _plisThumbnails :: !(Maybe ThumbnailDetails)
, _plisTitle :: !(Maybe Text)
, _plisPlayListId :: !(Maybe Text)
, _plisVideoOwnerChannelTitle :: !(Maybe Text)
, _plisVideoOwnerChannelId :: !(Maybe Text)
, _plisDescription :: !(Maybe Text)
, _plisPosition :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListItemSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plisResourceId'
--
-- * 'plisPublishedAt'
--
-- * 'plisChannelTitle'
--
-- * 'plisChannelId'
--
-- * 'plisThumbnails'
--
-- * 'plisTitle'
--
-- * 'plisPlayListId'
--
-- * 'plisVideoOwnerChannelTitle'
--
-- * 'plisVideoOwnerChannelId'
--
-- * 'plisDescription'
--
-- * 'plisPosition'
playListItemSnippet
:: PlayListItemSnippet
playListItemSnippet =
PlayListItemSnippet'
{ _plisResourceId = Nothing
, _plisPublishedAt = Nothing
, _plisChannelTitle = Nothing
, _plisChannelId = Nothing
, _plisThumbnails = Nothing
, _plisTitle = Nothing
, _plisPlayListId = Nothing
, _plisVideoOwnerChannelTitle = Nothing
, _plisVideoOwnerChannelId = Nothing
, _plisDescription = Nothing
, _plisPosition = Nothing
}
-- | The id object contains information that can be used to uniquely identify
-- the resource that is included in the playlist as the playlist item.
plisResourceId :: Lens' PlayListItemSnippet (Maybe ResourceId)
plisResourceId
= lens _plisResourceId
(\ s a -> s{_plisResourceId = a})
-- | The date and time that the item was added to the playlist.
plisPublishedAt :: Lens' PlayListItemSnippet (Maybe UTCTime)
plisPublishedAt
= lens _plisPublishedAt
(\ s a -> s{_plisPublishedAt = a})
. mapping _DateTime
-- | Channel title for the channel that the playlist item belongs to.
plisChannelTitle :: Lens' PlayListItemSnippet (Maybe Text)
plisChannelTitle
= lens _plisChannelTitle
(\ s a -> s{_plisChannelTitle = a})
-- | The ID that YouTube uses to uniquely identify the user that added the
-- item to the playlist.
plisChannelId :: Lens' PlayListItemSnippet (Maybe Text)
plisChannelId
= lens _plisChannelId
(\ s a -> s{_plisChannelId = a})
-- | A map of thumbnail images associated with the playlist item. For each
-- object in the map, the key is the name of the thumbnail image, and the
-- value is an object that contains other information about the thumbnail.
plisThumbnails :: Lens' PlayListItemSnippet (Maybe ThumbnailDetails)
plisThumbnails
= lens _plisThumbnails
(\ s a -> s{_plisThumbnails = a})
-- | The item\'s title.
plisTitle :: Lens' PlayListItemSnippet (Maybe Text)
plisTitle
= lens _plisTitle (\ s a -> s{_plisTitle = a})
-- | The ID that YouTube uses to uniquely identify thGe playlist that the
-- playlist item is in.
plisPlayListId :: Lens' PlayListItemSnippet (Maybe Text)
plisPlayListId
= lens _plisPlayListId
(\ s a -> s{_plisPlayListId = a})
-- | Channel title for the channel this video belongs to.
plisVideoOwnerChannelTitle :: Lens' PlayListItemSnippet (Maybe Text)
plisVideoOwnerChannelTitle
= lens _plisVideoOwnerChannelTitle
(\ s a -> s{_plisVideoOwnerChannelTitle = a})
-- | Channel id for the channel this video belongs to.
plisVideoOwnerChannelId :: Lens' PlayListItemSnippet (Maybe Text)
plisVideoOwnerChannelId
= lens _plisVideoOwnerChannelId
(\ s a -> s{_plisVideoOwnerChannelId = a})
-- | The item\'s description.
plisDescription :: Lens' PlayListItemSnippet (Maybe Text)
plisDescription
= lens _plisDescription
(\ s a -> s{_plisDescription = a})
-- | The order in which the item appears in the playlist. The value uses a
-- zero-based index, so the first item has a position of 0, the second item
-- has a position of 1, and so forth.
plisPosition :: Lens' PlayListItemSnippet (Maybe Word32)
plisPosition
= lens _plisPosition (\ s a -> s{_plisPosition = a})
. mapping _Coerce
instance FromJSON PlayListItemSnippet where
parseJSON
= withObject "PlayListItemSnippet"
(\ o ->
PlayListItemSnippet' <$>
(o .:? "resourceId") <*> (o .:? "publishedAt") <*>
(o .:? "channelTitle")
<*> (o .:? "channelId")
<*> (o .:? "thumbnails")
<*> (o .:? "title")
<*> (o .:? "playlistId")
<*> (o .:? "videoOwnerChannelTitle")
<*> (o .:? "videoOwnerChannelId")
<*> (o .:? "description")
<*> (o .:? "position"))
instance ToJSON PlayListItemSnippet where
toJSON PlayListItemSnippet'{..}
= object
(catMaybes
[("resourceId" .=) <$> _plisResourceId,
("publishedAt" .=) <$> _plisPublishedAt,
("channelTitle" .=) <$> _plisChannelTitle,
("channelId" .=) <$> _plisChannelId,
("thumbnails" .=) <$> _plisThumbnails,
("title" .=) <$> _plisTitle,
("playlistId" .=) <$> _plisPlayListId,
("videoOwnerChannelTitle" .=) <$>
_plisVideoOwnerChannelTitle,
("videoOwnerChannelId" .=) <$>
_plisVideoOwnerChannelId,
("description" .=) <$> _plisDescription,
("position" .=) <$> _plisPosition])
-- | DEPRECATED. b\/157517979: This part was never populated after it was
-- added. However, it sees non-zero traffic because there is generated
-- client code in the wild that refers to it [1]. We keep this field and do
-- NOT remove it because otherwise V3 would return an error when this part
-- gets requested [2]. [1]
-- https:\/\/developers.google.com\/resources\/api-libraries\/documentation\/youtube\/v3\/csharp\/latest\/classGoogle_1_1Apis_1_1YouTube_1_1v3_1_1Data_1_1VideoProjectDetails.html
-- [2]
-- http:\/\/google3\/video\/youtube\/src\/python\/servers\/data_api\/common.py?l=1565-1569&rcl=344141677
--
-- /See:/ 'videoProjectDetails' smart constructor.
data VideoProjectDetails =
VideoProjectDetails'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoProjectDetails' with the minimum fields required to make a request.
--
videoProjectDetails
:: VideoProjectDetails
videoProjectDetails = VideoProjectDetails'
instance FromJSON VideoProjectDetails where
parseJSON
= withObject "VideoProjectDetails"
(\ o -> pure VideoProjectDetails')
instance ToJSON VideoProjectDetails where
toJSON = const emptyObject
-- | Ratings schemes. The country-specific ratings are mostly for movies and
-- shows. LINT.IfChange
--
-- /See:/ 'contentRating' smart constructor.
data ContentRating =
ContentRating'
{ _crFpbRatingReasons :: !(Maybe [ContentRatingFpbRatingReasonsItem])
, _crPefilmRating :: !(Maybe ContentRatingPefilmRating)
, _crCccRating :: !(Maybe ContentRatingCccRating)
, _crAnatelRating :: !(Maybe ContentRatingAnatelRating)
, _crMpaaRating :: !(Maybe ContentRatingMpaaRating)
, _crCceRating :: !(Maybe ContentRatingCceRating)
, _crMccaaRating :: !(Maybe ContentRatingMccaaRating)
, _crChfilmRating :: !(Maybe ContentRatingChfilmRating)
, _crIcaaRating :: !(Maybe ContentRatingIcaaRating)
, _crFcbmRating :: !(Maybe ContentRatingFcbmRating)
, _crBmukkRating :: !(Maybe ContentRatingBmukkRating)
, _crMoctwRating :: !(Maybe ContentRatingMoctwRating)
, _crNfvcbRating :: !(Maybe ContentRatingNfvcbRating)
, _crDjctqRatingReasons :: !(Maybe [ContentRatingDjctqRatingReasonsItem])
, _crAgcomRating :: !(Maybe ContentRatingAgcomRating)
, _crCnaRating :: !(Maybe ContentRatingCnaRating)
, _crCatvfrRating :: !(Maybe ContentRatingCatvfrRating)
, _crCbfcRating :: !(Maybe ContentRatingCbfcRating)
, _crKfcbRating :: !(Maybe ContentRatingKfcbRating)
, _crSmsaRating :: !(Maybe ContentRatingSmsaRating)
, _crChvrsRating :: !(Maybe ContentRatingChvrsRating)
, _crIncaaRating :: !(Maybe ContentRatingIncaaRating)
, _crMcstRating :: !(Maybe ContentRatingMcstRating)
, _crNfrcRating :: !(Maybe ContentRatingNfrcRating)
, _crCsaRating :: !(Maybe ContentRatingCsaRating)
, _crMocRating :: !(Maybe ContentRatingMocRating)
, _crEirinRating :: !(Maybe ContentRatingEirinRating)
, _crFskRating :: !(Maybe ContentRatingFskRating)
, _crEefilmRating :: !(Maybe ContentRatingEefilmRating)
, _crRcnofRating :: !(Maybe ContentRatingRcnofRating)
, _crMekuRating :: !(Maybe ContentRatingMekuRating)
, _crIlfilmRating :: !(Maybe ContentRatingIlfilmRating)
, _crIfcoRating :: !(Maybe ContentRatingIfcoRating)
, _crNbcplRating :: !(Maybe ContentRatingNbcplRating)
, _crGrfilmRating :: !(Maybe ContentRatingGrfilmRating)
, _crRteRating :: !(Maybe ContentRatingRteRating)
, _crAcbRating :: !(Maybe ContentRatingAcbRating)
, _crCatvRating :: !(Maybe ContentRatingCatvRating)
, _crMdaRating :: !(Maybe ContentRatingMdaRating)
, _crNmcRating :: !(Maybe ContentRatingNmcRating)
, _crDjctqRating :: !(Maybe ContentRatingDjctqRating)
, _crSmaisRating :: !(Maybe ContentRatingSmaisRating)
, _crCscfRating :: !(Maybe ContentRatingCscfRating)
, _crTvpgRating :: !(Maybe ContentRatingTvpgRating)
, _crRtcRating :: !(Maybe ContentRatingRtcRating)
, _crYtRating :: !(Maybe ContentRatingYtRating)
, _crBbfcRating :: !(Maybe ContentRatingBbfcRating)
, _crMenaMpaaRating :: !(Maybe ContentRatingMenaMpaaRating)
, _crKijkwijzerRating :: !(Maybe ContentRatingKijkwijzerRating)
, _crMtrcbRating :: !(Maybe ContentRatingMtrcbRating)
, _crFcoRating :: !(Maybe ContentRatingFcoRating)
, _crCicfRating :: !(Maybe ContentRatingCicfRating)
, _crCzfilmRating :: !(Maybe ContentRatingCzfilmRating)
, _crNbcRating :: !(Maybe ContentRatingNbcRating)
, _crFmocRating :: !(Maybe ContentRatingFmocRating)
, _crRussiaRating :: !(Maybe ContentRatingRussiaRating)
, _crEgfilmRating :: !(Maybe ContentRatingEgfilmRating)
, _crResorteviolenciaRating :: !(Maybe ContentRatingResorteviolenciaRating)
, _crMibacRating :: !(Maybe ContentRatingMibacRating)
, _crMedietilsynetRating :: !(Maybe ContentRatingMedietilsynetRating)
, _crMccypRating :: !(Maybe ContentRatingMccypRating)
, _crNkclvRating :: !(Maybe ContentRatingNkclvRating)
, _crFpbRating :: !(Maybe ContentRatingFpbRating)
, _crLsfRating :: !(Maybe ContentRatingLsfRating)
, _crBfvcRating :: !(Maybe ContentRatingBfvcRating)
, _crMpaatRating :: !(Maybe ContentRatingMpaatRating)
, _crEcbmctRating :: !(Maybe ContentRatingEcbmctRating)
, _crCNCRating :: !(Maybe ContentRatingCNCRating)
, _crSkfilmRating :: !(Maybe ContentRatingSkfilmRating)
, _crOflcRating :: !(Maybe ContentRatingOflcRating)
, _crKmrbRating :: !(Maybe ContentRatingKmrbRating)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ContentRating' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'crFpbRatingReasons'
--
-- * 'crPefilmRating'
--
-- * 'crCccRating'
--
-- * 'crAnatelRating'
--
-- * 'crMpaaRating'
--
-- * 'crCceRating'
--
-- * 'crMccaaRating'
--
-- * 'crChfilmRating'
--
-- * 'crIcaaRating'
--
-- * 'crFcbmRating'
--
-- * 'crBmukkRating'
--
-- * 'crMoctwRating'
--
-- * 'crNfvcbRating'
--
-- * 'crDjctqRatingReasons'
--
-- * 'crAgcomRating'
--
-- * 'crCnaRating'
--
-- * 'crCatvfrRating'
--
-- * 'crCbfcRating'
--
-- * 'crKfcbRating'
--
-- * 'crSmsaRating'
--
-- * 'crChvrsRating'
--
-- * 'crIncaaRating'
--
-- * 'crMcstRating'
--
-- * 'crNfrcRating'
--
-- * 'crCsaRating'
--
-- * 'crMocRating'
--
-- * 'crEirinRating'
--
-- * 'crFskRating'
--
-- * 'crEefilmRating'
--
-- * 'crRcnofRating'
--
-- * 'crMekuRating'
--
-- * 'crIlfilmRating'
--
-- * 'crIfcoRating'
--
-- * 'crNbcplRating'
--
-- * 'crGrfilmRating'
--
-- * 'crRteRating'
--
-- * 'crAcbRating'
--
-- * 'crCatvRating'
--
-- * 'crMdaRating'
--
-- * 'crNmcRating'
--
-- * 'crDjctqRating'
--
-- * 'crSmaisRating'
--
-- * 'crCscfRating'
--
-- * 'crTvpgRating'
--
-- * 'crRtcRating'
--
-- * 'crYtRating'
--
-- * 'crBbfcRating'
--
-- * 'crMenaMpaaRating'
--
-- * 'crKijkwijzerRating'
--
-- * 'crMtrcbRating'
--
-- * 'crFcoRating'
--
-- * 'crCicfRating'
--
-- * 'crCzfilmRating'
--
-- * 'crNbcRating'
--
-- * 'crFmocRating'
--
-- * 'crRussiaRating'
--
-- * 'crEgfilmRating'
--
-- * 'crResorteviolenciaRating'
--
-- * 'crMibacRating'
--
-- * 'crMedietilsynetRating'
--
-- * 'crMccypRating'
--
-- * 'crNkclvRating'
--
-- * 'crFpbRating'
--
-- * 'crLsfRating'
--
-- * 'crBfvcRating'
--
-- * 'crMpaatRating'
--
-- * 'crEcbmctRating'
--
-- * 'crCNCRating'
--
-- * 'crSkfilmRating'
--
-- * 'crOflcRating'
--
-- * 'crKmrbRating'
contentRating
:: ContentRating
contentRating =
ContentRating'
{ _crFpbRatingReasons = Nothing
, _crPefilmRating = Nothing
, _crCccRating = Nothing
, _crAnatelRating = Nothing
, _crMpaaRating = Nothing
, _crCceRating = Nothing
, _crMccaaRating = Nothing
, _crChfilmRating = Nothing
, _crIcaaRating = Nothing
, _crFcbmRating = Nothing
, _crBmukkRating = Nothing
, _crMoctwRating = Nothing
, _crNfvcbRating = Nothing
, _crDjctqRatingReasons = Nothing
, _crAgcomRating = Nothing
, _crCnaRating = Nothing
, _crCatvfrRating = Nothing
, _crCbfcRating = Nothing
, _crKfcbRating = Nothing
, _crSmsaRating = Nothing
, _crChvrsRating = Nothing
, _crIncaaRating = Nothing
, _crMcstRating = Nothing
, _crNfrcRating = Nothing
, _crCsaRating = Nothing
, _crMocRating = Nothing
, _crEirinRating = Nothing
, _crFskRating = Nothing
, _crEefilmRating = Nothing
, _crRcnofRating = Nothing
, _crMekuRating = Nothing
, _crIlfilmRating = Nothing
, _crIfcoRating = Nothing
, _crNbcplRating = Nothing
, _crGrfilmRating = Nothing
, _crRteRating = Nothing
, _crAcbRating = Nothing
, _crCatvRating = Nothing
, _crMdaRating = Nothing
, _crNmcRating = Nothing
, _crDjctqRating = Nothing
, _crSmaisRating = Nothing
, _crCscfRating = Nothing
, _crTvpgRating = Nothing
, _crRtcRating = Nothing
, _crYtRating = Nothing
, _crBbfcRating = Nothing
, _crMenaMpaaRating = Nothing
, _crKijkwijzerRating = Nothing
, _crMtrcbRating = Nothing
, _crFcoRating = Nothing
, _crCicfRating = Nothing
, _crCzfilmRating = Nothing
, _crNbcRating = Nothing
, _crFmocRating = Nothing
, _crRussiaRating = Nothing
, _crEgfilmRating = Nothing
, _crResorteviolenciaRating = Nothing
, _crMibacRating = Nothing
, _crMedietilsynetRating = Nothing
, _crMccypRating = Nothing
, _crNkclvRating = Nothing
, _crFpbRating = Nothing
, _crLsfRating = Nothing
, _crBfvcRating = Nothing
, _crMpaatRating = Nothing
, _crEcbmctRating = Nothing
, _crCNCRating = Nothing
, _crSkfilmRating = Nothing
, _crOflcRating = Nothing
, _crKmrbRating = Nothing
}
-- | Reasons that explain why the video received its FPB (South Africa)
-- rating.
crFpbRatingReasons :: Lens' ContentRating [ContentRatingFpbRatingReasonsItem]
crFpbRatingReasons
= lens _crFpbRatingReasons
(\ s a -> s{_crFpbRatingReasons = a})
. _Default
. _Coerce
-- | The video\'s rating in Peru.
crPefilmRating :: Lens' ContentRating (Maybe ContentRatingPefilmRating)
crPefilmRating
= lens _crPefilmRating
(\ s a -> s{_crPefilmRating = a})
-- | The video\'s Consejo de Calificación Cinematográfica (Chile) rating.
crCccRating :: Lens' ContentRating (Maybe ContentRatingCccRating)
crCccRating
= lens _crCccRating (\ s a -> s{_crCccRating = a})
-- | The video\'s Anatel (Asociación Nacional de Televisión) rating for
-- Chilean television.
crAnatelRating :: Lens' ContentRating (Maybe ContentRatingAnatelRating)
crAnatelRating
= lens _crAnatelRating
(\ s a -> s{_crAnatelRating = a})
-- | The video\'s Motion Picture Association of America (MPAA) rating.
crMpaaRating :: Lens' ContentRating (Maybe ContentRatingMpaaRating)
crMpaaRating
= lens _crMpaaRating (\ s a -> s{_crMpaaRating = a})
-- | The video\'s rating from Portugal\'s Comissão de Classificação de
-- Espect´culos.
crCceRating :: Lens' ContentRating (Maybe ContentRatingCceRating)
crCceRating
= lens _crCceRating (\ s a -> s{_crCceRating = a})
-- | The video\'s rating from Malta\'s Film Age-Classification Board.
crMccaaRating :: Lens' ContentRating (Maybe ContentRatingMccaaRating)
crMccaaRating
= lens _crMccaaRating
(\ s a -> s{_crMccaaRating = a})
-- | The video\'s rating in Switzerland.
crChfilmRating :: Lens' ContentRating (Maybe ContentRatingChfilmRating)
crChfilmRating
= lens _crChfilmRating
(\ s a -> s{_crChfilmRating = a})
-- | The video\'s Instituto de la Cinematografía y de las Artes Audiovisuales
-- (ICAA - Spain) rating.
crIcaaRating :: Lens' ContentRating (Maybe ContentRatingIcaaRating)
crIcaaRating
= lens _crIcaaRating (\ s a -> s{_crIcaaRating = a})
-- | The video\'s rating from Malaysia\'s Film Censorship Board.
crFcbmRating :: Lens' ContentRating (Maybe ContentRatingFcbmRating)
crFcbmRating
= lens _crFcbmRating (\ s a -> s{_crFcbmRating = a})
-- | The video\'s rating from the Austrian Board of Media Classification
-- (Bundesministerium für Unterricht, Kunst und Kultur).
crBmukkRating :: Lens' ContentRating (Maybe ContentRatingBmukkRating)
crBmukkRating
= lens _crBmukkRating
(\ s a -> s{_crBmukkRating = a})
-- | The video\'s rating from Taiwan\'s Ministry of Culture (文化部).
crMoctwRating :: Lens' ContentRating (Maybe ContentRatingMoctwRating)
crMoctwRating
= lens _crMoctwRating
(\ s a -> s{_crMoctwRating = a})
-- | The video\'s rating from Nigeria\'s National Film and Video Censors
-- Board.
crNfvcbRating :: Lens' ContentRating (Maybe ContentRatingNfvcbRating)
crNfvcbRating
= lens _crNfvcbRating
(\ s a -> s{_crNfvcbRating = a})
-- | Reasons that explain why the video received its DJCQT (Brazil) rating.
crDjctqRatingReasons :: Lens' ContentRating [ContentRatingDjctqRatingReasonsItem]
crDjctqRatingReasons
= lens _crDjctqRatingReasons
(\ s a -> s{_crDjctqRatingReasons = a})
. _Default
. _Coerce
-- | The video\'s rating from Italy\'s Autorità per le Garanzie nelle
-- Comunicazioni (AGCOM).
crAgcomRating :: Lens' ContentRating (Maybe ContentRatingAgcomRating)
crAgcomRating
= lens _crAgcomRating
(\ s a -> s{_crAgcomRating = a})
-- | The video\'s rating from Romania\'s CONSILIUL NATIONAL AL
-- AUDIOVIZUALULUI (CNA).
crCnaRating :: Lens' ContentRating (Maybe ContentRatingCnaRating)
crCnaRating
= lens _crCnaRating (\ s a -> s{_crCnaRating = a})
-- | The video\'s rating from the Canadian Radio-Television and
-- Telecommunications Commission (CRTC) for Canadian French-language
-- broadcasts. For more information, see the Canadian Broadcast Standards
-- Council website.
crCatvfrRating :: Lens' ContentRating (Maybe ContentRatingCatvfrRating)
crCatvfrRating
= lens _crCatvfrRating
(\ s a -> s{_crCatvfrRating = a})
-- | The video\'s Central Board of Film Certification (CBFC - India) rating.
crCbfcRating :: Lens' ContentRating (Maybe ContentRatingCbfcRating)
crCbfcRating
= lens _crCbfcRating (\ s a -> s{_crCbfcRating = a})
-- | The video\'s rating from the Kenya Film Classification Board.
crKfcbRating :: Lens' ContentRating (Maybe ContentRatingKfcbRating)
crKfcbRating
= lens _crKfcbRating (\ s a -> s{_crKfcbRating = a})
-- | The video\'s rating from Statens medieråd (Sweden\'s National Media
-- Council).
crSmsaRating :: Lens' ContentRating (Maybe ContentRatingSmsaRating)
crSmsaRating
= lens _crSmsaRating (\ s a -> s{_crSmsaRating = a})
-- | The video\'s Canadian Home Video Rating System (CHVRS) rating.
crChvrsRating :: Lens' ContentRating (Maybe ContentRatingChvrsRating)
crChvrsRating
= lens _crChvrsRating
(\ s a -> s{_crChvrsRating = a})
-- | The video\'s INCAA (Instituto Nacional de Cine y Artes Audiovisuales -
-- Argentina) rating.
crIncaaRating :: Lens' ContentRating (Maybe ContentRatingIncaaRating)
crIncaaRating
= lens _crIncaaRating
(\ s a -> s{_crIncaaRating = a})
-- | The video\'s rating system for Vietnam - MCST
crMcstRating :: Lens' ContentRating (Maybe ContentRatingMcstRating)
crMcstRating
= lens _crMcstRating (\ s a -> s{_crMcstRating = a})
-- | The video\'s rating from the Bulgarian National Film Center.
crNfrcRating :: Lens' ContentRating (Maybe ContentRatingNfrcRating)
crNfrcRating
= lens _crNfrcRating (\ s a -> s{_crNfrcRating = a})
-- | The video\'s rating from France\'s Conseil supérieur de l’audiovisuel,
-- which rates broadcast content.
crCsaRating :: Lens' ContentRating (Maybe ContentRatingCsaRating)
crCsaRating
= lens _crCsaRating (\ s a -> s{_crCsaRating = a})
-- | The video\'s Ministerio de Cultura (Colombia) rating.
crMocRating :: Lens' ContentRating (Maybe ContentRatingMocRating)
crMocRating
= lens _crMocRating (\ s a -> s{_crMocRating = a})
-- | The video\'s Eirin (映倫) rating. Eirin is the Japanese rating system.
crEirinRating :: Lens' ContentRating (Maybe ContentRatingEirinRating)
crEirinRating
= lens _crEirinRating
(\ s a -> s{_crEirinRating = a})
-- | The video\'s Freiwillige Selbstkontrolle der Filmwirtschaft (FSK -
-- Germany) rating.
crFskRating :: Lens' ContentRating (Maybe ContentRatingFskRating)
crFskRating
= lens _crFskRating (\ s a -> s{_crFskRating = a})
-- | The video\'s rating in Estonia.
crEefilmRating :: Lens' ContentRating (Maybe ContentRatingEefilmRating)
crEefilmRating
= lens _crEefilmRating
(\ s a -> s{_crEefilmRating = a})
-- | The video\'s rating from the Hungarian Nemzeti Filmiroda, the Rating
-- Committee of the National Office of Film.
crRcnofRating :: Lens' ContentRating (Maybe ContentRatingRcnofRating)
crRcnofRating
= lens _crRcnofRating
(\ s a -> s{_crRcnofRating = a})
-- | The video\'s rating from Finland\'s Kansallinen Audiovisuaalinen
-- Instituutti (National Audiovisual Institute).
crMekuRating :: Lens' ContentRating (Maybe ContentRatingMekuRating)
crMekuRating
= lens _crMekuRating (\ s a -> s{_crMekuRating = a})
-- | The video\'s rating in Israel.
crIlfilmRating :: Lens' ContentRating (Maybe ContentRatingIlfilmRating)
crIlfilmRating
= lens _crIlfilmRating
(\ s a -> s{_crIlfilmRating = a})
-- | The video\'s Irish Film Classification Office (IFCO - Ireland) rating.
-- See the IFCO website for more information.
crIfcoRating :: Lens' ContentRating (Maybe ContentRatingIfcoRating)
crIfcoRating
= lens _crIfcoRating (\ s a -> s{_crIfcoRating = a})
-- | The video\'s rating in Poland.
crNbcplRating :: Lens' ContentRating (Maybe ContentRatingNbcplRating)
crNbcplRating
= lens _crNbcplRating
(\ s a -> s{_crNbcplRating = a})
-- | The video\'s rating in Greece.
crGrfilmRating :: Lens' ContentRating (Maybe ContentRatingGrfilmRating)
crGrfilmRating
= lens _crGrfilmRating
(\ s a -> s{_crGrfilmRating = a})
-- | The video\'s rating from Ireland\'s Raidió Teilifís Éireann.
crRteRating :: Lens' ContentRating (Maybe ContentRatingRteRating)
crRteRating
= lens _crRteRating (\ s a -> s{_crRteRating = a})
-- | The video\'s Australian Classification Board (ACB) or Australian
-- Communications and Media Authority (ACMA) rating. ACMA ratings are used
-- to classify children\'s television programming.
crAcbRating :: Lens' ContentRating (Maybe ContentRatingAcbRating)
crAcbRating
= lens _crAcbRating (\ s a -> s{_crAcbRating = a})
-- | Rating system for Canadian TV - Canadian TV Classification System The
-- video\'s rating from the Canadian Radio-Television and
-- Telecommunications Commission (CRTC) for Canadian English-language
-- broadcasts. For more information, see the Canadian Broadcast Standards
-- Council website.
crCatvRating :: Lens' ContentRating (Maybe ContentRatingCatvRating)
crCatvRating
= lens _crCatvRating (\ s a -> s{_crCatvRating = a})
-- | The video\'s rating from Singapore\'s Media Development Authority (MDA)
-- and, specifically, it\'s Board of Film Censors (BFC).
crMdaRating :: Lens' ContentRating (Maybe ContentRatingMdaRating)
crMdaRating
= lens _crMdaRating (\ s a -> s{_crMdaRating = a})
-- | The National Media Council ratings system for United Arab Emirates.
crNmcRating :: Lens' ContentRating (Maybe ContentRatingNmcRating)
crNmcRating
= lens _crNmcRating (\ s a -> s{_crNmcRating = a})
-- | The video\'s Departamento de Justiça, Classificação, Qualificação e
-- Títulos (DJCQT - Brazil) rating.
crDjctqRating :: Lens' ContentRating (Maybe ContentRatingDjctqRating)
crDjctqRating
= lens _crDjctqRating
(\ s a -> s{_crDjctqRating = a})
-- | The video\'s rating in Iceland.
crSmaisRating :: Lens' ContentRating (Maybe ContentRatingSmaisRating)
crSmaisRating
= lens _crSmaisRating
(\ s a -> s{_crSmaisRating = a})
-- | The video\'s rating from Luxembourg\'s Commission de surveillance de la
-- classification des films (CSCF).
crCscfRating :: Lens' ContentRating (Maybe ContentRatingCscfRating)
crCscfRating
= lens _crCscfRating (\ s a -> s{_crCscfRating = a})
-- | The video\'s TV Parental Guidelines (TVPG) rating.
crTvpgRating :: Lens' ContentRating (Maybe ContentRatingTvpgRating)
crTvpgRating
= lens _crTvpgRating (\ s a -> s{_crTvpgRating = a})
-- | The video\'s General Directorate of Radio, Television and Cinematography
-- (Mexico) rating.
crRtcRating :: Lens' ContentRating (Maybe ContentRatingRtcRating)
crRtcRating
= lens _crRtcRating (\ s a -> s{_crRtcRating = a})
-- | A rating that YouTube uses to identify age-restricted content.
crYtRating :: Lens' ContentRating (Maybe ContentRatingYtRating)
crYtRating
= lens _crYtRating (\ s a -> s{_crYtRating = a})
-- | The video\'s British Board of Film Classification (BBFC) rating.
crBbfcRating :: Lens' ContentRating (Maybe ContentRatingBbfcRating)
crBbfcRating
= lens _crBbfcRating (\ s a -> s{_crBbfcRating = a})
-- | The rating system for MENA countries, a clone of MPAA. It is needed to
-- prevent titles go live w\/o additional QC check, since some of them can
-- be inappropriate for the countries at all. See b\/33408548 for more
-- details.
crMenaMpaaRating :: Lens' ContentRating (Maybe ContentRatingMenaMpaaRating)
crMenaMpaaRating
= lens _crMenaMpaaRating
(\ s a -> s{_crMenaMpaaRating = a})
-- | The video\'s NICAM\/Kijkwijzer rating from the Nederlands Instituut voor
-- de Classificatie van Audiovisuele Media (Netherlands).
crKijkwijzerRating :: Lens' ContentRating (Maybe ContentRatingKijkwijzerRating)
crKijkwijzerRating
= lens _crKijkwijzerRating
(\ s a -> s{_crKijkwijzerRating = a})
-- | The video\'s rating from the Movie and Television Review and
-- Classification Board (Philippines).
crMtrcbRating :: Lens' ContentRating (Maybe ContentRatingMtrcbRating)
crMtrcbRating
= lens _crMtrcbRating
(\ s a -> s{_crMtrcbRating = a})
-- | The video\'s rating from Hong Kong\'s Office for Film, Newspaper and
-- Article Administration.
crFcoRating :: Lens' ContentRating (Maybe ContentRatingFcoRating)
crFcoRating
= lens _crFcoRating (\ s a -> s{_crFcoRating = a})
-- | The video\'s rating from the Commission de Contrôle des Films (Belgium).
crCicfRating :: Lens' ContentRating (Maybe ContentRatingCicfRating)
crCicfRating
= lens _crCicfRating (\ s a -> s{_crCicfRating = a})
-- | The video\'s rating in the Czech Republic.
crCzfilmRating :: Lens' ContentRating (Maybe ContentRatingCzfilmRating)
crCzfilmRating
= lens _crCzfilmRating
(\ s a -> s{_crCzfilmRating = a})
-- | The video\'s rating from the Maldives National Bureau of Classification.
crNbcRating :: Lens' ContentRating (Maybe ContentRatingNbcRating)
crNbcRating
= lens _crNbcRating (\ s a -> s{_crNbcRating = a})
-- | This property has been deprecated. Use the
-- contentDetails.contentRating.cncRating instead.
crFmocRating :: Lens' ContentRating (Maybe ContentRatingFmocRating)
crFmocRating
= lens _crFmocRating (\ s a -> s{_crFmocRating = a})
-- | The video\'s National Film Registry of the Russian Federation (MKRF -
-- Russia) rating.
crRussiaRating :: Lens' ContentRating (Maybe ContentRatingRussiaRating)
crRussiaRating
= lens _crRussiaRating
(\ s a -> s{_crRussiaRating = a})
-- | The video\'s rating in Egypt.
crEgfilmRating :: Lens' ContentRating (Maybe ContentRatingEgfilmRating)
crEgfilmRating
= lens _crEgfilmRating
(\ s a -> s{_crEgfilmRating = a})
-- | The video\'s rating in Venezuela.
crResorteviolenciaRating :: Lens' ContentRating (Maybe ContentRatingResorteviolenciaRating)
crResorteviolenciaRating
= lens _crResorteviolenciaRating
(\ s a -> s{_crResorteviolenciaRating = a})
-- | The video\'s rating from the Ministero dei Beni e delle Attività
-- Culturali e del Turismo (Italy).
crMibacRating :: Lens' ContentRating (Maybe ContentRatingMibacRating)
crMibacRating
= lens _crMibacRating
(\ s a -> s{_crMibacRating = a})
-- | The video\'s rating from Medietilsynet, the Norwegian Media Authority.
crMedietilsynetRating :: Lens' ContentRating (Maybe ContentRatingMedietilsynetRating)
crMedietilsynetRating
= lens _crMedietilsynetRating
(\ s a -> s{_crMedietilsynetRating = a})
-- | The video\'s rating from the Danish Film Institute\'s (Det Danske
-- Filminstitut) Media Council for Children and Young People.
crMccypRating :: Lens' ContentRating (Maybe ContentRatingMccypRating)
crMccypRating
= lens _crMccypRating
(\ s a -> s{_crMccypRating = a})
-- | The video\'s rating from the Nacionãlais Kino centrs (National Film
-- Centre of Latvia).
crNkclvRating :: Lens' ContentRating (Maybe ContentRatingNkclvRating)
crNkclvRating
= lens _crNkclvRating
(\ s a -> s{_crNkclvRating = a})
-- | The video\'s rating from South Africa\'s Film and Publication Board.
crFpbRating :: Lens' ContentRating (Maybe ContentRatingFpbRating)
crFpbRating
= lens _crFpbRating (\ s a -> s{_crFpbRating = a})
-- | The video\'s rating from Indonesia\'s Lembaga Sensor Film.
crLsfRating :: Lens' ContentRating (Maybe ContentRatingLsfRating)
crLsfRating
= lens _crLsfRating (\ s a -> s{_crLsfRating = a})
-- | The video\'s rating from Thailand\'s Board of Film and Video Censors.
crBfvcRating :: Lens' ContentRating (Maybe ContentRatingBfvcRating)
crBfvcRating
= lens _crBfvcRating (\ s a -> s{_crBfvcRating = a})
-- | The rating system for trailer, DVD, and Ad in the US. See
-- http:\/\/movielabs.com\/md\/ratings\/v2.3\/html\/US_MPAAT_Ratings.html.
crMpaatRating :: Lens' ContentRating (Maybe ContentRatingMpaatRating)
crMpaatRating
= lens _crMpaatRating
(\ s a -> s{_crMpaatRating = a})
-- | Rating system in Turkey - Evaluation and Classification Board of the
-- Ministry of Culture and Tourism
crEcbmctRating :: Lens' ContentRating (Maybe ContentRatingEcbmctRating)
crEcbmctRating
= lens _crEcbmctRating
(\ s a -> s{_crEcbmctRating = a})
-- | Rating system in France - Commission de classification cinematographique
crCNCRating :: Lens' ContentRating (Maybe ContentRatingCNCRating)
crCNCRating
= lens _crCNCRating (\ s a -> s{_crCNCRating = a})
-- | The video\'s rating in Slovakia.
crSkfilmRating :: Lens' ContentRating (Maybe ContentRatingSkfilmRating)
crSkfilmRating
= lens _crSkfilmRating
(\ s a -> s{_crSkfilmRating = a})
-- | The video\'s Office of Film and Literature Classification (OFLC - New
-- Zealand) rating.
crOflcRating :: Lens' ContentRating (Maybe ContentRatingOflcRating)
crOflcRating
= lens _crOflcRating (\ s a -> s{_crOflcRating = a})
-- | The video\'s Korea Media Rating Board (영상물등급위원회) rating. The
-- KMRB rates videos in South Korea.
crKmrbRating :: Lens' ContentRating (Maybe ContentRatingKmrbRating)
crKmrbRating
= lens _crKmrbRating (\ s a -> s{_crKmrbRating = a})
instance FromJSON ContentRating where
parseJSON
= withObject "ContentRating"
(\ o ->
ContentRating' <$>
(o .:? "fpbRatingReasons" .!= mempty) <*>
(o .:? "pefilmRating")
<*> (o .:? "cccRating")
<*> (o .:? "anatelRating")
<*> (o .:? "mpaaRating")
<*> (o .:? "cceRating")
<*> (o .:? "mccaaRating")
<*> (o .:? "chfilmRating")
<*> (o .:? "icaaRating")
<*> (o .:? "fcbmRating")
<*> (o .:? "bmukkRating")
<*> (o .:? "moctwRating")
<*> (o .:? "nfvcbRating")
<*> (o .:? "djctqRatingReasons" .!= mempty)
<*> (o .:? "agcomRating")
<*> (o .:? "cnaRating")
<*> (o .:? "catvfrRating")
<*> (o .:? "cbfcRating")
<*> (o .:? "kfcbRating")
<*> (o .:? "smsaRating")
<*> (o .:? "chvrsRating")
<*> (o .:? "incaaRating")
<*> (o .:? "mcstRating")
<*> (o .:? "nfrcRating")
<*> (o .:? "csaRating")
<*> (o .:? "mocRating")
<*> (o .:? "eirinRating")
<*> (o .:? "fskRating")
<*> (o .:? "eefilmRating")
<*> (o .:? "rcnofRating")
<*> (o .:? "mekuRating")
<*> (o .:? "ilfilmRating")
<*> (o .:? "ifcoRating")
<*> (o .:? "nbcplRating")
<*> (o .:? "grfilmRating")
<*> (o .:? "rteRating")
<*> (o .:? "acbRating")
<*> (o .:? "catvRating")
<*> (o .:? "mdaRating")
<*> (o .:? "nmcRating")
<*> (o .:? "djctqRating")
<*> (o .:? "smaisRating")
<*> (o .:? "cscfRating")
<*> (o .:? "tvpgRating")
<*> (o .:? "rtcRating")
<*> (o .:? "ytRating")
<*> (o .:? "bbfcRating")
<*> (o .:? "menaMpaaRating")
<*> (o .:? "kijkwijzerRating")
<*> (o .:? "mtrcbRating")
<*> (o .:? "fcoRating")
<*> (o .:? "cicfRating")
<*> (o .:? "czfilmRating")
<*> (o .:? "nbcRating")
<*> (o .:? "fmocRating")
<*> (o .:? "russiaRating")
<*> (o .:? "egfilmRating")
<*> (o .:? "resorteviolenciaRating")
<*> (o .:? "mibacRating")
<*> (o .:? "medietilsynetRating")
<*> (o .:? "mccypRating")
<*> (o .:? "nkclvRating")
<*> (o .:? "fpbRating")
<*> (o .:? "lsfRating")
<*> (o .:? "bfvcRating")
<*> (o .:? "mpaatRating")
<*> (o .:? "ecbmctRating")
<*> (o .:? "cncRating")
<*> (o .:? "skfilmRating")
<*> (o .:? "oflcRating")
<*> (o .:? "kmrbRating"))
instance ToJSON ContentRating where
toJSON ContentRating'{..}
= object
(catMaybes
[("fpbRatingReasons" .=) <$> _crFpbRatingReasons,
("pefilmRating" .=) <$> _crPefilmRating,
("cccRating" .=) <$> _crCccRating,
("anatelRating" .=) <$> _crAnatelRating,
("mpaaRating" .=) <$> _crMpaaRating,
("cceRating" .=) <$> _crCceRating,
("mccaaRating" .=) <$> _crMccaaRating,
("chfilmRating" .=) <$> _crChfilmRating,
("icaaRating" .=) <$> _crIcaaRating,
("fcbmRating" .=) <$> _crFcbmRating,
("bmukkRating" .=) <$> _crBmukkRating,
("moctwRating" .=) <$> _crMoctwRating,
("nfvcbRating" .=) <$> _crNfvcbRating,
("djctqRatingReasons" .=) <$> _crDjctqRatingReasons,
("agcomRating" .=) <$> _crAgcomRating,
("cnaRating" .=) <$> _crCnaRating,
("catvfrRating" .=) <$> _crCatvfrRating,
("cbfcRating" .=) <$> _crCbfcRating,
("kfcbRating" .=) <$> _crKfcbRating,
("smsaRating" .=) <$> _crSmsaRating,
("chvrsRating" .=) <$> _crChvrsRating,
("incaaRating" .=) <$> _crIncaaRating,
("mcstRating" .=) <$> _crMcstRating,
("nfrcRating" .=) <$> _crNfrcRating,
("csaRating" .=) <$> _crCsaRating,
("mocRating" .=) <$> _crMocRating,
("eirinRating" .=) <$> _crEirinRating,
("fskRating" .=) <$> _crFskRating,
("eefilmRating" .=) <$> _crEefilmRating,
("rcnofRating" .=) <$> _crRcnofRating,
("mekuRating" .=) <$> _crMekuRating,
("ilfilmRating" .=) <$> _crIlfilmRating,
("ifcoRating" .=) <$> _crIfcoRating,
("nbcplRating" .=) <$> _crNbcplRating,
("grfilmRating" .=) <$> _crGrfilmRating,
("rteRating" .=) <$> _crRteRating,
("acbRating" .=) <$> _crAcbRating,
("catvRating" .=) <$> _crCatvRating,
("mdaRating" .=) <$> _crMdaRating,
("nmcRating" .=) <$> _crNmcRating,
("djctqRating" .=) <$> _crDjctqRating,
("smaisRating" .=) <$> _crSmaisRating,
("cscfRating" .=) <$> _crCscfRating,
("tvpgRating" .=) <$> _crTvpgRating,
("rtcRating" .=) <$> _crRtcRating,
("ytRating" .=) <$> _crYtRating,
("bbfcRating" .=) <$> _crBbfcRating,
("menaMpaaRating" .=) <$> _crMenaMpaaRating,
("kijkwijzerRating" .=) <$> _crKijkwijzerRating,
("mtrcbRating" .=) <$> _crMtrcbRating,
("fcoRating" .=) <$> _crFcoRating,
("cicfRating" .=) <$> _crCicfRating,
("czfilmRating" .=) <$> _crCzfilmRating,
("nbcRating" .=) <$> _crNbcRating,
("fmocRating" .=) <$> _crFmocRating,
("russiaRating" .=) <$> _crRussiaRating,
("egfilmRating" .=) <$> _crEgfilmRating,
("resorteviolenciaRating" .=) <$>
_crResorteviolenciaRating,
("mibacRating" .=) <$> _crMibacRating,
("medietilsynetRating" .=) <$>
_crMedietilsynetRating,
("mccypRating" .=) <$> _crMccypRating,
("nkclvRating" .=) <$> _crNkclvRating,
("fpbRating" .=) <$> _crFpbRating,
("lsfRating" .=) <$> _crLsfRating,
("bfvcRating" .=) <$> _crBfvcRating,
("mpaatRating" .=) <$> _crMpaatRating,
("ecbmctRating" .=) <$> _crEcbmctRating,
("cncRating" .=) <$> _crCNCRating,
("skfilmRating" .=) <$> _crSkfilmRating,
("oflcRating" .=) <$> _crOflcRating,
("kmrbRating" .=) <$> _crKmrbRating])
-- | A *playlist* resource represents a YouTube playlist. A playlist is a
-- collection of videos that can be viewed sequentially and shared with
-- other users. A playlist can contain up to 200 videos, and YouTube does
-- not limit the number of playlists that each user creates. By default,
-- playlists are publicly visible to other users, but playlists can be
-- public or private. YouTube also uses playlists to identify special
-- collections of videos for a channel, such as: - uploaded videos -
-- favorite videos - positively rated (liked) videos - watch history -
-- watch later To be more specific, these lists are associated with a
-- channel, which is a collection of a person, group, or company\'s videos,
-- playlists, and other YouTube information. You can retrieve the playlist
-- IDs for each of these lists from the channel resource for a given
-- channel. You can then use the playlistItems.list method to retrieve any
-- of those lists. You can also add or remove items from those lists by
-- calling the playlistItems.insert and playlistItems.delete methods.
--
-- /See:/ 'playList' smart constructor.
data PlayList =
PlayList'
{ _plStatus :: !(Maybe PlayListStatus)
, _plEtag :: !(Maybe Text)
, _plSnippet :: !(Maybe PlayListSnippet)
, _plKind :: !Text
, _plContentDetails :: !(Maybe PlayListContentDetails)
, _plId :: !(Maybe Text)
, _plLocalizations :: !(Maybe PlayListLocalizations)
, _plPlayer :: !(Maybe PlayListPlayer)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plStatus'
--
-- * 'plEtag'
--
-- * 'plSnippet'
--
-- * 'plKind'
--
-- * 'plContentDetails'
--
-- * 'plId'
--
-- * 'plLocalizations'
--
-- * 'plPlayer'
playList
:: PlayList
playList =
PlayList'
{ _plStatus = Nothing
, _plEtag = Nothing
, _plSnippet = Nothing
, _plKind = "youtube#playlist"
, _plContentDetails = Nothing
, _plId = Nothing
, _plLocalizations = Nothing
, _plPlayer = Nothing
}
-- | The status object contains status information for the playlist.
plStatus :: Lens' PlayList (Maybe PlayListStatus)
plStatus = lens _plStatus (\ s a -> s{_plStatus = a})
-- | Etag of this resource.
plEtag :: Lens' PlayList (Maybe Text)
plEtag = lens _plEtag (\ s a -> s{_plEtag = a})
-- | The snippet object contains basic details about the playlist, such as
-- its title and description.
plSnippet :: Lens' PlayList (Maybe PlayListSnippet)
plSnippet
= lens _plSnippet (\ s a -> s{_plSnippet = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#playlist\".
plKind :: Lens' PlayList Text
plKind = lens _plKind (\ s a -> s{_plKind = a})
-- | The contentDetails object contains information like video count.
plContentDetails :: Lens' PlayList (Maybe PlayListContentDetails)
plContentDetails
= lens _plContentDetails
(\ s a -> s{_plContentDetails = a})
-- | The ID that YouTube uses to uniquely identify the playlist.
plId :: Lens' PlayList (Maybe Text)
plId = lens _plId (\ s a -> s{_plId = a})
-- | Localizations for different languages
plLocalizations :: Lens' PlayList (Maybe PlayListLocalizations)
plLocalizations
= lens _plLocalizations
(\ s a -> s{_plLocalizations = a})
-- | The player object contains information that you would use to play the
-- playlist in an embedded player.
plPlayer :: Lens' PlayList (Maybe PlayListPlayer)
plPlayer = lens _plPlayer (\ s a -> s{_plPlayer = a})
instance FromJSON PlayList where
parseJSON
= withObject "PlayList"
(\ o ->
PlayList' <$>
(o .:? "status") <*> (o .:? "etag") <*>
(o .:? "snippet")
<*> (o .:? "kind" .!= "youtube#playlist")
<*> (o .:? "contentDetails")
<*> (o .:? "id")
<*> (o .:? "localizations")
<*> (o .:? "player"))
instance ToJSON PlayList where
toJSON PlayList'{..}
= object
(catMaybes
[("status" .=) <$> _plStatus,
("etag" .=) <$> _plEtag,
("snippet" .=) <$> _plSnippet,
Just ("kind" .= _plKind),
("contentDetails" .=) <$> _plContentDetails,
("id" .=) <$> _plId,
("localizations" .=) <$> _plLocalizations,
("player" .=) <$> _plPlayer])
-- | Branding properties for the channel view.
--
-- /See:/ 'channelSettings' smart constructor.
data ChannelSettings =
ChannelSettings'
{ _cShowRelatedChannels :: !(Maybe Bool)
, _cDefaultTab :: !(Maybe Text)
, _cFeaturedChannelsTitle :: !(Maybe Text)
, _cCountry :: !(Maybe Text)
, _cProFileColor :: !(Maybe Text)
, _cModerateComments :: !(Maybe Bool)
, _cKeywords :: !(Maybe Text)
, _cUnsubscribedTrailer :: !(Maybe Text)
, _cTrackingAnalyticsAccountId :: !(Maybe Text)
, _cFeaturedChannelsURLs :: !(Maybe [Text])
, _cShowBrowseView :: !(Maybe Bool)
, _cTitle :: !(Maybe Text)
, _cDescription :: !(Maybe Text)
, _cDefaultLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cShowRelatedChannels'
--
-- * 'cDefaultTab'
--
-- * 'cFeaturedChannelsTitle'
--
-- * 'cCountry'
--
-- * 'cProFileColor'
--
-- * 'cModerateComments'
--
-- * 'cKeywords'
--
-- * 'cUnsubscribedTrailer'
--
-- * 'cTrackingAnalyticsAccountId'
--
-- * 'cFeaturedChannelsURLs'
--
-- * 'cShowBrowseView'
--
-- * 'cTitle'
--
-- * 'cDescription'
--
-- * 'cDefaultLanguage'
channelSettings
:: ChannelSettings
channelSettings =
ChannelSettings'
{ _cShowRelatedChannels = Nothing
, _cDefaultTab = Nothing
, _cFeaturedChannelsTitle = Nothing
, _cCountry = Nothing
, _cProFileColor = Nothing
, _cModerateComments = Nothing
, _cKeywords = Nothing
, _cUnsubscribedTrailer = Nothing
, _cTrackingAnalyticsAccountId = Nothing
, _cFeaturedChannelsURLs = Nothing
, _cShowBrowseView = Nothing
, _cTitle = Nothing
, _cDescription = Nothing
, _cDefaultLanguage = Nothing
}
-- | Whether related channels should be proposed.
cShowRelatedChannels :: Lens' ChannelSettings (Maybe Bool)
cShowRelatedChannels
= lens _cShowRelatedChannels
(\ s a -> s{_cShowRelatedChannels = a})
-- | Which content tab users should see when viewing the channel.
cDefaultTab :: Lens' ChannelSettings (Maybe Text)
cDefaultTab
= lens _cDefaultTab (\ s a -> s{_cDefaultTab = a})
-- | Title for the featured channels tab.
cFeaturedChannelsTitle :: Lens' ChannelSettings (Maybe Text)
cFeaturedChannelsTitle
= lens _cFeaturedChannelsTitle
(\ s a -> s{_cFeaturedChannelsTitle = a})
-- | The country of the channel.
cCountry :: Lens' ChannelSettings (Maybe Text)
cCountry = lens _cCountry (\ s a -> s{_cCountry = a})
-- | A prominent color that can be rendered on this channel page.
cProFileColor :: Lens' ChannelSettings (Maybe Text)
cProFileColor
= lens _cProFileColor
(\ s a -> s{_cProFileColor = a})
-- | Whether user-submitted comments left on the channel page need to be
-- approved by the channel owner to be publicly visible.
cModerateComments :: Lens' ChannelSettings (Maybe Bool)
cModerateComments
= lens _cModerateComments
(\ s a -> s{_cModerateComments = a})
-- | Lists keywords associated with the channel, comma-separated.
cKeywords :: Lens' ChannelSettings (Maybe Text)
cKeywords
= lens _cKeywords (\ s a -> s{_cKeywords = a})
-- | The trailer of the channel, for users that are not subscribers.
cUnsubscribedTrailer :: Lens' ChannelSettings (Maybe Text)
cUnsubscribedTrailer
= lens _cUnsubscribedTrailer
(\ s a -> s{_cUnsubscribedTrailer = a})
-- | The ID for a Google Analytics account to track and measure traffic to
-- the channels.
cTrackingAnalyticsAccountId :: Lens' ChannelSettings (Maybe Text)
cTrackingAnalyticsAccountId
= lens _cTrackingAnalyticsAccountId
(\ s a -> s{_cTrackingAnalyticsAccountId = a})
-- | The list of featured channels.
cFeaturedChannelsURLs :: Lens' ChannelSettings [Text]
cFeaturedChannelsURLs
= lens _cFeaturedChannelsURLs
(\ s a -> s{_cFeaturedChannelsURLs = a})
. _Default
. _Coerce
-- | Whether the tab to browse the videos should be displayed.
cShowBrowseView :: Lens' ChannelSettings (Maybe Bool)
cShowBrowseView
= lens _cShowBrowseView
(\ s a -> s{_cShowBrowseView = a})
-- | Specifies the channel title.
cTitle :: Lens' ChannelSettings (Maybe Text)
cTitle = lens _cTitle (\ s a -> s{_cTitle = a})
-- | Specifies the channel description.
cDescription :: Lens' ChannelSettings (Maybe Text)
cDescription
= lens _cDescription (\ s a -> s{_cDescription = a})
cDefaultLanguage :: Lens' ChannelSettings (Maybe Text)
cDefaultLanguage
= lens _cDefaultLanguage
(\ s a -> s{_cDefaultLanguage = a})
instance FromJSON ChannelSettings where
parseJSON
= withObject "ChannelSettings"
(\ o ->
ChannelSettings' <$>
(o .:? "showRelatedChannels") <*>
(o .:? "defaultTab")
<*> (o .:? "featuredChannelsTitle")
<*> (o .:? "country")
<*> (o .:? "profileColor")
<*> (o .:? "moderateComments")
<*> (o .:? "keywords")
<*> (o .:? "unsubscribedTrailer")
<*> (o .:? "trackingAnalyticsAccountId")
<*> (o .:? "featuredChannelsUrls" .!= mempty)
<*> (o .:? "showBrowseView")
<*> (o .:? "title")
<*> (o .:? "description")
<*> (o .:? "defaultLanguage"))
instance ToJSON ChannelSettings where
toJSON ChannelSettings'{..}
= object
(catMaybes
[("showRelatedChannels" .=) <$>
_cShowRelatedChannels,
("defaultTab" .=) <$> _cDefaultTab,
("featuredChannelsTitle" .=) <$>
_cFeaturedChannelsTitle,
("country" .=) <$> _cCountry,
("profileColor" .=) <$> _cProFileColor,
("moderateComments" .=) <$> _cModerateComments,
("keywords" .=) <$> _cKeywords,
("unsubscribedTrailer" .=) <$> _cUnsubscribedTrailer,
("trackingAnalyticsAccountId" .=) <$>
_cTrackingAnalyticsAccountId,
("featuredChannelsUrls" .=) <$>
_cFeaturedChannelsURLs,
("showBrowseView" .=) <$> _cShowBrowseView,
("title" .=) <$> _cTitle,
("description" .=) <$> _cDescription,
("defaultLanguage" .=) <$> _cDefaultLanguage])
-- | Basic details about a subscription, including title, description and
-- thumbnails of the subscribed item.
--
-- /See:/ 'subscriptionSnippet' smart constructor.
data SubscriptionSnippet =
SubscriptionSnippet'
{ _ssResourceId :: !(Maybe ResourceId)
, _ssPublishedAt :: !(Maybe DateTime')
, _ssChannelTitle :: !(Maybe Text)
, _ssChannelId :: !(Maybe Text)
, _ssThumbnails :: !(Maybe ThumbnailDetails)
, _ssTitle :: !(Maybe Text)
, _ssDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SubscriptionSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ssResourceId'
--
-- * 'ssPublishedAt'
--
-- * 'ssChannelTitle'
--
-- * 'ssChannelId'
--
-- * 'ssThumbnails'
--
-- * 'ssTitle'
--
-- * 'ssDescription'
subscriptionSnippet
:: SubscriptionSnippet
subscriptionSnippet =
SubscriptionSnippet'
{ _ssResourceId = Nothing
, _ssPublishedAt = Nothing
, _ssChannelTitle = Nothing
, _ssChannelId = Nothing
, _ssThumbnails = Nothing
, _ssTitle = Nothing
, _ssDescription = Nothing
}
-- | The id object contains information about the channel that the user
-- subscribed to.
ssResourceId :: Lens' SubscriptionSnippet (Maybe ResourceId)
ssResourceId
= lens _ssResourceId (\ s a -> s{_ssResourceId = a})
-- | The date and time that the subscription was created.
ssPublishedAt :: Lens' SubscriptionSnippet (Maybe UTCTime)
ssPublishedAt
= lens _ssPublishedAt
(\ s a -> s{_ssPublishedAt = a})
. mapping _DateTime
-- | Channel title for the channel that the subscription belongs to.
ssChannelTitle :: Lens' SubscriptionSnippet (Maybe Text)
ssChannelTitle
= lens _ssChannelTitle
(\ s a -> s{_ssChannelTitle = a})
-- | The ID that YouTube uses to uniquely identify the subscriber\'s channel.
ssChannelId :: Lens' SubscriptionSnippet (Maybe Text)
ssChannelId
= lens _ssChannelId (\ s a -> s{_ssChannelId = a})
-- | A map of thumbnail images associated with the video. For each object in
-- the map, the key is the name of the thumbnail image, and the value is an
-- object that contains other information about the thumbnail.
ssThumbnails :: Lens' SubscriptionSnippet (Maybe ThumbnailDetails)
ssThumbnails
= lens _ssThumbnails (\ s a -> s{_ssThumbnails = a})
-- | The subscription\'s title.
ssTitle :: Lens' SubscriptionSnippet (Maybe Text)
ssTitle = lens _ssTitle (\ s a -> s{_ssTitle = a})
-- | The subscription\'s details.
ssDescription :: Lens' SubscriptionSnippet (Maybe Text)
ssDescription
= lens _ssDescription
(\ s a -> s{_ssDescription = a})
instance FromJSON SubscriptionSnippet where
parseJSON
= withObject "SubscriptionSnippet"
(\ o ->
SubscriptionSnippet' <$>
(o .:? "resourceId") <*> (o .:? "publishedAt") <*>
(o .:? "channelTitle")
<*> (o .:? "channelId")
<*> (o .:? "thumbnails")
<*> (o .:? "title")
<*> (o .:? "description"))
instance ToJSON SubscriptionSnippet where
toJSON SubscriptionSnippet'{..}
= object
(catMaybes
[("resourceId" .=) <$> _ssResourceId,
("publishedAt" .=) <$> _ssPublishedAt,
("channelTitle" .=) <$> _ssChannelTitle,
("channelId" .=) <$> _ssChannelId,
("thumbnails" .=) <$> _ssThumbnails,
("title" .=) <$> _ssTitle,
("description" .=) <$> _ssDescription])
-- | Details about the live streaming metadata.
--
-- /See:/ 'videoLiveStreamingDetails' smart constructor.
data VideoLiveStreamingDetails =
VideoLiveStreamingDetails'
{ _vlsdActualEndTime :: !(Maybe DateTime')
, _vlsdConcurrentViewers :: !(Maybe (Textual Word64))
, _vlsdScheduledEndTime :: !(Maybe DateTime')
, _vlsdScheduledStartTime :: !(Maybe DateTime')
, _vlsdActualStartTime :: !(Maybe DateTime')
, _vlsdActiveLiveChatId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoLiveStreamingDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vlsdActualEndTime'
--
-- * 'vlsdConcurrentViewers'
--
-- * 'vlsdScheduledEndTime'
--
-- * 'vlsdScheduledStartTime'
--
-- * 'vlsdActualStartTime'
--
-- * 'vlsdActiveLiveChatId'
videoLiveStreamingDetails
:: VideoLiveStreamingDetails
videoLiveStreamingDetails =
VideoLiveStreamingDetails'
{ _vlsdActualEndTime = Nothing
, _vlsdConcurrentViewers = Nothing
, _vlsdScheduledEndTime = Nothing
, _vlsdScheduledStartTime = Nothing
, _vlsdActualStartTime = Nothing
, _vlsdActiveLiveChatId = Nothing
}
-- | The time that the broadcast actually ended. This value will not be
-- available until the broadcast is over.
vlsdActualEndTime :: Lens' VideoLiveStreamingDetails (Maybe UTCTime)
vlsdActualEndTime
= lens _vlsdActualEndTime
(\ s a -> s{_vlsdActualEndTime = a})
. mapping _DateTime
-- | The number of viewers currently watching the broadcast. The property and
-- its value will be present if the broadcast has current viewers and the
-- broadcast owner has not hidden the viewcount for the video. Note that
-- YouTube stops tracking the number of concurrent viewers for a broadcast
-- when the broadcast ends. So, this property would not identify the number
-- of viewers watching an archived video of a live broadcast that already
-- ended.
vlsdConcurrentViewers :: Lens' VideoLiveStreamingDetails (Maybe Word64)
vlsdConcurrentViewers
= lens _vlsdConcurrentViewers
(\ s a -> s{_vlsdConcurrentViewers = a})
. mapping _Coerce
-- | The time that the broadcast is scheduled to end. If the value is empty
-- or the property is not present, then the broadcast is scheduled to
-- contiue indefinitely.
vlsdScheduledEndTime :: Lens' VideoLiveStreamingDetails (Maybe UTCTime)
vlsdScheduledEndTime
= lens _vlsdScheduledEndTime
(\ s a -> s{_vlsdScheduledEndTime = a})
. mapping _DateTime
-- | The time that the broadcast is scheduled to begin.
vlsdScheduledStartTime :: Lens' VideoLiveStreamingDetails (Maybe UTCTime)
vlsdScheduledStartTime
= lens _vlsdScheduledStartTime
(\ s a -> s{_vlsdScheduledStartTime = a})
. mapping _DateTime
-- | The time that the broadcast actually started. This value will not be
-- available until the broadcast begins.
vlsdActualStartTime :: Lens' VideoLiveStreamingDetails (Maybe UTCTime)
vlsdActualStartTime
= lens _vlsdActualStartTime
(\ s a -> s{_vlsdActualStartTime = a})
. mapping _DateTime
-- | The ID of the currently active live chat attached to this video. This
-- field is filled only if the video is a currently live broadcast that has
-- live chat. Once the broadcast transitions to complete this field will be
-- removed and the live chat closed down. For persistent broadcasts that
-- live chat id will no longer be tied to this video but rather to the new
-- video being displayed at the persistent page.
vlsdActiveLiveChatId :: Lens' VideoLiveStreamingDetails (Maybe Text)
vlsdActiveLiveChatId
= lens _vlsdActiveLiveChatId
(\ s a -> s{_vlsdActiveLiveChatId = a})
instance FromJSON VideoLiveStreamingDetails where
parseJSON
= withObject "VideoLiveStreamingDetails"
(\ o ->
VideoLiveStreamingDetails' <$>
(o .:? "actualEndTime") <*>
(o .:? "concurrentViewers")
<*> (o .:? "scheduledEndTime")
<*> (o .:? "scheduledStartTime")
<*> (o .:? "actualStartTime")
<*> (o .:? "activeLiveChatId"))
instance ToJSON VideoLiveStreamingDetails where
toJSON VideoLiveStreamingDetails'{..}
= object
(catMaybes
[("actualEndTime" .=) <$> _vlsdActualEndTime,
("concurrentViewers" .=) <$> _vlsdConcurrentViewers,
("scheduledEndTime" .=) <$> _vlsdScheduledEndTime,
("scheduledStartTime" .=) <$>
_vlsdScheduledStartTime,
("actualStartTime" .=) <$> _vlsdActualStartTime,
("activeLiveChatId" .=) <$> _vlsdActiveLiveChatId])
-- | Details about a resource which is being promoted.
--
-- /See:/ 'activityContentDetailsPromotedItem' smart constructor.
data ActivityContentDetailsPromotedItem =
ActivityContentDetailsPromotedItem'
{ _acdpiDestinationURL :: !(Maybe Text)
, _acdpiClickTrackingURL :: !(Maybe Text)
, _acdpiForecastingURL :: !(Maybe [Text])
, _acdpiDescriptionText :: !(Maybe Text)
, _acdpiCtaType :: !(Maybe ActivityContentDetailsPromotedItemCtaType)
, _acdpiVideoId :: !(Maybe Text)
, _acdpiAdTag :: !(Maybe Text)
, _acdpiCreativeViewURL :: !(Maybe Text)
, _acdpiImpressionURL :: !(Maybe [Text])
, _acdpiCustomCtaButtonText :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ActivityContentDetailsPromotedItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdpiDestinationURL'
--
-- * 'acdpiClickTrackingURL'
--
-- * 'acdpiForecastingURL'
--
-- * 'acdpiDescriptionText'
--
-- * 'acdpiCtaType'
--
-- * 'acdpiVideoId'
--
-- * 'acdpiAdTag'
--
-- * 'acdpiCreativeViewURL'
--
-- * 'acdpiImpressionURL'
--
-- * 'acdpiCustomCtaButtonText'
activityContentDetailsPromotedItem
:: ActivityContentDetailsPromotedItem
activityContentDetailsPromotedItem =
ActivityContentDetailsPromotedItem'
{ _acdpiDestinationURL = Nothing
, _acdpiClickTrackingURL = Nothing
, _acdpiForecastingURL = Nothing
, _acdpiDescriptionText = Nothing
, _acdpiCtaType = Nothing
, _acdpiVideoId = Nothing
, _acdpiAdTag = Nothing
, _acdpiCreativeViewURL = Nothing
, _acdpiImpressionURL = Nothing
, _acdpiCustomCtaButtonText = Nothing
}
-- | The URL the client should direct the user to, if the user chooses to
-- visit the advertiser\'s website.
acdpiDestinationURL :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiDestinationURL
= lens _acdpiDestinationURL
(\ s a -> s{_acdpiDestinationURL = a})
-- | The URL the client should ping to indicate that the user clicked through
-- on this promoted item.
acdpiClickTrackingURL :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiClickTrackingURL
= lens _acdpiClickTrackingURL
(\ s a -> s{_acdpiClickTrackingURL = a})
-- | The list of forecasting URLs. The client should ping all of these URLs
-- when a promoted item is not available, to indicate that a promoted item
-- could have been shown.
acdpiForecastingURL :: Lens' ActivityContentDetailsPromotedItem [Text]
acdpiForecastingURL
= lens _acdpiForecastingURL
(\ s a -> s{_acdpiForecastingURL = a})
. _Default
. _Coerce
-- | The text description to accompany the promoted item.
acdpiDescriptionText :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiDescriptionText
= lens _acdpiDescriptionText
(\ s a -> s{_acdpiDescriptionText = a})
-- | The type of call-to-action, a message to the user indicating action that
-- can be taken.
acdpiCtaType :: Lens' ActivityContentDetailsPromotedItem (Maybe ActivityContentDetailsPromotedItemCtaType)
acdpiCtaType
= lens _acdpiCtaType (\ s a -> s{_acdpiCtaType = a})
-- | The ID that YouTube uses to uniquely identify the promoted video.
acdpiVideoId :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiVideoId
= lens _acdpiVideoId (\ s a -> s{_acdpiVideoId = a})
-- | The URL the client should fetch to request a promoted item.
acdpiAdTag :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiAdTag
= lens _acdpiAdTag (\ s a -> s{_acdpiAdTag = a})
-- | The URL the client should ping to indicate that the user was shown this
-- promoted item.
acdpiCreativeViewURL :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiCreativeViewURL
= lens _acdpiCreativeViewURL
(\ s a -> s{_acdpiCreativeViewURL = a})
-- | The list of impression URLs. The client should ping all of these URLs to
-- indicate that the user was shown this promoted item.
acdpiImpressionURL :: Lens' ActivityContentDetailsPromotedItem [Text]
acdpiImpressionURL
= lens _acdpiImpressionURL
(\ s a -> s{_acdpiImpressionURL = a})
. _Default
. _Coerce
-- | The custom call-to-action button text. If specified, it will override
-- the default button text for the cta_type.
acdpiCustomCtaButtonText :: Lens' ActivityContentDetailsPromotedItem (Maybe Text)
acdpiCustomCtaButtonText
= lens _acdpiCustomCtaButtonText
(\ s a -> s{_acdpiCustomCtaButtonText = a})
instance FromJSON ActivityContentDetailsPromotedItem
where
parseJSON
= withObject "ActivityContentDetailsPromotedItem"
(\ o ->
ActivityContentDetailsPromotedItem' <$>
(o .:? "destinationUrl") <*>
(o .:? "clickTrackingUrl")
<*> (o .:? "forecastingUrl" .!= mempty)
<*> (o .:? "descriptionText")
<*> (o .:? "ctaType")
<*> (o .:? "videoId")
<*> (o .:? "adTag")
<*> (o .:? "creativeViewUrl")
<*> (o .:? "impressionUrl" .!= mempty)
<*> (o .:? "customCtaButtonText"))
instance ToJSON ActivityContentDetailsPromotedItem
where
toJSON ActivityContentDetailsPromotedItem'{..}
= object
(catMaybes
[("destinationUrl" .=) <$> _acdpiDestinationURL,
("clickTrackingUrl" .=) <$> _acdpiClickTrackingURL,
("forecastingUrl" .=) <$> _acdpiForecastingURL,
("descriptionText" .=) <$> _acdpiDescriptionText,
("ctaType" .=) <$> _acdpiCtaType,
("videoId" .=) <$> _acdpiVideoId,
("adTag" .=) <$> _acdpiAdTag,
("creativeViewUrl" .=) <$> _acdpiCreativeViewURL,
("impressionUrl" .=) <$> _acdpiImpressionURL,
("customCtaButtonText" .=) <$>
_acdpiCustomCtaButtonText])
-- | Geographical coordinates of a point, in WGS84.
--
-- /See:/ 'geoPoint' smart constructor.
data GeoPoint =
GeoPoint'
{ _gpLatitude :: !(Maybe (Textual Double))
, _gpAltitude :: !(Maybe (Textual Double))
, _gpLongitude :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GeoPoint' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gpLatitude'
--
-- * 'gpAltitude'
--
-- * 'gpLongitude'
geoPoint
:: GeoPoint
geoPoint =
GeoPoint'
{_gpLatitude = Nothing, _gpAltitude = Nothing, _gpLongitude = Nothing}
-- | Latitude in degrees.
gpLatitude :: Lens' GeoPoint (Maybe Double)
gpLatitude
= lens _gpLatitude (\ s a -> s{_gpLatitude = a}) .
mapping _Coerce
-- | Altitude above the reference ellipsoid, in meters.
gpAltitude :: Lens' GeoPoint (Maybe Double)
gpAltitude
= lens _gpAltitude (\ s a -> s{_gpAltitude = a}) .
mapping _Coerce
-- | Longitude in degrees.
gpLongitude :: Lens' GeoPoint (Maybe Double)
gpLongitude
= lens _gpLongitude (\ s a -> s{_gpLongitude = a}) .
mapping _Coerce
instance FromJSON GeoPoint where
parseJSON
= withObject "GeoPoint"
(\ o ->
GeoPoint' <$>
(o .:? "latitude") <*> (o .:? "altitude") <*>
(o .:? "longitude"))
instance ToJSON GeoPoint where
toJSON GeoPoint'{..}
= object
(catMaybes
[("latitude" .=) <$> _gpLatitude,
("altitude" .=) <$> _gpAltitude,
("longitude" .=) <$> _gpLongitude])
-- | Comments written in (direct or indirect) reply to the top level comment.
--
-- /See:/ 'commentThreadReplies' smart constructor.
newtype CommentThreadReplies =
CommentThreadReplies'
{ _ctrComments :: Maybe [Comment]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CommentThreadReplies' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctrComments'
commentThreadReplies
:: CommentThreadReplies
commentThreadReplies = CommentThreadReplies' {_ctrComments = Nothing}
-- | A limited number of replies. Unless the number of replies returned
-- equals total_reply_count in the snippet the returned replies are only a
-- subset of the total number of replies.
ctrComments :: Lens' CommentThreadReplies [Comment]
ctrComments
= lens _ctrComments (\ s a -> s{_ctrComments = a}) .
_Default
. _Coerce
instance FromJSON CommentThreadReplies where
parseJSON
= withObject "CommentThreadReplies"
(\ o ->
CommentThreadReplies' <$>
(o .:? "comments" .!= mempty))
instance ToJSON CommentThreadReplies where
toJSON CommentThreadReplies'{..}
= object
(catMaybes [("comments" .=) <$> _ctrComments])
-- | ChannelSection localization setting
--
-- /See:/ 'channelSectionLocalization' smart constructor.
newtype ChannelSectionLocalization =
ChannelSectionLocalization'
{ _cslTitle :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelSectionLocalization' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cslTitle'
channelSectionLocalization
:: ChannelSectionLocalization
channelSectionLocalization = ChannelSectionLocalization' {_cslTitle = Nothing}
-- | The localized strings for channel section\'s title.
cslTitle :: Lens' ChannelSectionLocalization (Maybe Text)
cslTitle = lens _cslTitle (\ s a -> s{_cslTitle = a})
instance FromJSON ChannelSectionLocalization where
parseJSON
= withObject "ChannelSectionLocalization"
(\ o ->
ChannelSectionLocalization' <$> (o .:? "title"))
instance ToJSON ChannelSectionLocalization where
toJSON ChannelSectionLocalization'{..}
= object (catMaybes [("title" .=) <$> _cslTitle])
--
-- /See:/ 'videoAbuseReportSecondaryReason' smart constructor.
data VideoAbuseReportSecondaryReason =
VideoAbuseReportSecondaryReason'
{ _varsrId :: !(Maybe Text)
, _varsrLabel :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoAbuseReportSecondaryReason' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'varsrId'
--
-- * 'varsrLabel'
videoAbuseReportSecondaryReason
:: VideoAbuseReportSecondaryReason
videoAbuseReportSecondaryReason =
VideoAbuseReportSecondaryReason' {_varsrId = Nothing, _varsrLabel = Nothing}
-- | The ID of this abuse report secondary reason.
varsrId :: Lens' VideoAbuseReportSecondaryReason (Maybe Text)
varsrId = lens _varsrId (\ s a -> s{_varsrId = a})
-- | The localized label for this abuse report secondary reason.
varsrLabel :: Lens' VideoAbuseReportSecondaryReason (Maybe Text)
varsrLabel
= lens _varsrLabel (\ s a -> s{_varsrLabel = a})
instance FromJSON VideoAbuseReportSecondaryReason
where
parseJSON
= withObject "VideoAbuseReportSecondaryReason"
(\ o ->
VideoAbuseReportSecondaryReason' <$>
(o .:? "id") <*> (o .:? "label"))
instance ToJSON VideoAbuseReportSecondaryReason where
toJSON VideoAbuseReportSecondaryReason'{..}
= object
(catMaybes
[("id" .=) <$> _varsrId,
("label" .=) <$> _varsrLabel])
-- | The contentOwnerDetails object encapsulates channel data that is
-- relevant for YouTube Partners linked with the channel.
--
-- /See:/ 'channelContentOwnerDetails' smart constructor.
data ChannelContentOwnerDetails =
ChannelContentOwnerDetails'
{ _ccodTimeLinked :: !(Maybe DateTime')
, _ccodContentOwner :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ChannelContentOwnerDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccodTimeLinked'
--
-- * 'ccodContentOwner'
channelContentOwnerDetails
:: ChannelContentOwnerDetails
channelContentOwnerDetails =
ChannelContentOwnerDetails'
{_ccodTimeLinked = Nothing, _ccodContentOwner = Nothing}
-- | The date and time when the channel was linked to the content owner.
ccodTimeLinked :: Lens' ChannelContentOwnerDetails (Maybe UTCTime)
ccodTimeLinked
= lens _ccodTimeLinked
(\ s a -> s{_ccodTimeLinked = a})
. mapping _DateTime
-- | The ID of the content owner linked to the channel.
ccodContentOwner :: Lens' ChannelContentOwnerDetails (Maybe Text)
ccodContentOwner
= lens _ccodContentOwner
(\ s a -> s{_ccodContentOwner = a})
instance FromJSON ChannelContentOwnerDetails where
parseJSON
= withObject "ChannelContentOwnerDetails"
(\ o ->
ChannelContentOwnerDetails' <$>
(o .:? "timeLinked") <*> (o .:? "contentOwner"))
instance ToJSON ChannelContentOwnerDetails where
toJSON ChannelContentOwnerDetails'{..}
= object
(catMaybes
[("timeLinked" .=) <$> _ccodTimeLinked,
("contentOwner" .=) <$> _ccodContentOwner])
-- | Basic details about an i18n language, such as language code and
-- human-readable name.
--
-- /See:/ 'i18nLanguageSnippet' smart constructor.
data I18nLanguageSnippet =
I18nLanguageSnippet'
{ _ilsHl :: !(Maybe Text)
, _ilsName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nLanguageSnippet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ilsHl'
--
-- * 'ilsName'
i18nLanguageSnippet
:: I18nLanguageSnippet
i18nLanguageSnippet =
I18nLanguageSnippet' {_ilsHl = Nothing, _ilsName = Nothing}
-- | A short BCP-47 code that uniquely identifies a language.
ilsHl :: Lens' I18nLanguageSnippet (Maybe Text)
ilsHl = lens _ilsHl (\ s a -> s{_ilsHl = a})
-- | The human-readable name of the language in the language itself.
ilsName :: Lens' I18nLanguageSnippet (Maybe Text)
ilsName = lens _ilsName (\ s a -> s{_ilsName = a})
instance FromJSON I18nLanguageSnippet where
parseJSON
= withObject "I18nLanguageSnippet"
(\ o ->
I18nLanguageSnippet' <$>
(o .:? "hl") <*> (o .:? "name"))
instance ToJSON I18nLanguageSnippet where
toJSON I18nLanguageSnippet'{..}
= object
(catMaybes
[("hl" .=) <$> _ilsHl, ("name" .=) <$> _ilsName])
--
-- /See:/ 'memberListResponse' smart constructor.
data MemberListResponse =
MemberListResponse'
{ _mlrEtag :: !(Maybe Text)
, _mlrTokenPagination :: !(Maybe TokenPagination)
, _mlrNextPageToken :: !(Maybe Text)
, _mlrPageInfo :: !(Maybe PageInfo)
, _mlrKind :: !Text
, _mlrItems :: !(Maybe [Member])
, _mlrVisitorId :: !(Maybe Text)
, _mlrEventId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MemberListResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mlrEtag'
--
-- * 'mlrTokenPagination'
--
-- * 'mlrNextPageToken'
--
-- * 'mlrPageInfo'
--
-- * 'mlrKind'
--
-- * 'mlrItems'
--
-- * 'mlrVisitorId'
--
-- * 'mlrEventId'
memberListResponse
:: MemberListResponse
memberListResponse =
MemberListResponse'
{ _mlrEtag = Nothing
, _mlrTokenPagination = Nothing
, _mlrNextPageToken = Nothing
, _mlrPageInfo = Nothing
, _mlrKind = "youtube#memberListResponse"
, _mlrItems = Nothing
, _mlrVisitorId = Nothing
, _mlrEventId = Nothing
}
-- | Etag of this resource.
mlrEtag :: Lens' MemberListResponse (Maybe Text)
mlrEtag = lens _mlrEtag (\ s a -> s{_mlrEtag = a})
mlrTokenPagination :: Lens' MemberListResponse (Maybe TokenPagination)
mlrTokenPagination
= lens _mlrTokenPagination
(\ s a -> s{_mlrTokenPagination = a})
-- | The token that can be used as the value of the pageToken parameter to
-- retrieve the next page in the result set.
mlrNextPageToken :: Lens' MemberListResponse (Maybe Text)
mlrNextPageToken
= lens _mlrNextPageToken
(\ s a -> s{_mlrNextPageToken = a})
mlrPageInfo :: Lens' MemberListResponse (Maybe PageInfo)
mlrPageInfo
= lens _mlrPageInfo (\ s a -> s{_mlrPageInfo = a})
-- | Identifies what kind of resource this is. Value: the fixed string
-- \"youtube#memberListResponse\".
mlrKind :: Lens' MemberListResponse Text
mlrKind = lens _mlrKind (\ s a -> s{_mlrKind = a})
-- | A list of members that match the request criteria.
mlrItems :: Lens' MemberListResponse [Member]
mlrItems
= lens _mlrItems (\ s a -> s{_mlrItems = a}) .
_Default
. _Coerce
-- | The visitorId identifies the visitor.
mlrVisitorId :: Lens' MemberListResponse (Maybe Text)
mlrVisitorId
= lens _mlrVisitorId (\ s a -> s{_mlrVisitorId = a})
-- | Serialized EventId of the request which produced this response.
mlrEventId :: Lens' MemberListResponse (Maybe Text)
mlrEventId
= lens _mlrEventId (\ s a -> s{_mlrEventId = a})
instance FromJSON MemberListResponse where
parseJSON
= withObject "MemberListResponse"
(\ o ->
MemberListResponse' <$>
(o .:? "etag") <*> (o .:? "tokenPagination") <*>
(o .:? "nextPageToken")
<*> (o .:? "pageInfo")
<*> (o .:? "kind" .!= "youtube#memberListResponse")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "visitorId")
<*> (o .:? "eventId"))
instance ToJSON MemberListResponse where
toJSON MemberListResponse'{..}
= object
(catMaybes
[("etag" .=) <$> _mlrEtag,
("tokenPagination" .=) <$> _mlrTokenPagination,
("nextPageToken" .=) <$> _mlrNextPageToken,
("pageInfo" .=) <$> _mlrPageInfo,
Just ("kind" .= _mlrKind),
("items" .=) <$> _mlrItems,
("visitorId" .=) <$> _mlrVisitorId,
("eventId" .=) <$> _mlrEventId])
| brendanhay/gogol | gogol-youtube/gen/Network/Google/YouTube/Types/Product.hs | mpl-2.0 | 561,702 | 0 | 82 | 134,953 | 104,596 | 60,230 | 44,366 | 11,680 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Content.Orderreturns.Process
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Processes return in your Merchant Center account.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.orderreturns.process@.
module Network.Google.Resource.Content.Orderreturns.Process
(
-- * REST Resource
OrderreturnsProcessResource
-- * Creating a Request
, orderreturnsProcess
, OrderreturnsProcess
-- * Request Lenses
, opXgafv
, opMerchantId
, opUploadProtocol
, opAccessToken
, opUploadType
, opPayload
, opReturnId
, opCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.orderreturns.process@ method which the
-- 'OrderreturnsProcess' request conforms to.
type OrderreturnsProcessResource =
"content" :>
"v2.1" :>
Capture "merchantId" (Textual Word64) :>
"orderreturns" :>
Capture "returnId" Text :>
"process" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] OrderreturnsProcessRequest :>
Post '[JSON] OrderreturnsProcessResponse
-- | Processes return in your Merchant Center account.
--
-- /See:/ 'orderreturnsProcess' smart constructor.
data OrderreturnsProcess =
OrderreturnsProcess'
{ _opXgafv :: !(Maybe Xgafv)
, _opMerchantId :: !(Textual Word64)
, _opUploadProtocol :: !(Maybe Text)
, _opAccessToken :: !(Maybe Text)
, _opUploadType :: !(Maybe Text)
, _opPayload :: !OrderreturnsProcessRequest
, _opReturnId :: !Text
, _opCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrderreturnsProcess' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'opXgafv'
--
-- * 'opMerchantId'
--
-- * 'opUploadProtocol'
--
-- * 'opAccessToken'
--
-- * 'opUploadType'
--
-- * 'opPayload'
--
-- * 'opReturnId'
--
-- * 'opCallback'
orderreturnsProcess
:: Word64 -- ^ 'opMerchantId'
-> OrderreturnsProcessRequest -- ^ 'opPayload'
-> Text -- ^ 'opReturnId'
-> OrderreturnsProcess
orderreturnsProcess pOpMerchantId_ pOpPayload_ pOpReturnId_ =
OrderreturnsProcess'
{ _opXgafv = Nothing
, _opMerchantId = _Coerce # pOpMerchantId_
, _opUploadProtocol = Nothing
, _opAccessToken = Nothing
, _opUploadType = Nothing
, _opPayload = pOpPayload_
, _opReturnId = pOpReturnId_
, _opCallback = Nothing
}
-- | V1 error format.
opXgafv :: Lens' OrderreturnsProcess (Maybe Xgafv)
opXgafv = lens _opXgafv (\ s a -> s{_opXgafv = a})
-- | The ID of the account that manages the order. This cannot be a
-- multi-client account.
opMerchantId :: Lens' OrderreturnsProcess Word64
opMerchantId
= lens _opMerchantId (\ s a -> s{_opMerchantId = a})
. _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
opUploadProtocol :: Lens' OrderreturnsProcess (Maybe Text)
opUploadProtocol
= lens _opUploadProtocol
(\ s a -> s{_opUploadProtocol = a})
-- | OAuth access token.
opAccessToken :: Lens' OrderreturnsProcess (Maybe Text)
opAccessToken
= lens _opAccessToken
(\ s a -> s{_opAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
opUploadType :: Lens' OrderreturnsProcess (Maybe Text)
opUploadType
= lens _opUploadType (\ s a -> s{_opUploadType = a})
-- | Multipart request metadata.
opPayload :: Lens' OrderreturnsProcess OrderreturnsProcessRequest
opPayload
= lens _opPayload (\ s a -> s{_opPayload = a})
-- | The ID of the return.
opReturnId :: Lens' OrderreturnsProcess Text
opReturnId
= lens _opReturnId (\ s a -> s{_opReturnId = a})
-- | JSONP
opCallback :: Lens' OrderreturnsProcess (Maybe Text)
opCallback
= lens _opCallback (\ s a -> s{_opCallback = a})
instance GoogleRequest OrderreturnsProcess where
type Rs OrderreturnsProcess =
OrderreturnsProcessResponse
type Scopes OrderreturnsProcess =
'["https://www.googleapis.com/auth/content"]
requestClient OrderreturnsProcess'{..}
= go _opMerchantId _opReturnId _opXgafv
_opUploadProtocol
_opAccessToken
_opUploadType
_opCallback
(Just AltJSON)
_opPayload
shoppingContentService
where go
= buildClient
(Proxy :: Proxy OrderreturnsProcessResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Orderreturns/Process.hs | mpl-2.0 | 5,623 | 0 | 20 | 1,380 | 882 | 511 | 371 | 128 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Genomics.Annotations.BatchCreate
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates one or more new annotations atomically. All annotations must
-- belong to the same annotation set. Caller must have WRITE permission for
-- this annotation set. For optimal performance, batch positionally
-- adjacent annotations together. If the request has a systemic issue, such
-- as an attempt to write to an inaccessible annotation set, the entire RPC
-- will fail accordingly. For lesser data issues, when possible an error
-- will be isolated to the corresponding batch entry in the response; the
-- remaining well formed annotations will be created normally. For details
-- on the requirements for each individual annotation resource, see
-- CreateAnnotation.
--
-- /See:/ <https://cloud.google.com/genomics Genomics API Reference> for @genomics.annotations.batchCreate@.
module Network.Google.Resource.Genomics.Annotations.BatchCreate
(
-- * REST Resource
AnnotationsBatchCreateResource
-- * Creating a Request
, annotationsBatchCreate
, AnnotationsBatchCreate
-- * Request Lenses
, abcXgafv
, abcUploadProtocol
, abcPp
, abcAccessToken
, abcUploadType
, abcPayload
, abcBearerToken
, abcCallback
) where
import Network.Google.Genomics.Types
import Network.Google.Prelude
-- | A resource alias for @genomics.annotations.batchCreate@ method which the
-- 'AnnotationsBatchCreate' request conforms to.
type AnnotationsBatchCreateResource =
"v1" :>
"annotations:batchCreate" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] BatchCreateAnnotationsRequest :>
Post '[JSON] BatchCreateAnnotationsResponse
-- | Creates one or more new annotations atomically. All annotations must
-- belong to the same annotation set. Caller must have WRITE permission for
-- this annotation set. For optimal performance, batch positionally
-- adjacent annotations together. If the request has a systemic issue, such
-- as an attempt to write to an inaccessible annotation set, the entire RPC
-- will fail accordingly. For lesser data issues, when possible an error
-- will be isolated to the corresponding batch entry in the response; the
-- remaining well formed annotations will be created normally. For details
-- on the requirements for each individual annotation resource, see
-- CreateAnnotation.
--
-- /See:/ 'annotationsBatchCreate' smart constructor.
data AnnotationsBatchCreate = AnnotationsBatchCreate'
{ _abcXgafv :: !(Maybe Xgafv)
, _abcUploadProtocol :: !(Maybe Text)
, _abcPp :: !Bool
, _abcAccessToken :: !(Maybe Text)
, _abcUploadType :: !(Maybe Text)
, _abcPayload :: !BatchCreateAnnotationsRequest
, _abcBearerToken :: !(Maybe Text)
, _abcCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AnnotationsBatchCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'abcXgafv'
--
-- * 'abcUploadProtocol'
--
-- * 'abcPp'
--
-- * 'abcAccessToken'
--
-- * 'abcUploadType'
--
-- * 'abcPayload'
--
-- * 'abcBearerToken'
--
-- * 'abcCallback'
annotationsBatchCreate
:: BatchCreateAnnotationsRequest -- ^ 'abcPayload'
-> AnnotationsBatchCreate
annotationsBatchCreate pAbcPayload_ =
AnnotationsBatchCreate'
{ _abcXgafv = Nothing
, _abcUploadProtocol = Nothing
, _abcPp = True
, _abcAccessToken = Nothing
, _abcUploadType = Nothing
, _abcPayload = pAbcPayload_
, _abcBearerToken = Nothing
, _abcCallback = Nothing
}
-- | V1 error format.
abcXgafv :: Lens' AnnotationsBatchCreate (Maybe Xgafv)
abcXgafv = lens _abcXgafv (\ s a -> s{_abcXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
abcUploadProtocol :: Lens' AnnotationsBatchCreate (Maybe Text)
abcUploadProtocol
= lens _abcUploadProtocol
(\ s a -> s{_abcUploadProtocol = a})
-- | Pretty-print response.
abcPp :: Lens' AnnotationsBatchCreate Bool
abcPp = lens _abcPp (\ s a -> s{_abcPp = a})
-- | OAuth access token.
abcAccessToken :: Lens' AnnotationsBatchCreate (Maybe Text)
abcAccessToken
= lens _abcAccessToken
(\ s a -> s{_abcAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
abcUploadType :: Lens' AnnotationsBatchCreate (Maybe Text)
abcUploadType
= lens _abcUploadType
(\ s a -> s{_abcUploadType = a})
-- | Multipart request metadata.
abcPayload :: Lens' AnnotationsBatchCreate BatchCreateAnnotationsRequest
abcPayload
= lens _abcPayload (\ s a -> s{_abcPayload = a})
-- | OAuth bearer token.
abcBearerToken :: Lens' AnnotationsBatchCreate (Maybe Text)
abcBearerToken
= lens _abcBearerToken
(\ s a -> s{_abcBearerToken = a})
-- | JSONP
abcCallback :: Lens' AnnotationsBatchCreate (Maybe Text)
abcCallback
= lens _abcCallback (\ s a -> s{_abcCallback = a})
instance GoogleRequest AnnotationsBatchCreate where
type Rs AnnotationsBatchCreate =
BatchCreateAnnotationsResponse
type Scopes AnnotationsBatchCreate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/genomics"]
requestClient AnnotationsBatchCreate'{..}
= go _abcXgafv _abcUploadProtocol (Just _abcPp)
_abcAccessToken
_abcUploadType
_abcBearerToken
_abcCallback
(Just AltJSON)
_abcPayload
genomicsService
where go
= buildClient
(Proxy :: Proxy AnnotationsBatchCreateResource)
mempty
| rueshyna/gogol | gogol-genomics/gen/Network/Google/Resource/Genomics/Annotations/BatchCreate.hs | mpl-2.0 | 6,828 | 0 | 18 | 1,549 | 878 | 517 | 361 | 124 | 1 |
myLength :: [t] -> Int
myLength [] = 0
myLength (x:xs) = myLength xs + 1 | alephnil/h99 | 04.hs | apache-2.0 | 72 | 0 | 7 | 15 | 45 | 23 | 22 | 3 | 1 |
{-# LANGUAGE BangPatterns #-}
module Database.VCache.VRef
( VRef
, vref, deref
, vref', deref'
, unsafeVRefAddr
, unsafeVRefRefct
, vref_space
, CacheMode(..)
, vrefc, derefc
, withVRefBytes
, unsafeVRefEncoding
) where
import Control.Monad
import Data.IORef
import Data.Bits
import Data.Word
import Data.ByteString (ByteString)
import Foreign.Ptr
import Foreign.Storable
import System.IO.Unsafe
import Database.VCache.Types
import Database.VCache.Alloc
import Database.VCache.Read
-- | Construct a reference with the cache initially active, i.e.
-- such that immediate deref can access the value without reading
-- from the database. The given value will be placed in the cache
-- unless the same vref has already been constructed.
vref :: (VCacheable a) => VSpace -> a -> VRef a
vref = vrefc CacheMode1
{-# INLINE vref #-}
-- | Construct a VRef with an alternative cache control mode.
vrefc :: (VCacheable a) => CacheMode -> VSpace -> a -> VRef a
vrefc cm vc v = unsafePerformIO (newVRefIO vc v cm)
{-# INLINABLE vrefc #-}
-- | In some cases, developers can reasonably assume they won't need a
-- value in the near future. In these cases, use the vref' constructor
-- to allocate a VRef without caching the content.
vref' :: (VCacheable a) => VSpace -> a -> VRef a
vref' vc v = unsafePerformIO (newVRefIO' vc v)
{-# INLINABLE vref' #-}
readVRef :: VRef a -> IO (a, Int)
readVRef v = readAddrIO (vref_space v) (vref_addr v) (vref_parse v)
{-# INLINE readVRef #-}
-- | Dereference a VRef, obtaining its value. If the value is not in
-- cache, it will be read into the database then cached. Otherwise,
-- the value is read from cache and the cache is touched to restart
-- any expiration.
--
-- Assuming a valid VCacheable instance, this operation should return
-- an equivalent value as was used to construct the VRef.
deref :: VRef a -> a
deref = derefc CacheMode1
{-# INLINE deref #-}
-- | Dereference a VRef with an alternative cache control mode.
derefc :: CacheMode -> VRef a -> a
derefc cm v = unsafeDupablePerformIO $
unsafeInterleaveIO (readVRef v) >>= \ lazy_read_rw ->
join $ atomicModifyIORef (vref_cache v) $ \case
Cached r bf ->
let bf' = touchCache cm bf in
let c' = Cached r bf' in
(c', c' `seq` return r)
NotCached ->
let (r,w) = lazy_read_rw in
let c' = mkVRefCache r w cm in
let op = initVRefCache v >> return r in
(c', c' `seq` op)
{-# NOINLINE derefc #-}
-- | Dereference a VRef. This will read from the cache if the value
-- is available, but will not update the cache. If the value is not
-- cached, it will be read instead from the persistence layer.
--
-- This can be useful if you know you'll only dereference a value
-- once for a given task, or if the datatype involved is cheap to
-- parse (e.g. simple bytestrings) such that there isn't a strong
-- need to cache the parse result.
deref' :: VRef a -> a
deref' v = unsafePerformIO $
readIORef (vref_cache v) >>= \case
Cached r _ -> return r
NotCached -> fmap fst (readVRef v)
{-# INLINABLE deref' #-}
-- | Specialized, zero-copy access to a `VRef ByteString`. Access to
-- the given ByteString becomes invalid after returning. This operation
-- may also block the writer if it runs much longer than a single
-- writer batch (though, writer batches are frequently large enough
-- that this shouldn't be a problem if you're careful).
--
withVRefBytes :: VRef ByteString -> (Ptr Word8 -> Int -> IO a) -> IO a
withVRefBytes v action = unsafeVRefEncoding v $ \ p n ->
-- valid ByteString encoding: varNat, bytes, 0 (children)
readVarNat p 0 >>= \ (p', n') ->
let bOK = (p' `plusPtr` n') == (p `plusPtr` (n-1)) in
let eMsg = show v ++ " doesn't contain a ByteString" in
unless bOK (fail $ "withVRefBytes: " ++ eMsg) >>
action p' n'
readVarNat :: Ptr Word8 -> Int -> IO (Ptr Word8, Int)
readVarNat !p !n =
peek p >>= \ w8 ->
let p' = p `plusPtr` 1 in
let n' = (n `shiftL` 7) + fromIntegral (w8 .&. 0x7f) in
let bDone = (0 == (w8 .&. 0x80)) in
if bDone then return (p', n') else
readVarNat p' n'
-- | Zero-copy access to the raw encoding for any VRef. The given data
-- becomes invalid after returning. This is provided for mostly for
-- debugging purposes, i.e. so you can peek under the hood and see how
-- things are encoded or eyeball the encoding.
unsafeVRefEncoding :: VRef any -> (Ptr Word8 -> Int -> IO a) -> IO a
unsafeVRefEncoding v = withBytesIO (vref_space v) (vref_addr v)
{-# INLINE unsafeVRefEncoding #-}
-- | Each VRef has an numeric address in the VSpace. This address is
-- non-deterministic, and essentially independent of the arguments to
-- the vref constructor. This function is 'unsafe' in the sense that
-- it violates the illusion of purity. However, the VRef address will
-- be stable so long as the developer can guarantee it is reachable.
--
-- This function may be useful for memoization tables and similar.
--
-- The 'Show' instance for VRef will also show the address.
unsafeVRefAddr :: VRef a -> Address
unsafeVRefAddr = vref_addr
{-# INLINE unsafeVRefAddr #-}
-- | This function allows developers to access the reference count
-- for the VRef that is currently recorded in the database. This may
-- be useful for heuristic purposes. However, caveats are needed:
--
-- First, due to structure sharing, a VRef may share an address with
-- VRefs of other types having the same serialized form. Reference
-- counts are at the address level.
--
-- Second, because the VCache writer operates in a background thread,
-- the reference count returned here may be slightly out of date.
--
-- Third, it is possible that VCache will eventually use some other
-- form of garbage collection than reference counting. This function
-- should be considered an unstable element of the API.
unsafeVRefRefct :: VRef a -> IO Int
unsafeVRefRefct v = readRefctIO (vref_space v) (vref_addr v)
{-# INLINE unsafeVRefRefct #-}
| dmbarbour/haskell-vcache | hsrc_lib/Database/VCache/VRef.hs | bsd-2-clause | 6,043 | 0 | 20 | 1,270 | 1,093 | 596 | 497 | -1 | -1 |
module RuntimeProcessManager (withRuntimeProcess) where
import JavaUtils (getClassPath)
import StringPrefixes (namespace)
import System.IO (Handle, hSetBuffering, BufferMode(..))
import System.Process
withRuntimeProcess :: String -> BufferMode -> ((Handle,Handle) -> IO a) -> Bool -> IO a
withRuntimeProcess class_name buffer_mode do_this loadPrelude
= do cp <- if loadPrelude then return "runtime/runtime.jar" else getClassPath
let p = (proc "java" ["-cp", cp, namespace ++ class_name, cp])
{std_in = CreatePipe, std_out = CreatePipe}
(Just inP, Just outP, _, proch) <- createProcess p
hSetBuffering inP buffer_mode
hSetBuffering outP buffer_mode
result <- do_this (inP, outP)
terminateProcess proch
return result
| bixuanzju/fcore | lib/services/RuntimeProcessManager.hs | bsd-2-clause | 797 | 0 | 14 | 171 | 241 | 128 | 113 | 16 | 2 |
{- Copyright (c) 2008 David Roundy
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. -}
module Distribution.Franchise.ListUtils
( stripPrefix, stripSuffix, endsWithOneOf, commaWords ) where
import Data.List ( isSuffixOf )
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys) | x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix x y = reverse `fmap` stripPrefix (reverse x) (reverse y)
-- | Checks if a string ends with any given suffix
endsWithOneOf :: [String] -- ^ List of strings to check
-> String -- ^ String to check against
-> Bool
endsWithOneOf xs y = any (`isSuffixOf` y) xs
commaWords :: [String] -> String
commaWords [] = ""
commaWords [x] = x
commaWords (x:xs) = x++", "++commaWords xs
| droundy/franchise | Distribution/Franchise/ListUtils.hs | bsd-3-clause | 2,222 | 0 | 9 | 412 | 292 | 158 | 134 | 17 | 1 |
module HsImport.Types where
import qualified Language.Haskell.Exts as HS
type SrcLine = Int
type SrcColumn = Int
type SrcSpan = HS.SrcSpan
type SrcLoc = HS.SrcLoc
type Annotation = (HS.SrcSpanInfo, [HS.Comment])
type Decl = HS.Decl Annotation
type ImportDecl = HS.ImportDecl Annotation
type ImportSpec = HS.ImportSpec Annotation
type ImportSpecList = HS.ImportSpecList Annotation
type Name = HS.Name Annotation
type CName = HS.CName Annotation
type Module = HS.Module Annotation
type ModuleName = String
type ErrorMessage = String
data ParseResult = ParseResult
{ -- | the parse result
result :: HS.ParseResult Module
-- | if the source file isn't completely parsable, because e.g.
-- it contains incomplete Haskell code, then 'lastValidLine'
-- contains the last line till the source is parsable
, lastValidLine :: Maybe Int
}
firstSrcLine :: Annotation -> SrcLine
firstSrcLine = minimum . map HS.srcSpanStartLine . srcSpans
lastSrcLine :: Annotation -> SrcLine
lastSrcLine = maximum . map HS.srcSpanEndLine . srcSpans
firstSrcColumn :: Annotation -> SrcColumn
firstSrcColumn = minimum . map HS.srcSpanStartColumn . srcSpans
lastSrcColumn :: Annotation -> SrcColumn
lastSrcColumn = maximum . map HS.srcSpanEndColumn . srcSpans
srcSpan :: Annotation -> SrcSpan
srcSpan ann@(HS.SrcSpanInfo srcSpan _, _) =
srcSpan { HS.srcSpanStartLine = firstSrcLine ann
, HS.srcSpanStartColumn = firstSrcColumn ann
, HS.srcSpanEndLine = lastSrcLine ann
, HS.srcSpanEndColumn = lastSrcColumn ann
}
srcSpans :: Annotation -> [SrcSpan]
srcSpans (HS.SrcSpanInfo srcSpan _, comments) = srcSpan : commentSrcSpans
where
commentSrcSpans = map (\(HS.Comment _ srcSpan _) -> srcSpan) comments
noAnnotation :: Annotation
noAnnotation = (HS.noSrcSpan, [])
| dan-t/hsimport | lib/HsImport/Types.hs | bsd-3-clause | 1,919 | 0 | 12 | 429 | 460 | 259 | 201 | 38 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Elm.Package.Description where
import Prelude hiding (read)
import Control.Applicative ((<$>))
import Control.Arrow (first)
import Control.Monad.Trans (MonadIO, liftIO)
import Control.Monad.Error.Class (MonadError, throwError)
import Control.Monad (when, mzero, forM)
import Data.Aeson
import Data.Aeson.Types (Parser)
import Data.Aeson.Encode.Pretty (encodePretty', defConfig, confCompare, keyOrder)
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.HashMap.Strict as Map
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Data.Text as T
import System.FilePath ((</>), (<.>))
import System.Directory (doesFileExist)
import qualified Elm.Compiler.Module as Module
import qualified Elm.Package as Package
import qualified Elm.Package.Constraint as C
import qualified Elm.Package.Paths as Path
import Elm.Utils ((|>))
data Description = Description
{ name :: Package.Name
, repo :: String
, version :: Package.Version
, elmVersion :: C.Constraint
, summary :: String
, license :: String
, sourceDirs :: [FilePath]
, exposed :: [Module.Name]
, natives :: Bool
, dependencies :: [(Package.Name, C.Constraint)]
}
defaultDescription :: Description
defaultDescription =
Description
{ name = Package.Name "USER" "PROJECT"
, repo = "https://github.com/USER/PROJECT.git"
, version = Package.initialVersion
, elmVersion = C.defaultElmVersion
, summary = "helpful summary of your project, less than 80 characters"
, license = "BSD3"
, sourceDirs = [ "." ]
, exposed = []
, natives = False
, dependencies = []
}
-- READ
read :: (MonadIO m, MonadError String m) => FilePath -> m Description
read path =
do json <- liftIO (BS.readFile path)
case eitherDecode json of
Left err ->
throwError $ "Error reading file " ++ path ++ ":\n " ++ err
Right ds ->
return ds
-- WRITE
write :: Description -> IO ()
write description =
BS.writeFile Path.description json
where
json = prettyJSON description
-- FIND MODULE FILE PATHS
locateExposedModules :: (MonadIO m, MonadError String m) => Description -> m [(Module.Name, FilePath)]
locateExposedModules desc =
mapM locate (exposed desc)
where
locate modul =
let path = Module.nameToPath modul <.> "elm"
dirs = sourceDirs desc
in
do possibleLocations <-
forM dirs $ \dir -> do
exists <- liftIO $ doesFileExist (dir </> path)
return (if exists then Just (dir </> path) else Nothing)
case Maybe.catMaybes possibleLocations of
[] ->
throwError $
unlines
[ "Could not find exposed module '" ++ Module.nameToString modul ++ "' when looking through"
, "the following source directories:"
, concatMap ("\n " ++) dirs
, ""
, "You may need to add a source directory to your " ++ Path.description ++ " file."
]
[location] ->
return (modul, location)
locations ->
throwError $
unlines
[ "I found more than one module named '" ++ Module.nameToString modul ++ "' in the"
, "following locations:"
, concatMap ("\n " ++) locations
, ""
, "Module names must be unique within your package."
]
-- JSON
prettyJSON :: Description -> BS.ByteString
prettyJSON description =
prettyAngles (encodePretty' config description)
where
config =
defConfig { confCompare = keyOrder (normalKeys ++ dependencyKeys) }
normalKeys =
[ "version"
, "summary"
, "repository"
, "license"
, "source-directories"
, "exposed-modules"
, "native-modules"
, "dependencies"
, "elm-version"
]
dependencyKeys =
dependencies description
|> map fst
|> List.sort
|> map (T.pack . Package.toString)
prettyAngles :: BS.ByteString -> BS.ByteString
prettyAngles string =
BS.concat $ replaceChunks string
where
replaceChunks str =
let (before, after) = BS.break (=='\\') str
in
case BS.take 6 after of
"\\u003e" -> before : ">" : replaceChunks (BS.drop 6 after)
"\\u003c" -> before : "<" : replaceChunks (BS.drop 6 after)
"" -> [before]
_ ->
before : "\\" : replaceChunks (BS.tail after)
instance ToJSON Description where
toJSON d =
object $
[ "repository" .= repo d
, "version" .= version d
, "summary" .= summary d
, "license" .= license d
, "source-directories" .= sourceDirs d
, "exposed-modules" .= exposed d
, "dependencies" .= jsonDeps (dependencies d)
, "elm-version" .= elmVersion d
] ++ if natives d then ["native-modules" .= True] else []
where
jsonDeps deps =
Map.fromList $ map (first (T.pack . Package.toString)) deps
instance FromJSON Description where
parseJSON (Object obj) =
do version <- get obj "version" "your project's version number"
elmVersion <- getElmVersion obj
summary <- get obj "summary" "a short summary of your project"
when (length summary >= 80) $
fail "'summary' must be less than 80 characters"
license <- get obj "license" "license information (BSD3 is recommended)"
repo <- get obj "repository" "a link to the project's GitHub repo"
name <- case repoToName repo of
Left err -> fail err
Right nm -> return nm
exposed <- get obj "exposed-modules" "a list of modules exposed to users"
sourceDirs <- get obj "source-directories" "the directories that hold source code"
deps <- getDependencies obj
natives <- maybe False id <$> obj .:? "native-modules"
return $ Description name repo version elmVersion summary license sourceDirs exposed natives deps
parseJSON _ = mzero
get :: FromJSON a => Object -> T.Text -> String -> Parser a
get obj field desc =
do maybe <- obj .:? field
case maybe of
Just value ->
return value
Nothing ->
fail $
"Missing field " ++ show field ++ ", " ++ desc ++ ".\n" ++
" Check out an example " ++ Path.description ++ " file here:\n" ++
" <https://raw.githubusercontent.com/evancz/elm-html/master/elm-package.json>"
getDependencies :: Object -> Parser [(Package.Name, C.Constraint)]
getDependencies obj =
do deps <- get obj "dependencies" "a listing of your project's dependencies"
forM (Map.toList deps) $ \(rawName, rawConstraint) ->
case (Package.fromString rawName, C.fromString rawConstraint) of
(Just name, Just constraint) ->
return (name, constraint)
(Nothing, _) ->
fail (Package.errorMsg rawName)
(_, Nothing) ->
fail (C.errorMessage rawConstraint)
getElmVersion :: Object -> Parser C.Constraint
getElmVersion obj =
do rawConstraint <- get obj "elm-version" elmVersionDescription
case C.fromString rawConstraint of
Just constraint ->
return constraint
Nothing ->
fail (C.errorMessage rawConstraint)
elmVersionDescription :: String
elmVersionDescription =
"acceptable versions of the Elm Platform (e.g. \""
++ C.toString C.defaultElmVersion ++ "\")"
repoToName :: String -> Either String Package.Name
repoToName repo =
if not (end `List.isSuffixOf` repo)
then Left msg
else
do path <- getPath
let raw = take (length path - length end) path
case Package.fromString raw of
Nothing -> Left msg
Just name -> Right name
where
getPath
| http `List.isPrefixOf` repo = Right $ drop (length http ) repo
| https `List.isPrefixOf` repo = Right $ drop (length https) repo
| otherwise = Left msg
http = "http://github.com/"
https = "https://github.com/"
end = ".git"
msg =
"the 'repository' field must point to a GitHub project for now, something\n\
\like <https://github.com/USER/PROJECT.git> where USER is your GitHub name\n\
\and PROJECT is the repo you want to upload."
| laszlopandy/elm-package | src/Elm/Package/Description.hs | bsd-3-clause | 8,771 | 0 | 21 | 2,702 | 2,188 | 1,153 | 1,035 | 204 | 4 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.RealArithmetic.Basis.Double.Measures
Description : distance between Double numbers
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Distance between Double numbers.
This is a private module reexported publicly via its parent.
-}
module Numeric.AERN.RealArithmetic.Basis.Double.Measures where
import Numeric.AERN.RealArithmetic.Basis.Double.NumericOrder
import Numeric.AERN.RealArithmetic.Basis.Double.FieldOps
import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut
import Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators
import Numeric.AERN.RealArithmetic.ExactOps
import Numeric.AERN.RealArithmetic.Measures
import Numeric.AERN.RealArithmetic.Interval.Double
import Numeric.AERN.Basics.Interval
instance HasDistance Double where
type Distance Double = DI
type DistanceEffortIndicator Double = ArithInOut.AddEffortIndicator DI
distanceDefaultEffort d = ArithInOut.addDefaultEffort (sampleDI :: DI)
distanceBetweenEff effort d1 d2 =
-- | d1 == 1/0 && d2 == 1/0 = zero
-- -- distance between two infinities is zero (beware: distance not continuous at infinities!)
-- | d1 == -1/0 && d2 == -1/0 = zero
-- | otherwise =
ArithInOut.absOut (d2I <-> d1I)
where
d1I = Interval d1 d1
d2I = Interval d2 d2
| michalkonecny/aern | aern-double/src/Numeric/AERN/RealArithmetic/Basis/Double/Measures.hs | bsd-3-clause | 1,576 | 0 | 8 | 320 | 178 | 113 | 65 | 19 | 0 |
{- |
Module : <Onping.Tag.Report>
Description : <Executable for Onping Tag Report >
Copyright : (c) <Plow Technology 2014>
License : <MIT>
Maintainer : <[email protected]>
Stability : unstable
Portability : portable
<Grab a company by its name and generate reports for all its sites , locations and tags.>
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Onping.Tag.Report where
-- General
import Data.Text (Text)
-- Database
import Plowtech.Persist.Settings
import Database.Persist
import Plowtech.Request.Haxl (PlowStateStore)
import qualified Plowtech.Request.Haxl as Haxl
import qualified Plowtech.Request.Haxl.Company as Haxl
import qualified Plowtech.Request.Haxl.Location as Haxl
import qualified Plowtech.Request.Haxl.OnpingTagCombined as Haxl
import qualified Plowtech.Request.Haxl.Site as Haxl
-- String Template
import Text.StringTemplate
data ReportStyle = HTML | CSV
-- Output Format
-- # Onping Register Report
-- ## Company: <company name>
-- ## Site: <site name>
-- ### Location: <location name> SlaveId: <locationSlaveId>
-- #### <location name> Parameter Tags
-- <table>
-- <tr>
-- <th>Tag Name</th> , <th>Slave Parameter Id </th>, <th>Parameter Tag ID</th>
-- <tr>
-- <tag name>, <slave_parameter_id>, <parameter tag Id>
-- fetchCompanies :: PlowStateStore -> Text -> IO [Company]
fetchCompanies :: PlowStateStore -> Text -> IO [Company]
fetchCompanies plowStateStore companyName' = do
companyEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getCompaniesByName [companyName']
return $ entityVal <$> companyEntities
fetchSites :: PlowStateStore -> Int -> IO [Site]
fetchSites plowStateStore companyId = do
siteEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getSitesByCompanyIdRefs [companyId]
return $ entityVal <$> siteEntities
fetchLocations :: PlowStateStore -> Int -> IO [Location]
fetchLocations plowStateStore siteId = do
locationEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getLocationsByAltKeys altkeys
return $ entityVal <$> locationEntities
where
altkeys = Haxl.LocationLookupId Nothing [] [siteId]
fetchOnpingTagCombineds :: PlowStateStore -> Int -> IO [OnpingTagCombined]
fetchOnpingTagCombineds plowStateStore locationId = do
otcEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getParametersByAltKeys altkeys
return otcEntities
where
altkeys = Haxl.ParameterLookupId [locationId] [] []
buildOTCSTemplate :: OnpingTagCombined -> String
buildOTCSTemplate otc = render otcSTemplate
where otcName = onpingTagCombinedDescription otc
otcSlaveParameterId = onpingTagCombinedSlave_parameter_id otc
otcParameterTagId = onpingTagCombinedParameter_tag_id otc
otcPID = onpingTagCombinedPid otc
baseTemplate = (newSTMP "<tr><td>$pid$</td><td>$tag_name$</td> <td>$slave_parameter_id$</td> <td>$parameter_tag_Id$</td></tr>") :: StringTemplate String
otcSTemplate = setAttribute "tag_name" otcName .
setAttribute "slave_parameter_id" otcSlaveParameterId .
setAttribute "parameter_tag_Id" otcParameterTagId .
setAttribute "pid" otcPID $ baseTemplate
buildTableSTemplate :: [OnpingTagCombined] -> String
buildTableSTemplate otcList = render tableSTemplate
where otcSTemplates = unlines $ buildOTCSTemplate <$> otcList
baseTemplate = (newSTMP "<table class='table table-condensed table-striped'> \n\
\<tr> \n\
\<th>Global Parameter Id </th> \n\
\<th>Tag Name</th> \n\
\<th>Slave Parameter Id </th> \n\
\<th>Parameter Tag ID</th> \n\
\</tr>\n\
\$otcSTemplate$\
\</table>") :: StringTemplate String
tableSTemplate = setAttribute "otcSTemplate" otcSTemplates $ baseTemplate
buildLocationTemplate :: PlowStateStore -> Location -> IO String
buildLocationTemplate plowStateStore l = do
otcList <- fetchOnpingTagCombineds plowStateStore (locationRefId l)
let tableTemplate = buildTableSTemplate otcList
locName = locationName l
locSlaveId = locationSlaveId l
baseTemplate = (newSTMP "\n### Location: $location_name$ SlaveId: $locationSlaveId$ \n\
\#### $location_name$ Parameter Tags \n\
\$tableTemplate$ \n") :: StringTemplate String
locationSTemplate = setAttribute "location_name" locName .
setAttribute "locationSlaveId" locSlaveId .
setAttribute "tableTemplate" tableTemplate $ baseTemplate
return $ render locationSTemplate
buildSiteTemplate :: PlowStateStore -> Site -> IO String
buildSiteTemplate plowStateStore s = do
locList <- fetchLocations plowStateStore (siteSiteIdRef s)
locationTemplates <- traverse (buildLocationTemplate plowStateStore ) locList
let sName = siteName s
baseTemplate = (newSTMP "\n## Site: $site_name$ \n\
\$location_template$ \n") :: StringTemplate String
siteSTemplate = setAttribute "site_name" sName .
setAttribute "location_template" (unlines locationTemplates) $ baseTemplate
return $ render siteSTemplate
buildCompanyTemplate :: PlowStateStore -> Text -> IO String
buildCompanyTemplate plowStateStore cName = do
companyList <- fetchCompanies plowStateStore cName
case companyList of
[] -> return "Error: There is no company records match the name given."
_ -> do
siteList <-fetchSites plowStateStore (companyCompanyIdRef . head $ companyList)
siteTemplates <- traverse (buildSiteTemplate plowStateStore ) siteList
let baseTemplate = (newSTMP "<head>\n\
\<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>\n\
\</head>\n\n\
\# Onping Register Report \n\n\
\## Company: $company_name$ \n\n\
\$site_template$ \n") :: StringTemplate String
companySTemplate = setAttribute "company_name" cName .
setAttribute "site_template" (unlines siteTemplates) $ baseTemplate
return $ render companySTemplate
-- --------------------------------------------------
buildOTCSTemplateCSV :: Text -> Text -> Text -> OnpingTagCombined -> String
buildOTCSTemplateCSV cName sName locName otc = render otcSTemplate
where otcName = onpingTagCombinedDescription otc
otcSlaveParameterId = onpingTagCombinedSlave_parameter_id otc
otcParameterTagId = onpingTagCombinedParameter_tag_id otc
otcPID = onpingTagCombinedPid otc
baseTemplate = (newSTMP "$company_name$ | $site_name$ | $location_name$ | $pid$ | $tag_name$ | $slave_parameter_id$ | $parameter_tag_Id$ \n") :: StringTemplate String
otcSTemplate = setAttribute "tag_name" otcName .
setAttribute "slave_parameter_id" otcSlaveParameterId .
setAttribute "parameter_tag_Id" otcParameterTagId .
setAttribute "company_name" cName.
setAttribute "site_name" sName.
setAttribute "location_name" locName.
setAttribute "pid" otcPID $ baseTemplate
buildTableSTemplateCSV :: Text -> Text -> Text -> [OnpingTagCombined] -> String
buildTableSTemplateCSV cName sName lName otcList = render tableSTemplate
where otcSTemplates = unlines $ buildOTCSTemplateCSV cName sName lName <$> otcList
baseTemplate = (newSTMP "$otcSTemplate$ \n") :: StringTemplate String
tableSTemplate = setAttribute "otcSTemplate" otcSTemplates $ baseTemplate
buildLocationTemplateCSV :: PlowStateStore -> Text -> Text -> Location -> IO String
buildLocationTemplateCSV plowStateStore cName sName l = do
let locName = locationName l
otcList <- fetchOnpingTagCombineds plowStateStore (locationRefId l)
let tableTemplate = buildTableSTemplateCSV cName sName locName otcList
baseTemplate = (newSTMP "$tableTemplate$ \n") :: StringTemplate String
locationSTemplate = setAttribute "tableTemplate" tableTemplate $ baseTemplate
return $ render locationSTemplate
buildSiteTemplateCSV :: PlowStateStore -> Text -> Site -> IO String
buildSiteTemplateCSV plowStateStore cName s = do
let sName = siteName s
locList <- fetchLocations plowStateStore (siteSiteIdRef s)
locationTemplates <- traverse (buildLocationTemplateCSV plowStateStore cName sName) locList
let
baseTemplate = (newSTMP "$location_template$") :: StringTemplate String
siteSTemplate = setAttribute "location_template" (unlines locationTemplates) $ baseTemplate
return $ render siteSTemplate
buildCompanyTemplateCSV :: PlowStateStore -> Text -> IO String
buildCompanyTemplateCSV plowStateStore cName = do
companyList <- fetchCompanies plowStateStore cName
case companyList of
[] -> return "Error: There is no company records match the name given."
_ -> do
siteList <-fetchSites plowStateStore (companyCompanyIdRef . head $ companyList)
siteTemplates <- traverse (buildSiteTemplateCSV plowStateStore cName) siteList
let baseTemplate = (newSTMP "Company Name | Site Name | Location Name | Global Parameter Id | Tag Name | Slave Parameter Id | Parameter Tag ID \n $site_template$ \n") :: StringTemplate String
companySTemplate = setAttribute "company_name" cName .
setAttribute "site_template" (unlines siteTemplates) $ baseTemplate
return $ render companySTemplate
| plow-technologies/onping-tag-report | src/Onping/Tag/Report.hs | bsd-3-clause | 10,288 | 0 | 19 | 2,646 | 1,695 | 847 | 848 | 133 | 2 |
module AI.MDP.GridWorld
(
GridWorld
,GridVal
,GridAction(..)
-- Debug/Visualization Funcs
,showRewards
,showAbsorbs
,showTransition
-- common action results
,deterministicActions
,maybeActions
,maybeReverseActions
,scatterActions
,BlockedCells
,MoveCost
,gridWorld
,reward
,absorb
,initVals
,iterVals
) where
import Text.Printf
import qualified Data.Vector as V
import Data.Vector(Vector, (//), (!))
import AI.MDP
data GridWorld = GridWorld { g_width :: !Int
, g_height :: !Int
, g_blocked :: Vector Bool
, g_mdp :: MDP
} deriving (Show, Eq)
data GridVal = GridVal { gv_gw :: GridWorld
, gv_vals :: !Values
}
renderGrid f g gv@(GridVal gw vs) = vbar ++ concatMap mkRow [0..(height-1)]
where mkRow i = showRow (V.slice (width*i) width (V.zip bs (f gv))) ++ vbar
showRow = (++ "\n") . foldl (\s x -> s ++ buildVal x ++ "|") "|" . V.toList
buildVal (False, v) = take valCellWidth $ g v ++ repeat ' '
buildVal (True, _) = take valCellWidth $ repeat '#'
valCellWidth = 5
vbar = replicate (1 + (valCellWidth+1) * width) '=' ++ "\n"
width = g_width gw
height = g_height gw
bs = g_blocked gw
showRewards gv = putStr $ renderGrid (rewards . g_mdp . gv_gw) (printf "%3.1f") gv
showAbsorbs gv = putStr $ renderGrid (absState . g_mdp . gv_gw) (\x -> case x of { True -> "X"; False -> " "; }) gv
showTransition (x, y) a gv = putStr $ renderGrid getTrans (printf "%3.1f") gv
where getTrans = ((! i) . (! actionI a) . transitions . g_mdp . gv_gw)
gw = gv_gw gv
w = g_width gw
h = g_height gw
i = y*w + x
instance Show GridVal where
show = renderGrid gv_vals (printf "%3.1f")
data GridAction = MoveW | MoveE | MoveN | MoveS | MoveNE | MoveNW | MoveSE | MoveSW | MoveNone deriving (Show, Eq, Ord)
actionI :: GridAction -> Int
actionI MoveW = 0
actionI MoveE = 1
actionI MoveN = 2
actionI MoveS = 3
actionI MoveNE = 4
actionI MoveNW = 5
actionI MoveSE = 6
actionI MoveSW = 7
actionI MoveNone = 8
-- ^ Gives the allowed actions and the results of executing it along with their probabilities
type ActionResult = [(GridAction, Probability)]
type ActionResults = [ActionResult] -- ^ implicit understanding: action results are in order
checkActionResult :: ActionResults -> Bool
checkActionResult = all (\n -> abs (n-1) < 1E10) . map (sum . map snd)
deterministicActions :: ActionResults
deterministicActions = [[(MoveW, 1)]
,[(MoveE, 1)]
,[(MoveN, 1)]
,[(MoveS, 1)]
,[(MoveNE, 1)]
,[(MoveNW, 1)]
,[(MoveSE, 1)]
,[(MoveSW, 1)]]
maybeReverseActions :: Probability -> ActionResults
maybeReverseActions p = [[(MoveW, p), (MoveE, p2)]
,[(MoveE, p), (MoveW, p2)]
,[(MoveN, p), (MoveS, p2)]
,[(MoveS, p), (MoveN, p2)]
,[(MoveNE, p), (MoveSW, p2)]
,[(MoveNW, p), (MoveSE, p2)]
,[(MoveSE, p), (MoveNW, p2)]
,[(MoveSW, p), (MoveNE, p2)]]
where p2 = 1-p
maybeActions :: Probability -> ActionResults
maybeActions p = [[(MoveW, p), (MoveNone, p2)]
,[(MoveE, p), (MoveNone, p2)]
,[(MoveN, p), (MoveNone, p2)]
,[(MoveS, p), (MoveNone, p2)]
,[(MoveNE, p), (MoveNone, p2)]
,[(MoveNW, p), (MoveNone, p2)]
,[(MoveSE, p), (MoveNone, p2)]
,[(MoveSW, p), (MoveNone, p2)]]
where p2 = 1-p
scatterActions :: Probability -> ActionResults
scatterActions p = [[(MoveW, p), (MoveNW, p2), (MoveSW, p2)]
,[(MoveE, p), (MoveNE, p2), (MoveSE, p2)]
,[(MoveN, p), (MoveNE, p2), (MoveNW, p2)]
,[(MoveS, p), (MoveSE, p2), (MoveSW, p2)]
,[(MoveNE, p), (MoveE, p2), (MoveN, p2)]
,[(MoveNW, p), (MoveW, p2), (MoveN, p2)]
,[(MoveSE, p), (MoveE, p2), (MoveS, p2)]
,[(MoveSW, p), (MoveW, p2), (MoveS, p2)]]
where p2 = (1-p)/2
type BlockedCells = [(Int, Int)]
type MoveCost = Double
gridWorld :: (Int, Int) -> Discount -> MoveCost -> ActionResults -> BlockedCells -> GridWorld
gridWorld (w, h) gamma moveCost actionRes blockedCells = GridWorld w h bs mdp
where numStates = w * h
mdp = MDP ts rs as gamma
rs = V.replicate numStates moveCost
as = V.replicate numStates False
nullT = V.replicate numStates 0.0
ts = V.fromList $ map mkActTrans actionRes
bs = V.replicate numStates False // map (\(x,y) -> (x*w + y, True)) blockedCells
mkActTrans ar = V.generate numStates (makeTrans w h bs ar nullT)
makeTrans :: Int -> Int -> Vector Bool -> ActionResult -> Vector Probability -> State -> Vector Probability
makeTrans w h bs ar vs s = V.accum (+) vs (map (\(a,p) -> (getI w h bs s a, p)) ar)
getI :: Int -> Int -> Vector Bool -> State -> GridAction -> State
getI w _ bs i MoveN | i < w || bs ! (i-w) = i
| otherwise = i - w
getI w h bs i MoveS | i >= (w*(h-2)) || bs ! (i+w) = i
| otherwise = i + w
getI w _ bs i MoveW | (i `mod` w) == 0 || bs ! (i-1) = i
| otherwise = i - 1
getI w _ bs i MoveE | (i `mod` w) == (w-1) || bs ! (i+1) = i
| otherwise = i + 1
getI w h bs i MoveNE = getI w h bs (getI w h bs i MoveN) MoveE
getI w h bs i MoveNW = getI w h bs (getI w h bs i MoveN) MoveW
getI w h bs i MoveSE = getI w h bs (getI w h bs i MoveS) MoveE
getI w h bs i MoveSW = getI w h bs (getI w h bs i MoveS) MoveW
getI _ _ _ i MoveNone = i
reward :: (Int, Int) -> Reward -> GridWorld -> GridWorld
reward (x, y) r g = g { g_mdp = mdp' }
where mdp = g_mdp g
w = g_width g
mdp' = mdp { rewards = rewards mdp // [((y * w + x), r)] }
absorb :: (Int, Int) -> Reward -> GridWorld -> GridWorld
absorb (x, y) r g = g { g_mdp = mdp' }
where mdp = g_mdp g
w = g_width g
mdp' = mdp { rewards = rewards mdp // [((y * w + x), r)]
, absState = absState mdp // [((y * w + x), True)] }
initVals :: GridWorld -> GridVal
initVals gw = GridVal gw vs
where vs = V.replicate (w*h) 0.0
w = g_width gw
h = g_height gw
type NumIters = Int
iterVals :: NumIters -> GridVal -> GridVal
iterVals 0 gv = gv
iterVals n (GridVal gw vs) = iterVals (n-1) $ GridVal gw vs'
where vs' = V.fromList $ map iter_ [0..(V.length vs -1)]
mdp = g_mdp gw
iter_ i = let r = rewards mdp ! i
g = discount mdp
t = transitions mdp
isAbsorbing = absState mdp ! i
doAction ts = V.sum (V.zipWith (*) (ts ! i) vs)
in if isAbsorbing
then r
else r + g * V.maximum (V.map doAction t)
| chetant/mdp | AI/MDP/GridWorld.hs | bsd-3-clause | 7,273 | 0 | 15 | 2,520 | 2,982 | 1,680 | 1,302 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable , NoMonomorphismRestriction #-}
import MFlow.Wai.Blaze.Html.All hiding (footer, retry, push)
import qualified MFlow.Wai.Blaze.Html.All as MF(retry)
import Control.Monad.Trans
import Data.Monoid
import Control.Applicative
import Control.Concurrent
import Control.Workflow as WF hiding (step)
import Control.Workflow.Stat
import Control.Concurrent.STM
import Data.Typeable
import Data.TCache.DefaultPersistence
import Data.Persistent.Collection
import Data.ByteString.Lazy.Char8(pack,unpack)
import Data.Map as M (fromList)
import Data.List(isPrefixOf)
import Data.Maybe
import Debug.Trace
import System.IO.Unsafe
(!>) = flip trace
--comprar o reservar
--no está en stock
--reservar libro
--si está en stock pasado un tiempo quitar la reserva
--si está en stock y reservado, comprar
data Book= Book{btitle :: String, stock,reserved :: Int} deriving (Read,Show, Eq,Typeable)
instance Indexable Book where key= btitle
instance Serializable Book where
serialize= pack. show
deserialize= read . unpack
keyBook= "booktitle" :: String
rbook= getDBRef $ keyBook
stm= liftIO . atomically
reservetime= 120 -- 5* 24 * 60 * 60 -- five days waiting for reserve and five days reserved
data RouteOptions= Buy | Other | Reserve | NoReserve deriving (Typeable,Show)
main= do
enterStock 30 rbook
restartWorkflows $ M.fromList [("buyreserve", buyReserve reservetime)]
runNavigation "" . transientNav $ do
op <- page $ absLink Buy "buy or reserve the book" <++ br <|> wlink Other "Do other things"
case op of
Other -> page $ "doing other things" ++> wlink () "home"
Buy -> do
reserved <- stm (do
mr <- readDBRef rbook !> "RESERVING"
case mr of
Nothing -> return False
Just r ->
if reserved r > 0 then return True
else if stock r > 0 then reserveIt rbook >> return True
else return False)
`compensate` (stm (unreserveIt rbook) >> fail "" !> "JUST")
if reserved then do
page $ buyIt keyBook
return() !> "buyit forward"
else reserveOffline keyBook
absLink ref = wcached (show ref) 0 . wlink ref
buyIt keyBook= do
mh <- getHistory "buyreserve" keyBook
p "there is one book for you in stock "
++> case mh of
Nothing -> p "The book was in stock and reserved online right now"
Just hist ->
let histmarkup= mconcat[p << l | l <- hist]
in h2 "History of your reserve:"
<> histmarkup
++> wlink keyBook "buy?"
`waction` (\ key -> do
stm . buy $ getDBRef key
page $ "bought! " ++> wlink () "home"
delWF "buyreserve" key)
<|> (absLink Buy undefined >> return())
reserveOffline keyBook = do
v <- getState "buyreserve" (buyReserve reservetime) keyBook
case v of
Left AlreadyRunning -> lookReserve keyBook
Left err -> error $ show err
Right (name, f, stat) -> do
r <- page $ wlink Reserve "not in stock. Press to reserve it when available in\
\ the next five days. It will be reserved for five days "
<|> br
++> wlink NoReserve "no thanks, go to home"
case r of
Reserve -> do
liftIO $ forkIO $ runWF1 name (buyReserve reservetime keyBook) stat True
return ()
NoReserve -> return()
lookReserve keyBook= do
hist <- getHistory "buyreserve" keyBook `onNothing ` return ["No workflow log"]
let histmarkup= mconcat[p << l | l <- hist]
page $ do
mr <- stm $ readDBRef rbook
if mr== Nothing
|| fmap stock mr == Just 0
&& fmap reserved mr == Just 0
then
"Sorry, not available but you already demanded a reservation when the book\
\ enter in stock"
++> wlink () << p "press here to go home if the book has not arrived"
<++ p "you can refresh or enter this url to verify availability"
<> h2 "status of your request for reservation upto now:"
<> histmarkup
else
h2 "Good! things changed: the book arrived and was reserved"
++> buyIt keyBook
compensate :: Monad m => FlowM v m a -> FlowM v m a -> FlowM v m a
compensate doit undoit= do
back <- goingBack
case back of
False -> doit >>= breturn
True -> undoit
withTimeoutIO flag f = liftIO $ atomically $ (f >> return True)
`orElse` (waitUntilSTM flag >> return False)
buyReserve timereserve keyBook= runFlowOnce f undefined where
f :: FlowM Html (Workflow IO) ()
f= do
let rbook = getDBRef keyBook
lift . logWF $ "You requested the reserve for: "++ keyBook
t <- lift $ getTimeoutFlag timereserve -- $ 5 * 24 * 60 * 60
r <- compensate (step $ withTimeoutIO t (reserveAndMailIt rbook))
(do
lift $ logWF "Unreserving the book"
step $ liftIO . atomically $ unreserveIt rbook >> fail "")
-- liftIO $ atomically $ (reserveAndMailIt rbook >> return True)
-- `orElse` (waitUntilSTM t >> return False)
if not r
then do
lift $ logWF "reservation period ended, no stock available"
return ()
else do
lift $ logWF "The book entered in stock, reserved "
t <- lift $ getTimeoutFlag timereserve -- $ 5 * 24 *60 * 60
r <- step . liftIO $ atomically $ (waitUntilSTM t >> return False)
`orElse` (testBought rbook >> return True)
if r
then do
lift $ logWF "Book was bought at this time"
else do
lift $ logWF "Reserved for a time, but reserve period ended"
fail ""
-- now it is compensated above
-- step . liftIO $ atomically $ unreserveIt rbook
userMail= "[email protected]"
mailQueue= "mailqueue"
reserveAndMailIt rbook= do
let qref = getQRef mailQueue
pushSTM qref ( userMail :: String
, "your book "++ keyObjDBRef rbook ++ " received" :: String
, "Hello, your book...." :: String)
reserveIt rbook
reserveIt rbook = do
mr <- readDBRef rbook !> "RESERVE"
case mr of
Nothing -> retry
Just (Book t s r) ->
if s >0 then writeDBRef rbook $ Book t (s-1) (r+1)
else retry
unreserveIt rbook= do
mr <- readDBRef rbook !> "UNRESERVE"
case mr of
Nothing -> error "unreserveIt: where is the book?"
Just (Book t s r) ->
if r >0 then writeDBRef rbook $ Book t (s+1) (r-1)
else return()
enterStock delay rbook= forkIO $ loop enter
where
loop f= f >> loop f
enter= do
threadDelay $ delay * 1000000
atomically $ do
Book _ n r <- readDBRef rbook `onNothing` return (Book keyBook 0 0)
writeDBRef rbook $ Book "booktitle" (n +1) r
!> "Added 1 more book to the stock"
buy rbook= do
mr <- readDBRef rbook
case mr of
Nothing -> error "Not in stock"
Just (Book t n n') ->
if n' > 0 !> show mr then writeDBRef rbook $ Book t n (n'-1)
!> "There is in Stock and reserved, BOUGHT"
else if n > 0 then
writeDBRef rbook $ Book t (n-1) 0
!> "No reserved, but stock available, BOUGHT"
else error "buy: neither stock nor reserve"
testBought rbook= do
mr <- readDBRef rbook
case mr of
Nothing -> retry !> ("testbought: the register does not exist: " ++ show rbook)
Just (Book t stock reserve) ->
case reserve of
0 -> return()
n -> retry
stopRestart delay timereserve th= do
threadDelay $ delay * 1000000
killThread th !> "workflow KILLED"
syncCache
atomically flushAll
restartWorkflows ( fromList [("buyreserve", buyReserve timereserve)] ) !> "workflow RESTARTED"
getHistory name x= liftIO $ do
let wfname= keyWF name x
let key= keyResource stat0{wfName=wfname}
atomically $ flushKey key
mh <- atomically . readDBRef . getDBRef $ key
case mh of
Nothing -> return Nothing
Just h -> return . Just
. catMaybes
. map eitherToMaybe
. map safeFromIDyn
$ versions h :: IO (Maybe [String])
where
eitherToMaybe (Right r)= Just r
eitherToMaybe (Left _) = Nothing
| agocorona/MFlow | tests/workflow1.hs | bsd-3-clause | 8,659 | 0 | 27 | 2,813 | 2,415 | 1,186 | 1,229 | 198 | 6 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Network.Mail.Locutoria.State where
import Control.Applicative ((<$>), pure)
import Control.Lens hiding (Index)
import Data.Default (def)
import Data.List (elemIndex, find)
import Data.Maybe (catMaybes, isJust, listToMaybe)
import Data.Text (Text)
import Network.Mail.Locutoria.Index hiding (_conversations, conversations)
import qualified Network.Mail.Locutoria.Index as Index
import Network.Mail.Locutoria.Message
import Network.Mail.Locutoria.Notmuch (Database)
import Network.Mail.Locutoria.Channel
import Network.Mail.Locutoria.Conversation
import Network.Mail.Locutoria.View
data State = State
{ _stDatabase :: Database
, _stIndex :: Index
, _stHistory :: History
, _stRefreshing :: Bool
, _stScreenSize :: (Int, Int)
, _stStatus :: Status
}
deriving (Eq, Show)
type History = [View]
data Status = GenericError Text
| Refreshing
| Nominal
deriving (Eq, Show)
makeLenses ''State
mkState :: Database -> State
mkState db = State
{ _stDatabase = db
, _stIndex = def
, _stHistory = []
, _stRefreshing = False
, _stScreenSize = (80, 50)
, _stStatus = Nominal
}
stView :: Lens' State View
stView f st = case st^.stHistory of
v:vs -> (\v' -> st & stHistory .~ (v':vs)) <$> f v
[] -> (\v' -> st & stHistory .~ (v':[])) <$> f Root
pushView :: View -> State -> State
pushView v = stHistory %~ (v:)
popView :: State -> State
popView = stHistory %~ drop 1
replaceView :: View -> State -> State
replaceView v = pushView v . popView
stChannel :: Traversal' State Channel
stChannel = stView . viewChannel
stConversation :: Traversal' State Conversation
stConversation f st = case conv of
Nothing -> pure st
Just c -> updateConv <$> f c
where
conv = case st ^. stView of
ShowChannel _ Nothing -> listToMaybe (stConversations st)
v -> v ^? viewConversation
updateConv c = case st ^. stView of
ShowChannel chan Nothing -> st & stView .~ ShowChannel chan (Just c)
_ -> st & stView . viewConversation .~ c
stMessage :: Traversal' State Message
stMessage f st = case msg of
Nothing -> pure st
Just m -> updateMsg <$> f m
where
msg = case st ^. stView of
ShowConversation _ _ Nothing -> listToMaybe (stMessages st)
v -> v ^? viewMessage
updateMsg m = case st ^. stView of
ShowConversation chan conv Nothing -> st & stView .~ ShowConversation chan conv (Just m)
_ -> st & stView . viewMessage .~ m
stChannelGroups :: State -> [ChannelGroup]
stChannelGroups s =
[ ChannelGroup "Direct" [NoListChannel]
, ChannelGroup "Flagged" [FlaggedChannel]
, ChannelGroup "Lists" ls
]
where
ls = ListChannel <$> lists (s^.stIndex)
stChannels :: State -> [Channel]
stChannels st = catMaybes $ flattenChannelGroups (stChannelGroups st)
stConversations :: State -> [Conversation]
stConversations st = case st ^? stChannel of
Just chan -> filter (inChannel chan) (st^.stIndex.Index.conversations)
Nothing -> []
stMessages :: State -> [Message]
stMessages st = case st ^? stConversation of
Just conv -> conv^.convMessages
Nothing -> []
stChannelIndex :: Traversal' State Int
stChannelIndex f st = case (idx, chan) of
(_, Nothing) -> pure st
(Nothing, _) -> pure st
(Just i, _) -> update <$> f i
where
update i' = case clampedLookup isJust i i' cs of
Just (Just chan') -> st & stChannel .~ chan'
_ -> st
where
chan = st ^? stChannel
cs = flattenChannelGroups $ stChannelGroups st
idx = flip elemIndex cs . Just =<< chan
stConversationIndex :: Traversal' State Int
stConversationIndex f st = case idx of
Nothing -> pure st
Just i -> update . clamp cs <$> f i
where
cs = st^.to stConversations
idx = flip elemIndex cs =<< st ^? stConversation
update idx' = case find (const True) (drop idx' cs) of
Just conv -> st & stConversation .~ conv
Nothing -> st
stMessageIndex :: Traversal' State Int
stMessageIndex f st = case idx of
Nothing -> pure st
Just i -> update . clamp ms <$> f i
where
ms = stMessages st
idx = flip elemIndex ms =<< st ^? stMessage
update idx' = case find (const True) (drop idx' ms) of
Just msg -> st & stMessage .~ msg
Nothing -> st
clamp :: [a] -> Int -> Int
clamp xs i = if i >= 0 then i `min` end else length xs - i `max` 0
where
end = length xs - 1
clampedLookup :: (a -> Bool) -> Int -> Int -> [a] -> Maybe a
clampedLookup p oldIdx newIdx xs = find p xs'
where
idx = if newIdx >= 0 && newIdx < oldIdx
then 0 - (length xs - newIdx)
else newIdx
xs' = if idx >= 0
then drop idx xs
else drop (0 - idx - 1) (reverse xs)
| hallettj/locutoria | Network/Mail/Locutoria/State.hs | bsd-3-clause | 4,908 | 1 | 15 | 1,284 | 1,732 | 915 | 817 | -1 | -1 |
module Base (
-- * General utilities
module Control.Applicative,
module Control.Monad.Extra,
module Data.List.Extra,
module Data.Maybe,
module Data.Semigroup,
module Hadrian.Utilities,
-- * Shake
module Development.Shake,
module Development.Shake.Classes,
module Development.Shake.FilePath,
module Development.Shake.Util,
-- * Basic data types
module Hadrian.Package,
module Stage,
module Way,
-- * Files
configH, ghcVersionH,
-- * Paths
hadrianPath, configPath, configFile, sourcePath, shakeFilesDir,
generatedDir, generatedPath,
stageBinPath, stageLibPath,
templateHscPath, ghcDeps,
relativePackageDbPath, packageDbPath, packageDbStamp, ghcSplitPath
) where
import Control.Applicative
import Control.Monad.Extra
import Control.Monad.Reader
import Data.List.Extra
import Data.Maybe
import Data.Semigroup
import Development.Shake hiding (parallel, unit, (*>), Normal)
import Development.Shake.Classes
import Development.Shake.FilePath
import Development.Shake.Util
import Hadrian.Utilities
import Hadrian.Package
import Stage
import Way
-- | Hadrian lives in the 'hadrianPath' directory of the GHC tree.
hadrianPath :: FilePath
hadrianPath = "hadrian"
-- TODO: Move this to build directory?
-- | Path to system configuration files, such as 'configFile'.
configPath :: FilePath
configPath = hadrianPath -/- "cfg"
-- | Path to the system configuration file generated by the @configure@ script.
configFile :: FilePath
configFile = configPath -/- "system.config"
-- | Path to source files of the build system, e.g. this file is located at
-- @sourcePath -/- "Base.hs"@. We use this to track some of the source files.
sourcePath :: FilePath
sourcePath = hadrianPath -/- "src"
-- TODO: Change @mk/config.h@ to @shake-build/cfg/config.h@.
-- | Path to the generated @mk/config.h@ file.
configH :: FilePath
configH = "mk/config.h"
ghcVersionH :: Action FilePath
ghcVersionH = generatedPath <&> (-/- "ghcversion.h")
-- | The directory in 'buildRoot' containing the Shake database and other
-- auxiliary files generated by Hadrian.
shakeFilesDir :: FilePath
shakeFilesDir = "hadrian"
-- | The directory in 'buildRoot' containing generated source files that are not
-- package-specific, e.g. @ghcplatform.h@.
generatedDir :: FilePath
generatedDir = "generated"
generatedPath :: Action FilePath
generatedPath = buildRoot <&> (-/- generatedDir)
-- | Path to the package database for the given stage of GHC,
-- relative to the build root.
relativePackageDbPath :: Stage -> FilePath
relativePackageDbPath stage = stageString stage -/- "lib" -/- "package.conf.d"
-- | Path to the package database used in a given 'Stage', including
-- the build root.
packageDbPath :: Stage -> Action FilePath
packageDbPath stage = buildRoot <&> (-/- relativePackageDbPath stage)
-- | We use a stamp file to track the existence of a package database.
packageDbStamp :: FilePath
packageDbStamp = ".stamp"
-- | @bin@ directory for the given 'Stage' (including the build root)
stageBinPath :: Stage -> Action FilePath
stageBinPath stage = buildRoot <&> (-/- stageString stage -/- "bin")
-- | @lib@ directory for the given 'Stage' (including the build root)
stageLibPath :: Stage -> Action FilePath
stageLibPath stage = buildRoot <&> (-/- stageString stage -/- "lib")
-- | Files the `ghc` binary depends on
ghcDeps :: Stage -> Action [FilePath]
ghcDeps stage = mapM (\f -> stageLibPath stage <&> (-/- f))
[ "ghc-usage.txt"
, "ghci-usage.txt"
, "llvm-targets"
, "llvm-passes"
, "platformConstants"
, "settings" ]
-- ref: utils/hsc2hs/ghc.mk
-- | Path to 'hsc2hs' template.
templateHscPath :: Stage -> Action FilePath
templateHscPath stage = stageLibPath stage <&> (-/- "template-hsc.h")
-- | @ghc-split@ is a Perl script used by GHC when run with @-split-objs@ flag.
-- It is generated in "Rules.Generate". This function returns the path relative
-- to the build root under which we will copy @ghc-split@.
ghcSplitPath :: Stage -> FilePath
ghcSplitPath stage = stageString stage -/- "bin" -/- "ghc-split"
| bgamari/shaking-up-ghc | src/Base.hs | bsd-3-clause | 4,129 | 0 | 9 | 704 | 642 | 392 | 250 | 74 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Plot.Gauss where
import Types
import PatternRecogn.Gauss.Utils
import PatternRecogn.Utils
import PatternRecogn.Lina as Lina
import PatternRecogn.Gauss.Types
import Graphics.Rendering.Chart.Easy as Chart hiding( Matrix, Vector )
import Graphics.Rendering.Chart.Backend.Diagrams as Chart
-- plot 1-dim data and estimated propability measure (gaussian)
plotProjected :: FilePath -> Vector -> Classes -> ErrT IO ()
plotProjected path dots params =
do
_ <- lift $ Chart.renderableToFile def path $ Chart.toRenderable diagram
return ()
where
diagram :: EC (Layout Double Double) ()
diagram =
do
layout_title .= path
Chart.plot $ points "data points" $
map (\x -> (x, 0)) $
Lina.toList dots
Chart.plot $ line "estimated distribution" $
concat $ map (\Class{..} -> gaussLine (vecToVal class_min) (matToVal class_cov)) $
params
vecToVal :: Vector -> R
vecToVal =
f
.
Lina.toList
where
f [x] = x
f _ = error "error converting to vector to scalar!"
matToVal :: Matrix -> R
matToVal =
f
.
Lina.toLists
where
f [[x]] = x
f _ = error "error converting to vector to scalar!"
gaussLine :: R -> R -> [[(R,R)]]
gaussLine center cov =
return $
map (\x -> (x, mahalanobis (scalar center) (scalar cov) (scalar x))) $
map (
\x -> (center - width / 2) + (x * width / count)
) $
[0..count]
where
count = 100 :: Num a => a
width = 30 * cov
plot :: FilePath -> Matrix -> Classes -> ErrT IO ()
plot path dots params =
do
_ <- lift $ Chart.renderableToFile def path $ Chart.toRenderable diagram
return ()
where
diagram :: EC (Layout Double Double) ()
diagram =
do
layout_title .= path
Chart.plot $ points "data points" $
map vecToTuple2 $
Lina.toRows dots
Chart.plot $
line "classes" $
map (
\Class{..} ->
map vecToTuple2 $
lineFromGauss class_min class_cov
)
params
lineFromGauss :: Vector -> Matrix -> [Vector]
lineFromGauss center cov =
toRows $
(+ asRow center) $ -- shift to center
(<> cov) $ -- multiply with covariance matrix
circleDots
where
circleDots =
cmap cos anglesMat
|||
cmap sin anglesMat
anglesMat =
((count :: Int)><1) angles
angles = (/(2*pi)) <$> ([0..(count-1)] :: [Double])
count :: Num a => a
count = 100
{-
vectorField :: String -> [((R,R),(R,R))] -> EC (Layout R R) (Plot R R)
vectorField title vectors =
fmap plotVectorField $ liftEC $
do
c <- takeColor
plot_vectors_values .= vectors
plot_vectors_style . vector_line_style . line_color .= c
plot_vectors_style . vector_head_style . point_color .= c
plot_vectors_title .= title
----plot_vectors_grid .= grid
-}
| EsGeh/pattern-recognition | test/Plot/Gauss.hs | bsd-3-clause | 2,710 | 68 | 16 | 617 | 916 | 481 | 435 | 82 | 2 |
module Test.Database.Redis.CommandTests (
commandTests
) where
import Database.Redis
import Test.HUnit
import Test.Util
-- ---------------------------------------------------------------------------
-- Tests
--
commandTests :: Test
commandTests = TestLabel "command" $
TestList [ -- * Connection
testPing,
-- * String
testSet, testGet, testGetset, testMget, testSetnx, testMset,
testMsetnx, testIncr, testIncrby, testDecr, testDecrby
]
-- ---------------------------------------------------------------------------
-- Connection
--
-- @todo: is an AUTH test possible?
testPing :: Test
testPing = testWithConn "ping" $ \r -> do
res <- ping r
assertEqual "test that ping returned pong" (RedisString "PONG") res
-- ---------------------------------------------------------------------------
-- String
--
testGet :: Test
testGet = testWithConn "get" $ \r -> do
_ <- set r "mykey" "secret"
res <- get r "mykey"
assertEqual "test that get gets set value" (RedisString "secret") res
testSet :: Test
testSet = testWithConn "set" $ \r -> do
res <- set r "mykey" "secret"
assertBool "test successful set" res
testGetset :: Test
testGetset = testWithConn "getset" $ \r -> do
_ <- set r "mykey" "secret"
res <- getset r "mykey" "new"
assertEqual "test getset returns old value" (RedisString "secret") res
res' <- get r "mykey"
assertEqual "test getset set new value" (RedisString "new") res'
testMget :: Test
testMget = testWithConn "mget" $ \r -> do
_ <- set r "key1" "val1"
_ <- set r "key2" "val2"
_ <- set r "key3" "val3"
res <- mget r ["key1", "key2", "key3"]
assertEqual "test mget returns all values"
(RedisMulti [ RedisString "val1"
, RedisString "val2"
, RedisString "val3" ])
res
testSetnx :: Test
testSetnx = testWithConn "setnx" $ \r -> do
res <- setnx r "mykey" "secret"
assertBool "test set when key does not exist" res
res' <- setnx r "mykey" "secret"
assertBool "test failed set when key already exists" $ not res'
testMset :: Test
testMset = testWithConn "mset" $ \r -> do
mset r [ ("key1", "val1")
, ("key2", "val2")
, ("key3", "val3") ]
res <- mget r ["key1", "key2", "key3"]
assertEqual "test mset set all values"
(RedisMulti [ RedisString "val1"
, RedisString "val2"
, RedisString "val3" ])
res
testMsetnx :: Test
testMsetnx = testWithConn "mset" $ \r -> do
res <- msetnx r [ ("key1", "val1")
, ("key2", "val2")
, ("key3", "val3") ]
assertBool "test msetnx returned success" res
res' <- mget r ["key1", "key2", "key3"]
assertEqual "test msetnx set all values"
(RedisMulti [ RedisString "val1"
, RedisString "val2"
, RedisString "val3" ])
res'
res'' <- msetnx r [ ("key3", "val3")
, ("key4", "val4") ]
assertBool "test msetnx failed when at least one key exists" $ not res''
res''' <- exists r "key4"
assertBool "test msetnx sets no keys on failure" $ not res'''
testIncr :: Test
testIncr = testWithConn "incr" $ \r -> do
res <- incr r "counter"
assertEqual "test incr sets key that didn't exist" (RedisInteger 1) res
res' <- incr r "counter"
assertEqual "test increment" (RedisInteger 2) res'
testIncrby :: Test
testIncrby = testWithConn "incrby" $ \r -> do
res <- incrby r "counter" (iToParam 7)
assertEqual "test incrby sets key that didn't exist" (RedisInteger 7) res
res' <- incrby r "counter" (iToParam 2)
assertEqual "test increment by" (RedisInteger 9) res'
testDecr :: Test
testDecr = testWithConn "decr" $ \r -> do
_ <- set r "counter" (iToParam 10)
res <- decr r "counter"
assertEqual "test decrement" (RedisInteger 9) res
testDecrby :: Test
testDecrby = testWithConn "decrby" $ \r -> do
_ <- set r "counter" (iToParam 10)
res <- decrby r "counter" (iToParam 7)
assertEqual "test decrement by" (RedisInteger 3) res
| brandur/redis-haskell | testsuite/tests/Test/Database/Redis/CommandTests.hs | bsd-3-clause | 4,277 | 0 | 13 | 1,213 | 1,160 | 577 | 583 | 98 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : Andrew Martin
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Andrew Martin <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This module uses the "constraints" package to prove that if all of the
-- columns satisfy the 'HasDefaultVector' constraint, then a vector
-- parameterized over the record has an instance of the generic vector
-- typeclass.
-----------------------------------------------------------------------------
module Data.Vector.Vinyl.Default.Empty.Monomorphic.Implication where
import Data.Constraint
import Data.List.TypeLevel.Constraint (ListAll)
import Data.Vector.Vinyl.Default.Empty.Monomorphic.Internal
import Data.Vector.Vinyl.Default.Types (HasDefaultVector)
import Data.Vinyl.Core (Rec (..))
import Data.Vinyl.Functor (Identity (..))
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
listAllVector :: Rec proxy rs
-> ListAll rs HasDefaultVector :- G.Vector Vector (Rec Identity rs)
listAllVector RNil = Sub Dict
listAllVector (_ :& rs) = Sub $ case listAllVector rs of
Sub Dict -> Dict
listAllMVector :: Rec proxy rs
-> ListAll rs HasDefaultVector :- GM.MVector MVector (Rec Identity rs)
listAllMVector RNil = Sub Dict
listAllMVector (_ :& rs) = Sub $ case listAllMVector rs of
Sub Dict -> Dict
-- listAllVectorBoth :: Rec proxy rs
-- -> ListAll rs HasDefaultVector :- (GM.MVector MVector (Rec Identity rs), G.Vector Vector (Rec Identity rs))
-- listAllVectorBoth RNil = Sub Dict
-- listAllVectorBoth (_ :& rs) = Sub $ case listAllVectorBoth rs of
-- Sub Dict -> Dict
| andrewthad/vinyl-vectors | src/Data/Vector/Vinyl/Default/Empty/Monomorphic/Implication.hs | bsd-3-clause | 2,047 | 0 | 9 | 521 | 289 | 173 | 116 | 21 | 1 |
{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
-- | Simple lenses (from SPJ's talk about lenses) - playground
module Sky.Lens.SimpleLens where
import Data.Functor.Identity
import Control.Applicative (Const(Const,getConst))
data LensR s a = LensR { getR :: s -> a, setR :: a -> s -> s }
type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s
-- From Lens' to LensR
set :: forall s a. Lens' s a -> a -> s -> s
set lens v = runIdentity . lens (Identity . const v)
get :: Lens' s a -> s -> a
get lens = getConst . lens Const
lensToLensR :: Lens' s a -> LensR s a
lensToLensR lens = LensR (get lens) (set lens)
-- From LensR to Lens'
lensRToLens :: LensR s a -> Lens' s a
lensRToLens (LensR getter setter) m s = fmap (flip setter s) (m $ getter s)
-- lensRToLens :: forall f s a. Functor f => LensR s a -> (a -> f a) -> s -> f s
-- lensRtoLens = let
-- -- m :: a -> f a
-- -- s :: s
-- -- getter :: s -> a
-- -- setter :: a -> s -> s
-- modded :: f a
-- modded = m (getter s)
-- setA :: a -> s
-- setA = flip setter s
-- in fmap setA modded -- :: f s
-- Lens' utilities
over :: Lens' s a -> (a -> a) -> s -> s
over lens m = runIdentity . lens (Identity . m)
-- modify, returning the old state
overRet :: Lens' s a -> (a -> a) -> s -> (a, s)
overRet lens m =
-- via: f a = ((,) a)
lens $ \a -> (a, m a)
-- Example
data Person = Person { _name :: String, _salary :: Int }
deriving (Show, Eq)
name :: Lens' Person String
name m p = fmap (\x -> p { _name = x }) (m $ _name p)
personX :: Person
personX = Person "Hans Wurst" 10
-- name :: forall f. Functor f => (String -> f String) -> Person -> f Person
-- name m p = let
-- -- m :: String -> f String
-- -- p :: Person
-- modded :: f String
-- modded = m (_name p)
-- setName :: String -> Person
-- setName x = p { _name = x }
-- in fmap setName modded
data A = A ()
data B = B ()
data C = C ()
data D = D ()
data X = X ()
f :: A -> B
f (A ()) = B ()
| xicesky/sky-haskell-playground | src/Sky/Lens/SimpleLens.hs | bsd-3-clause | 1,998 | 0 | 10 | 554 | 626 | 346 | 280 | 32 | 1 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE Safe #-}
module Data.MessagePack.Result where
import Control.Applicative (Alternative (..), Applicative (..),
(<$>), (<*>))
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import Test.QuickCheck.Arbitrary (Arbitrary (..))
import qualified Test.QuickCheck.Gen as Gen
data Result a
= Success a
| Failure String
deriving (Read, Show, Eq, Functor, Traversable, Foldable)
instance Applicative Result where
pure = Success
Success f <*> x = fmap f x
Failure msg <*> _ = Failure msg
instance Alternative Result where
empty = Failure "empty alternative"
s@Success {} <|> _ = s
_ <|> r = r
instance Monad Result where
return = pure
fail = Failure
Success x >>= f = f x
Failure msg >>= _ = Failure msg
instance Arbitrary a => Arbitrary (Result a) where
arbitrary = Gen.oneof
[ Success <$> arbitrary
, Failure <$> arbitrary
]
| SX91/msgpack-haskell | src/Data/MessagePack/Result.hs | bsd-3-clause | 1,153 | 0 | 8 | 350 | 319 | 174 | 145 | 32 | 0 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module HipChat.AddOn.Types.RoomEvent where
import Control.Lens.AsText (AsText)
import qualified Control.Lens.AsText as AsText
import Data.Aeson (FromJSON, ToJSON, parseJSON, toJSON)
data RoomEvent
= RoomArchived
| RoomCreated
| RoomDeleted
| RoomEnter
| RoomExit
| RoomFileUpload
| RoomMessage
| RoomNotification
| RoomTopicChange
| RoomUnarchived
deriving (Show, Eq)
instance AsText RoomEvent where
enc = \case
RoomArchived -> "room_archived"
RoomCreated -> "room_created"
RoomDeleted -> "room_deleted"
RoomEnter -> "room_enter"
RoomExit -> "room_exit"
RoomFileUpload -> "room_file_upload"
RoomMessage -> "room_message"
RoomNotification -> "room_notification"
RoomTopicChange -> "room_topic_change"
RoomUnarchived -> "room_unarchived"
dec = \case
"room_archived" -> Just RoomArchived
"room_created" -> Just RoomCreated
"room_deleted" -> Just RoomDeleted
"room_enter" -> Just RoomEnter
"room_exit" -> Just RoomExit
"room_file_upload" -> Just RoomFileUpload
"room_message" -> Just RoomMessage
"room_notification" -> Just RoomNotification
"room_topic_change" -> Just RoomTopicChange
"room_unarchived" -> Just RoomUnarchived
_ -> Nothing
instance ToJSON RoomEvent where
toJSON = AsText.toJSON
instance FromJSON RoomEvent where
parseJSON = AsText.parseJSON
| mjhopkins/hipchat | src/HipChat/AddOn/Types/RoomEvent.hs | bsd-3-clause | 1,566 | 0 | 9 | 397 | 302 | 163 | 139 | 46 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Quantity.FR.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Quantity.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = FR}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (QuantityData Cup 2 (Just "café"))
[ "2 tasses de café"
]
, examples (QuantityData Cup 1 Nothing)
[ "une Tasse"
]
, examples (QuantityData Tablespoon 3 (Just "sucre"))
[ "3 Cuillères à soupe de sucre"
]
]
| rfranek/duckling | Duckling/Quantity/FR/Corpus.hs | bsd-3-clause | 954 | 0 | 11 | 225 | 165 | 98 | 67 | 19 | 1 |
-- |A simple msgpack remote procedure call (rpc) system for
-- interacting with the MSF server.
module RPC.SimpleRPC (request) where
import MsgPack
import Data.Char
import Data.Maybe
import Network.HTTP (simpleHTTP)
import Network.HTTP.Base (Request (..), Response (..), RequestMethod (..))
import Network.HTTP.Headers (Header (..), HeaderName (..))
import Network.Stream (Result)
import Network.URI (URI(..),URIAuth(..))
import qualified Data.ByteString as BS
{-| request addr obj establishes a connection to the metasploit server
and then passes obj in a POST request, returning the Object formatted
response. -}
request :: URI -> Object -> IO Object
request uri obj =
simpleHTTP req >>= handleTransportErrors >>= handleApplicationErrors
where
req = Request {
rqURI = uri,
rqMethod = POST,
rqHeaders =
[ Header HdrUserAgent "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
, Header HdrContentType "binary/message-pack"
, Header HdrContentLength (show . BS.length $ body)
] ++ hostHdr,
rqBody = body
}
body = pack obj
hostHdr = fromMaybe [] $ do
auth <- uriAuthority uri
return [ Header HdrHost (uriRegName auth ++ uriPort auth) ]
handleTransportErrors :: Result (Response a) -> IO (Response a)
handleTransportErrors (Right a) = return a
handleTransportErrors (Left e) = error (show e)
handleApplicationErrors :: Response BS.ByteString -> IO Object
handleApplicationErrors response =
case rspCode response of
(2,_,_) -> case unpack (rspBody response) of
Right obj -> return obj
Left err -> fail ("Unable to unpack response: " ++ err)
(x,y,z) -> error (map intToDigit [x,y,z] ++ ' ' : (rspReason response))
| GaloisInc/msf-haskell | src/RPC/SimpleRPC.hs | bsd-3-clause | 1,716 | 0 | 15 | 339 | 504 | 275 | 229 | 36 | 3 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Transformations.Optimising.CaseCopyPropagationSpec where
import Transformations.Optimising.CaseCopyPropagation
import Transformations.Names (ExpChanges(..))
import Test.Hspec
import Grin.TH
import Test.Test hiding (newVar)
import Test.Assertions
import Grin.TypeEnv
import Data.Monoid
import Grin.Pretty
ctxs :: [TestExpContext]
ctxs =
[ emptyCtx
, lastBindR
, firstAlt
, middleAlt
-- , lastAlt
]
--spec :: Spec
--spec = pure ()
-- TODO: Check parsing.
spec :: Spec
spec = testExprContextIn ctxs $ \ctx -> do
it "Example from Figure 4.26" $ do
let teBefore = create $
(newVar "z'" int64_t) <>
(newVar "y'" int64_t) <>
(newVar "x'" int64_t)
let before = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- do
ccp.0 <- case v of
(Ffoo a) -> y' <- foo a
pure y'
(Fbar b) -> z' <- bar b
pure z'
(CInt x') -> pure x'
pure (CInt ccp.0)
pure m0
|]
-- TODO: Inspect type env
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
--(snd (ctx (teBefore, before))) `sameAs` (snd (ctx (teAfter, after)))
it "One node has no Int tagged value" $ do
let typeEnv = emptyTypeEnv
let teBefore = create $
(newVar "z'" float_t) <>
(newVar "y'" int64_t) <>
(newVar "x'" int64_t)
let before = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> pure (CInt x')
pure m0
|]
let after = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> pure (CInt x')
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teBefore, after))), NoChange)
xit "Embedded good case" $ do
let teBefore = create $
(newVar "z'" int64_t) <>
(newVar "y'" int64_t) <>
(newVar "x'" int64_t) <>
(newVar "z1'" int64_t) <>
(newVar "y1'" int64_t) <>
(newVar "x1'" int64_t)
let before = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> u1 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CInt z1')
(CInt x1') -> pure (CInt x1')
pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v'" int64_t <>
newVar "v1'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> u1 <- do
ccp.0 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure y1'
(Fbar b1) -> z1' <- bar b1
pure z1'
(CInt x1') -> pure x1'
pure (CInt ccp.0)
pure (CInt x')
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
it "Embedded bad case" $ do
let teBefore = create $
newVar "z'" int64_t <>
newVar "y'" int64_t <>
newVar "x'" int64_t <>
newVar "y1'" int64_t <>
newVar "z1'" float_t <>
newVar "x1'" int64_t
let before = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> u1 <- do
case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CFloat z1')
(CInt x1') -> pure (CInt x1')
pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- do
ccp.0 <- case v of
(Ffoo a) -> y' <- foo a
pure y'
(Fbar b) -> z' <- bar b
pure z'
(CInt x') -> u1 <- do
case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CFloat z1')
(CInt x1') -> pure (CInt x1')
pure x'
pure (CInt ccp.0)
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
it "Leave the outher, transform the inner" $ do
let teBefore = create $
newVar "z'" float_t <>
newVar "y'" int64_t <>
newVar "x'" int64_t <>
newVar "y1'" int64_t <>
newVar "z1'" int64_t <>
newVar "x1'" int64_t
let before = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> u1 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CInt z1')
(CInt x1') -> pure (CInt x1')
pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v1'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> u1 <- do
ccp.0 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure y1'
(Fbar b1) -> z1' <- bar b1
pure z1'
(CInt x1') -> pure x1'
pure (CInt ccp.0)
pure (CInt x')
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
xit "last expression is a case" $ do
let teBefore = create $
newVar "ax'" int64_t
let before =
[expr|
l2 <- eval l
case l2 of
(CNil) -> pure (CInt 0)
(CCons x xs) -> (CInt x') <- eval x
(CInt s') <- sum xs
ax' <- _prim_int_add x' s'
pure (CInt ax')
|]
let teAfter = extend teBefore $
newVar "l2'" int64_t
let after =
[expr|
l2 <- eval l
do ccp.0 <- case l2 of
(CNil) -> pure 0
(CCons x xs) -> (CInt x') <- eval x
(CInt s') <- sum xs
ax' <- _prim_int_add x' s'
pure ax'
pure (CInt ccp.0)
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
runTests :: IO ()
runTests = hspec spec
| andorp/grin | grin/test/Transformations/Optimising/CaseCopyPropagationSpec.hs | bsd-3-clause | 10,010 | 0 | 22 | 5,572 | 1,136 | 600 | 536 | 90 | 1 |
{-# LANGUAGE CPP, NamedFieldPuns, RecordWildCards #-}
-- | cabal-install CLI command: freeze
--
module Distribution.Client.CmdFreeze (
freezeCommand,
freezeAction,
) where
import Distribution.Client.ProjectPlanning
import Distribution.Client.ProjectConfig
( ProjectConfig(..), ProjectConfigShared(..)
, commandLineFlagsToProjectConfig, writeProjectLocalFreezeConfig
, findProjectRoot )
import Distribution.Client.Targets
( UserConstraint(..) )
import Distribution.Solver.Types.ConstraintSource
( ConstraintSource(..) )
import Distribution.Client.DistDirLayout
( defaultDistDirLayout, defaultCabalDirLayout )
import Distribution.Client.Config
( defaultCabalDir )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Package
( PackageName, packageName, packageVersion )
import Distribution.Version
( VersionRange, thisVersion, unionVersionRanges )
import Distribution.PackageDescription
( FlagAssignment )
import Distribution.Client.Setup
( GlobalFlags, ConfigFlags(..), ConfigExFlags, InstallFlags )
import Distribution.Simple.Setup
( HaddockFlags, fromFlagOrDefault )
import Distribution.Simple.Utils
( die, notice )
import Distribution.Verbosity
( normal )
import Data.Monoid as Monoid
import qualified Data.Map as Map
import Data.Map (Map)
import Control.Monad (unless)
import System.FilePath
import Distribution.Simple.Command
( CommandUI(..), usageAlternatives )
import Distribution.Simple.Utils
( wrapText )
import qualified Distribution.Client.Setup as Client
freezeCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
freezeCommand = Client.installCommand {
commandName = "new-freeze",
commandSynopsis = "Freezes a Nix-local build project",
commandUsage = usageAlternatives "new-freeze" [ "[FLAGS]" ],
commandDescription = Just $ \_ -> wrapText $
"Performs dependency solving on a Nix-local build project, and"
++ " then writes out the precise dependency configuration to cabal.project.freeze"
++ " so that the plan is always used in subsequent builds.",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " new-freeze "
++ " Freeze the configuration of the current project\n"
}
-- | To a first approximation, the @freeze@ command runs the first phase of
-- the @build@ command where we bring the install plan up to date, and then
-- based on the install plan we write out a @cabal.project.freeze@ config file.
--
-- For more details on how this works, see the module
-- "Distribution.Client.ProjectOrchestration"
--
freezeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
freezeAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'freeze' doesn't take any extra arguments: "
++ unwords extraArgs
cabalDir <- defaultCabalDir
let cabalDirLayout = defaultCabalDirLayout cabalDir
projectRootDir <- findProjectRoot
let distDirLayout = defaultDistDirLayout projectRootDir
let cliConfig = commandLineFlagsToProjectConfig
globalFlags configFlags configExFlags
installFlags haddockFlags
(_, elaboratedPlan, _, _) <-
rebuildInstallPlan verbosity
projectRootDir distDirLayout cabalDirLayout
cliConfig
let freezeConfig = projectFreezeConfig elaboratedPlan
writeProjectLocalFreezeConfig projectRootDir freezeConfig
notice verbosity $
"Wrote freeze file: " ++ projectRootDir </> "cabal.project.freeze"
where
verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
-- | Given the install plan, produce a config value with constraints that
-- freezes the versions of packages used in the plan.
--
projectFreezeConfig :: ElaboratedInstallPlan -> ProjectConfig
projectFreezeConfig elaboratedPlan =
Monoid.mempty {
projectConfigShared = Monoid.mempty {
projectConfigConstraints =
concat (Map.elems (projectFreezeConstraints elaboratedPlan))
}
}
-- | Given the install plan, produce solver constraints that will ensure the
-- solver picks the same solution again in future in different environments.
--
projectFreezeConstraints :: ElaboratedInstallPlan
-> Map PackageName [(UserConstraint, ConstraintSource)]
projectFreezeConstraints plan =
--
-- TODO: [required eventually] this is currently an underapproximation
-- since the constraints language is not expressive enough to specify the
-- precise solution. See https://github.com/haskell/cabal/issues/3502.
--
-- For the moment we deal with multiple versions in the solution by using
-- constraints that allow either version. Also, we do not include any
-- /version/ constraints for packages that are local to the project (e.g.
-- if the solution has two instances of Cabal, one from the local project
-- and one pulled in as a setup deps then we exclude all constraints on
-- Cabal, not just the constraint for the local instance since any
-- constraint would apply to both instances). We do however keep flag
-- constraints of local packages.
--
deleteLocalPackagesVersionConstraints
(Map.unionWith (++) versionConstraints flagConstraints)
where
versionConstraints :: Map PackageName [(UserConstraint, ConstraintSource)]
versionConstraints =
Map.mapWithKey
(\p v -> [(UserConstraintVersion p v, ConstraintSourceFreeze)])
versionRanges
versionRanges :: Map PackageName VersionRange
versionRanges =
Map.fromListWith unionVersionRanges $
[ (packageName pkg, thisVersion (packageVersion pkg))
| InstallPlan.PreExisting pkg <- InstallPlan.toList plan
]
++ [ (packageName pkg, thisVersion (packageVersion pkg))
| InstallPlan.Configured pkg <- InstallPlan.toList plan
]
flagConstraints :: Map PackageName [(UserConstraint, ConstraintSource)]
flagConstraints =
Map.mapWithKey
(\p f -> [(UserConstraintFlags p f, ConstraintSourceFreeze)])
flagAssignments
flagAssignments :: Map PackageName FlagAssignment
flagAssignments =
Map.fromList
[ (pkgname, flags)
| InstallPlan.Configured elab <- InstallPlan.toList plan
, let flags = elabFlagAssignment elab
pkgname = packageName elab
, not (null flags) ]
-- As described above, remove the version constraints on local packages,
-- but leave any flag constraints.
deleteLocalPackagesVersionConstraints
:: Map PackageName [(UserConstraint, ConstraintSource)]
-> Map PackageName [(UserConstraint, ConstraintSource)]
deleteLocalPackagesVersionConstraints =
#if MIN_VERSION_containers(0,5,0)
Map.mergeWithKey
(\_pkgname () constraints ->
case filter (not . isVersionConstraint . fst) constraints of
[] -> Nothing
constraints' -> Just constraints')
(const Map.empty) id
localPackages
#else
Map.mapMaybeWithKey
(\pkgname constraints ->
if pkgname `Map.member` localPackages
then case filter (not . isVersionConstraint . fst) constraints of
[] -> Nothing
constraints' -> Just constraints'
else Just constraints)
#endif
isVersionConstraint UserConstraintVersion{} = True
isVersionConstraint _ = False
localPackages :: Map PackageName ()
localPackages =
Map.fromList
[ (packageName elab, ())
| InstallPlan.Configured elab <- InstallPlan.toList plan
, elabLocalToProject elab
]
| sopvop/cabal | cabal-install/Distribution/Client/CmdFreeze.hs | bsd-3-clause | 8,028 | 0 | 14 | 1,899 | 1,274 | 720 | 554 | 133 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeApplications #-}
-- | typesafe printf in haskell
--
-- who needs idris lol
--
-- we didn't even need -XTypeInType :p
import GHC.TypeLits
import GHC.Types
import Data.Proxy
-- | Type level token
data Token = Var Type
| Const Symbol
type family Tokenize (s :: [Symbol]) :: ([Token]) where
Tokenize ("%i" ': xs) = Var Int ': Tokenize xs
Tokenize ("%s" ': xs) = Var String ': Tokenize xs
Tokenize (x ': xs) = Const x ': Tokenize xs
Tokenize ('[]) = '[]
-- | Arbitrarily sized products encoded in a GADT.
--
-- aka an HList.
--
data HList (k :: [Type]) where
Nil :: HList '[]
(:+) :: x -> HList xs -> HList (x ':xs)
-- | Now we need a way to generate a function
-- at both the term and type level
-- that grows as we recurse down
-- our typelevel list of tokens
class Parseable (s :: [Token]) where
type Needs s :: [Type]
printf'' :: Proxy s -> HList (Needs s) -> String
instance Parseable ('[]) where
type Needs '[] = '[]
printf'' _ x = ""
instance (KnownSymbol str, Parseable as) => Parseable (Const str ': as) where
type Needs (Const str ': as) = Needs as
printf'' _ x = symbolVal (Proxy :: Proxy str)
++ printf'' (Proxy :: Proxy as) x
instance {-# OVERLAPS #-} (Parseable as) => Parseable (Var String ': as) where
type Needs (Var String ': as) = (String ': (Needs as))
printf'' _ (x :+ xs) = x
++ printf'' (Proxy :: Proxy as) xs
instance (Show a, Parseable as) => Parseable (Var a ': as) where
type Needs (Var a ': as) = (a ': (Needs as))
printf'' _ (x :+ xs) = show x
++ printf'' (Proxy :: Proxy as) xs
-- | Uncurried version.
printf' :: forall l. (Parseable (Tokenize l)) => Proxy l -> HList (Needs (Tokenize l)) -> String
printf' _ = printf'' (Proxy :: Proxy (Tokenize l))
-- | Can we generalize currying for arbitrarily sized products?
--
-- Here's plain old currying:
curry' :: ((a, b) -> c) -> (a -> b -> c)
curry' f head = g
where
g tail = f (head, tail)
class Curryable k o where
type Curried k o
genCurry :: (HList k -> o) -> Curried k o
-- | base case
instance Curryable '[] o where
type Curried '[] o = o
genCurry f = f Nil
-- | inductive case
instance (Curryable as o) => Curryable (a ': as) o where
type Curried (a ': as) o = (a -> Curried as o)
genCurry f head = genCurry g
where
g tail = f (head :+ tail)
-- | Type-safe printf in Haskell!
printf :: forall l. (Parseable (Tokenize l), Curryable (Needs (Tokenize l)) String) => Curried (Needs (Tokenize l)) String
printf = genCurry (printf' (Proxy @l))
cool :: String
cool = printf @'["cool mayn"]
greet :: String -> String
greet = printf @'["hello ", "%s", "!"]
tellAge :: String -> Int -> String
tellAge = printf @'["%s", " is ", "%i", " years old."]
| sleexyz/haskell-fun | TypeSafePrintF.hs | bsd-3-clause | 3,196 | 0 | 13 | 735 | 1,140 | 617 | 523 | 67 | 1 |
module Main where
import Test.Tasty
import Test.Tasty.HUnit
-- import qualified TicTacToeTest as TTTT
-- import qualified GameOfLifeTest as GOL
-- import qualified HearthstoneTest as HT
-- import qualified RomanNumeralTest as RN
import qualified PokerHandsTest as PH
import qualified PokerHoldEmTest as PHT
main :: IO ()
main = defaultMain (testGroup "new group" [
-- TTTT.tests2
--, GOL.tests2
--, HT.tests
--, RN.tests2
-- PH.tests2
PHT.tests2
])
| steveshogren/haskell-katas | test/MainTest.hs | bsd-3-clause | 600 | 0 | 9 | 215 | 67 | 45 | 22 | 8 | 1 |
module Y2017.Day09 (answer1, answer2) where
import Data.Functor
import Data.Void
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.Megaparsec
import Text.Megaparsec.Char
type Parser = Parsec Void Text
answer1, answer2 :: IO ()
answer1 = parseInput >>= print . streamSize
answer2 = parseInput >>= print . garbageSize
streamSize = go 1
where go n (Garbage _) = 0
go n (Group gs) = n + sum (fmap (go (n+1)) gs)
garbageSize (Garbage t) = T.length t
garbageSize (Group gs) = sum $ fmap garbageSize gs
data Stuff = Group [Stuff] | Garbage Text deriving Show
parseInput = parseStream <$> T.readFile "data/2017/day09.txt"
parseStream :: Text -> Stuff
parseStream s = case parse parseGroup "stream" s of
Left err -> error (show err)
Right x -> x
parseGroup = Group <$> between (char '{') (char '}') (parseStuff `sepBy` char ',')
parseStuff :: Parser Stuff
parseStuff = parseGroup <|> parseGarbage
parseGarbage = Garbage <$> between (char '<') (char '>') garbageContent
-- don't parse cancelled characters
garbageContent :: Parser Text
garbageContent = T.concat <$> many
( try (char '!' *> (T.singleton <$> asciiChar) $> T.pack "")
<|> (T.singleton <$> satisfy (/= '>'))
)
| geekingfrog/advent-of-code | src/Y2017/Day09.hs | bsd-3-clause | 1,270 | 0 | 15 | 247 | 474 | 252 | 222 | 31 | 2 |
----------------------------------------------------------------------------
-- |
-- Module : Haskell.Language.Server.Tags.Types.Imports
-- Copyright : (c) Sergey Vinokurov 2018
-- License : BSD3-style (see LICENSE)
-- Maintainer : [email protected]
----------------------------------------------------------------------------
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Haskell.Language.Server.Tags.Types.Imports
( ImportKey(..)
, ImportTarget(..)
, ImportSpec(..)
, importBringsUnqualifiedNames
, importBringsQualifiedNames
, importBringsNamesQualifiedWith
, ImportQualification(..)
, hasQualifier
, getQualifier
, ImportListSpec(..)
, ImportType(..)
, ImportList(..)
, EntryWithChildren(..)
, mkEntryWithoutChildren
, ChildrenVisibility(..)
) where
import Control.DeepSeq
import Data.Hashable
import Data.Map.Strict (Map)
import Data.Set (Set)
import Data.Store (Store)
import Data.Text.Prettyprint.Doc.Ext
import GHC.Generics (Generic)
import Data.KeyMap (KeyMap, HasKey(..))
import Data.SubkeyMap (HasSubkey(..))
import Data.SymbolMap (SymbolMap)
import qualified Data.SymbolMap as SM
import Data.Symbols
import qualified Haskell.Language.Lexer.FastTags as FastTags
-- | Handle for when particular module enters another module's scope.
data ImportKey = ImportKey
{ -- | Whether this import statement is annotated with {-# SOURCE #-} pragma.
-- This means that it refers to .hs-boot file, rather than vanilla .hs file.
ikImportTarget :: !ImportTarget
-- | Name of imported module
, ikModuleName :: !ModuleName
} deriving (Eq, Ord, Show, Generic)
instance Hashable ImportKey
instance NFData ImportKey
instance Store ImportKey
instance HasSubkey ImportKey where
type Subkey ImportKey = ModuleName
getSubkey = ikModuleName
instance Pretty ImportKey where
pretty ik =
"ImportKey" <+> pretty (ikImportTarget ik) <+> pretty (ikModuleName ik)
data ImportTarget = VanillaModule | HsBootModule
deriving (Eq, Ord, Show, Enum, Bounded, Generic)
instance Hashable ImportTarget
instance NFData ImportTarget
instance Store ImportTarget
instance Pretty ImportTarget where
pretty = ppGeneric
-- | Information about import statement
data ImportSpec = ImportSpec
{ ispecImportKey :: !ImportKey
, ispecQualification :: !ImportQualification
, ispecImportList :: !(ImportListSpec ImportList)
} deriving (Eq, Ord, Show, Generic)
instance NFData ImportSpec
instance Store ImportSpec
instance Pretty ImportSpec where
pretty = ppGeneric
-- NB See [Record fields visibility] why this function must not be
-- incorporated into main name resolution logic (i.e. the 'LoadModule' module).
importBringsUnqualifiedNames :: SymbolMap -> ImportSpec -> Maybe SymbolMap
importBringsUnqualifiedNames exportedNames ImportSpec{ispecQualification} =
case ispecQualification of
Qualified _ ->
case foldMap
(\(p, children) ->
-- [Record fields visibility]
-- Functions associated with a type will likely be names of
-- fields, which do come unqualified. But actual functions don't (!).
-- That's why this logic is not incorporated into main name resolution,
-- but only in search.
if resolvedSymbolType p == FastTags.Type
then filter ((== FastTags.Function) . resolvedSymbolType) children
else [])
(SM.childrenRelations exportedNames) of
[] -> Nothing
xs -> Just $ SM.fromList xs
Unqualified -> Just exportedNames
BothQualifiedAndUnqualified _ -> Just exportedNames
importBringsQualifiedNames :: ImportSpec -> Bool
importBringsQualifiedNames ImportSpec{ispecQualification} =
case ispecQualification of
Qualified _ -> True
Unqualified -> False
BothQualifiedAndUnqualified _ -> True
importBringsNamesQualifiedWith :: ImportSpec -> ImportQualifier -> Bool
importBringsNamesQualifiedWith ImportSpec{ispecQualification} q =
getQualifier ispecQualification == Just q
data ImportQualification =
-- | Qualified import, e.g.
--
-- import qualified X as Y
--
-- The ModuleName field would store "Y" in this case.
--
-- import qualified X - field would store "X"
Qualified !ImportQualifier
-- | Vanilla import, e.g.
--
-- import X
| Unqualified
-- | Vanilla import with explicit alias, e.g.
--
-- import X as Y
| BothQualifiedAndUnqualified !ImportQualifier
deriving (Eq, Ord, Show, Generic)
instance Hashable ImportQualification
instance NFData ImportQualification
instance Store ImportQualification
instance Pretty ImportQualification where
pretty = ppGeneric
hasQualifier :: ImportQualifier -> ImportQualification -> Bool
hasQualifier qual = maybe False (== qual) . getQualifier
getQualifier :: ImportQualification -> Maybe ImportQualifier
getQualifier (Qualified q) = Just q
getQualifier Unqualified = Nothing
getQualifier (BothQualifiedAndUnqualified q) = Just q
data ImportType =
-- | Explicit import list of an import statement, e.g.
--
-- import Foo (x, y, z(Baz))
-- import Bar ()
Imported
| -- | Hiding import list
--
-- import Foo hiding (x, y(Bar), z)
-- import Foo hiding ()
Hidden
deriving (Eq, Ord, Show, Generic)
instance Hashable ImportType
instance NFData ImportType
instance Store ImportType
instance Pretty ImportType where
pretty = ppGeneric
data ImportListSpec a =
NoImportList
-- | When we canot precisely analyse an import list it's
-- conservatively defaulted to "import all".
| AssumedWildcardImportList
| SpecificImports !a
deriving (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (ImportListSpec a)
instance Store a => Store (ImportListSpec a)
instance Pretty a => Pretty (ImportListSpec a) where
pretty = ppGeneric
-- | User-provided import/hiding list.
data ImportList = ImportList
{ ilEntries :: !(KeyMap Set (EntryWithChildren () UnqualifiedSymbolName))
, ilImportType :: !ImportType
} deriving (Eq, Ord, Show, Generic)
instance NFData ImportList
instance Store ImportList
instance Pretty ImportList where
pretty ImportList{ilImportType, ilEntries} =
ppFoldableHeader ("Import list[" <> pretty ilImportType <> "]") ilEntries
data EntryWithChildren childAnn name = EntryWithChildren
{ entryName :: !name
, entryChildrenVisibility :: !(Maybe (ChildrenVisibility childAnn))
} deriving (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
instance (NFData a, NFData b) => NFData (EntryWithChildren a b)
instance (Store a, Store b) => Store (EntryWithChildren a b)
instance (Pretty ann, Pretty name) => Pretty (EntryWithChildren ann name) where
pretty = ppGeneric
mkEntryWithoutChildren :: a -> EntryWithChildren ann a
mkEntryWithoutChildren name = EntryWithChildren name Nothing
instance HasKey (EntryWithChildren ann UnqualifiedSymbolName) where
type Key (EntryWithChildren ann UnqualifiedSymbolName) = UnqualifiedSymbolName
{-# INLINE getKey #-}
getKey = entryName
instance HasKey (EntryWithChildren ann SymbolName) where
type Key (EntryWithChildren ann SymbolName) = SymbolName
{-# INLINE getKey #-}
getKey = entryName
data ChildrenVisibility ann =
-- | Wildcard import/export, e.g. Foo(..)
VisibleAllChildren
-- | Import/export with explicit list of children, e.g. Foo(Bar, Baz), Quux(foo, bar).
-- Set is always non-empty.
| VisibleSpecificChildren !(Map UnqualifiedSymbolName ann)
-- | Wildcard export with some things added in, so they'll be visible on
-- wildcard import, e.g.
-- ErrorCall(..,ErrorCall)
| VisibleAllChildrenPlusSome !(Map UnqualifiedSymbolName ann)
deriving (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (ChildrenVisibility a)
instance Store a => Store (ChildrenVisibility a)
instance Pretty a => Pretty (ChildrenVisibility a) where
pretty = ppGeneric
| sergv/tags-server | src/Haskell/Language/Server/Tags/Types/Imports.hs | bsd-3-clause | 8,319 | 0 | 17 | 1,626 | 1,657 | 905 | 752 | 187 | 5 |
-----------------------------------------------------------------------------
-- Pred: Predicates
--
-- Part of `Typing Haskell in Haskell', version of November 23, 2000
-- Copyright (c) Mark P Jones and the Oregon Graduate Institute
-- of Science and Technology, 1999-2000
--
-- This program is distributed as Free Software under the terms
-- in the file "License" that is included in the distribution
-- of this software, copies of which may be obtained from:
-- http://www.cse.ogi.edu/~mpj/thih/
--
-----------------------------------------------------------------------------
module Pred where
import Data.List(union,(\\))
import Control.Monad(msum)
import Id
import Kind
import Type
import Subst
import Unify
import PPrint
data Qual t = [Pred] :=> t
deriving Eq
instance PPrint t => PPrint (Qual t) where
pprint (ps :=> t) = (pprint ps <+> text ":=>") $$ nest 2 (parPprint t)
data Pred = IsIn Id Type
deriving Eq
instance PPrint Pred where
pprint (IsIn i t) = text "isIn1" <+> text ("c" ++ i) <+> parPprint t
instance Types t => Types (Qual t) where
apply s (ps :=> t) = apply s ps :=> apply s t
tv (ps :=> t) = tv ps `union` tv t
instance Types Pred where
apply s (IsIn i t) = IsIn i (apply s t)
tv (IsIn i t) = tv t
mguPred, matchPred :: Pred -> Pred -> Maybe Subst
mguPred = lift mgu
matchPred = lift match
lift m (IsIn i t) (IsIn i' t')
| i == i' = m t t'
| otherwise = fail "classes differ"
type Class = ([Id], [Inst])
type Inst = Qual Pred
-----------------------------------------------------------------------------
data ClassEnv = ClassEnv { classes :: Id -> Maybe Class,
defaults :: [Type] }
super :: ClassEnv -> Id -> [Id]
super ce i = case classes ce i of Just (is, its) -> is
insts :: ClassEnv -> Id -> [Inst]
insts ce i = case classes ce i of Just (is, its) -> its
defined :: Maybe a -> Bool
defined (Just x) = True
defined Nothing = False
modify :: ClassEnv -> Id -> Class -> ClassEnv
modify ce i c = ce{classes = \j -> if i==j then Just c
else classes ce j}
initialEnv :: ClassEnv
initialEnv = ClassEnv { classes = \i -> fail "class not defined",
defaults = [tInteger, tDouble] }
type EnvTransformer = ClassEnv -> Maybe ClassEnv
infixr 5 <:>
(<:>) :: EnvTransformer -> EnvTransformer -> EnvTransformer
(f <:> g) ce = do ce' <- f ce
g ce'
addClass :: Id -> [Id] -> EnvTransformer
addClass i is ce
| defined (classes ce i) = fail "class already defined"
| any (not . defined . classes ce) is = fail "superclass not defined"
| otherwise = return (modify ce i (is, []))
addPreludeClasses :: EnvTransformer
addPreludeClasses = addCoreClasses <:> addNumClasses
addCoreClasses :: EnvTransformer
addCoreClasses = addClass "Eq" []
<:> addClass "Ord" ["Eq"]
<:> addClass "Show" []
<:> addClass "Read" []
<:> addClass "Bounded" []
<:> addClass "Enum" []
<:> addClass "Functor" []
<:> addClass "Monad" []
addNumClasses :: EnvTransformer
addNumClasses = addClass "Num" ["Eq", "Show"]
<:> addClass "Real" ["Num", "Ord"]
<:> addClass "Fractional" ["Num"]
<:> addClass "Integral" ["Real", "Enum"]
<:> addClass "RealFrac" ["Real", "Fractional"]
<:> addClass "Floating" ["Fractional"]
<:> addClass "RealFloat" ["RealFrac", "Floating"]
addInst :: [Pred] -> Pred -> EnvTransformer
addInst ps p@(IsIn i _) ce
| not (defined (classes ce i)) = fail "no class for instance"
| any (overlap p) qs = fail "overlapping instance"
| otherwise = return (modify ce i c)
where its = insts ce i
qs = [ q | (_ :=> q) <- its ]
c = (super ce i, (ps:=>p) : its)
overlap :: Pred -> Pred -> Bool
overlap p q = defined (mguPred p q)
exampleInsts :: EnvTransformer
exampleInsts = addPreludeClasses
<:> addInst [] (IsIn "Ord" tUnit)
<:> addInst [] (IsIn "Ord" tChar)
<:> addInst [] (IsIn "Ord" tInt)
<:> addInst [IsIn "Ord" (TVar (Tyvar "a" Star)),
IsIn "Ord" (TVar (Tyvar "b" Star))]
(IsIn "Ord" (pair (TVar (Tyvar "a" Star))
(TVar (Tyvar "b" Star))))
-----------------------------------------------------------------------------
bySuper :: ClassEnv -> Pred -> [Pred]
bySuper ce p@(IsIn i t)
= p : concat [ bySuper ce (IsIn i' t) | i' <- super ce i ]
byInst :: ClassEnv -> Pred -> Maybe [Pred]
byInst ce p@(IsIn i t) = msum [ tryInst it | it <- insts ce i ]
where tryInst (ps :=> h) = do u <- matchPred h p
Just (map (apply u) ps)
entail :: ClassEnv -> [Pred] -> Pred -> Bool
entail ce ps p = any (p `elem`) (map (bySuper ce) ps) ||
case byInst ce p of
Nothing -> False
Just qs -> all (entail ce ps) qs
-----------------------------------------------------------------------------
inHnf :: Pred -> Bool
inHnf (IsIn c t) = hnf t
where hnf (TVar v) = True
hnf (TCon tc) = False
hnf (TAp t _) = hnf t
toHnfs :: Monad m => ClassEnv -> [Pred] -> m [Pred]
toHnfs ce ps = do pss <- mapM (toHnf ce) ps
return (concat pss)
toHnf :: Monad m => ClassEnv -> Pred -> m [Pred]
toHnf ce p | inHnf p = return [p]
| otherwise = case byInst ce p of
Nothing -> fail "context reduction"
Just ps -> toHnfs ce ps
simplify :: ClassEnv -> [Pred] -> [Pred]
simplify ce = loop []
where loop rs [] = rs
loop rs (p:ps) | entail ce (rs++ps) p = loop rs ps
| otherwise = loop (p:rs) ps
reduce :: Monad m => ClassEnv -> [Pred] -> m [Pred]
reduce ce ps = do qs <- toHnfs ce ps
return (simplify ce qs)
scEntail :: ClassEnv -> [Pred] -> Pred -> Bool
scEntail ce ps p = any (p `elem`) (map (bySuper ce) ps)
-----------------------------------------------------------------------------
| elben/typing-haskell-in-haskell | Pred.hs | bsd-3-clause | 6,679 | 0 | 14 | 2,295 | 2,236 | 1,139 | 1,097 | 129 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- | Add <http://www.w3.org/TR/cors/ CORS> (cross-origin resource sharing)
-- headers to a Snap application. CORS headers can be added either conditionally
-- or unconditionally to the entire site, or you can apply CORS headers to a
-- single route.
module CORS
(
-- * Applying CORS to a specific response
applyCORS
-- * Option Specification
, CORSOptions(..)
, defaultOptions
-- ** Origin lists
, OriginList(..)
, OriginSet, mkOriginSet, origins
-- * Internals
, HashableURI(..), HashableMethod (..)
) where
import Control.Applicative
import Control.Monad (when)
import Data.CaseInsensitive (CI)
import Data.Foldable (for_)
import Data.Hashable (Hashable(..))
import Data.Maybe (fromMaybe)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Network.URI (URI (..), URIAuth (..), parseURI)
import qualified Data.Attoparsec.Combinator as Attoparsec
import qualified Data.Attoparsec.ByteString.Char8 as Attoparsec
import qualified Data.ByteString.Char8 as Char8
import qualified Data.CaseInsensitive as CI
import qualified Data.HashSet as HashSet
import qualified Data.Text as Text
import qualified Snap.Core as Snap
-- | A set of origins. RFC 6454 specifies that origins are a scheme, host and
-- port, so the 'OriginSet' wrapper around a 'HashSet.HashSet' ensures that each
-- 'URI' constists of nothing more than this.
newtype OriginSet = OriginSet { origins :: HashSet.HashSet HashableURI }
-- | Used to specify the contents of the @Access-Control-Allow-Origin@ header.
data OriginList
= Everywhere
-- ^ Allow any origin to access this resource. Corresponds to
-- @Access-Control-Allow-Origin: *@
| Nowhere
-- ^ Do not allow cross-origin requests
| Origins OriginSet
-- ^ Allow cross-origin requests from these origins.
-- | Specify the options to use when building CORS headers for a response. Most
-- of these options are 'Snap.Handler' actions to allow you to conditionally
-- determine the setting of each header.
data CORSOptions m = CORSOptions
{ corsAllowOrigin :: m OriginList
-- ^ Which origins are allowed to make cross-origin requests.
, corsAllowCredentials :: m Bool
-- ^ Whether or not to allow exposing the response when the omit credentials
-- flag is unset.
, corsExposeHeaders :: m (HashSet.HashSet (CI Char8.ByteString))
-- ^ A list of headers that are exposed to clients. This allows clients to
-- read the values of these headers, if the response includes them.
, corsAllowedMethods :: m (HashSet.HashSet HashableMethod)
-- ^ A list of request methods that are allowed.
, corsAllowedHeaders :: HashSet.HashSet String -> m (HashSet.HashSet String)
-- ^ An action to determine which of the request headers are allowed.
-- This action is supplied the parsed contents of
-- @Access-Control-Request-Headers@.
, corsMaxAge :: m (Maybe Int)
-- ^ Set the maximum number of seconds that a preflight authorization is
-- valid for.
}
-- | Liberal default options. Specifies that:
--
-- * All origins may make cross-origin requests
-- * @allow-credentials@ is true.
-- * No extra headers beyond simple headers are exposed.
-- * @GET@, @POST@, @PUT@, @DELETE@ and @HEAD@ are all allowed.
-- * All request headers are allowed.
--
-- All options are determined unconditionally.
defaultOptions :: Monad m => CORSOptions m
defaultOptions = CORSOptions
{ corsAllowOrigin = return Everywhere
, corsAllowCredentials = return True
, corsExposeHeaders = return HashSet.empty
, corsAllowedMethods =
return $ HashSet.fromList $ map HashableMethod
[ Snap.GET, Snap.POST, Snap.PUT, Snap.DELETE, Snap.HEAD ]
, corsAllowedHeaders = return
, corsMaxAge = return Nothing
}
-- | Apply CORS headers to a specific request. This is useful if you only have
-- a single action that needs CORS headers, and you don't want to pay for
-- conditional checks on every request.
--
-- You should note that 'applyCORS' needs to be used before you add any
-- 'Snap.method' combinators. For example, the following won't do what you want:
--
-- > method POST $ applyCORS defaultOptions $ myHandler
--
-- This fails to work as CORS requires an @OPTIONS@ request in the preflighting
-- stage, but this would get filtered out. Instead, use
--
-- > applyCORS defaultOptions $ method POST $ myHandler
applyCORS :: CORSOptions Snap.Snap -> Snap.Snap () -> Snap.Snap ()
applyCORS options m = do
mbRawOrigin <- getHeader "Origin"
case decodeOrigin =<< mbRawOrigin of
Nothing -> m
Just origin -> corsRequestFrom origin
where
corsRequestFrom origin = do
originList <- corsAllowOrigin options
if origin `inOriginList` originList
then Snap.method Snap.OPTIONS (preflightRequestFrom origin)
<|> handleRequestFrom origin
else m
preflightRequestFrom origin = do
maybeMethod <- fmap (parseMethod . Char8.unpack) <$>
getHeader "Access-Control-Request-Method"
case maybeMethod of
Nothing -> m
Just method -> do
allowedMethods <- corsAllowedMethods options
if method `HashSet.member` allowedMethods
then do
maybeHeaders <-
fromMaybe (Just HashSet.empty) . fmap splitHeaders
<$> getHeader "Access-Control-Request-Headers"
case maybeHeaders of
Nothing -> m
Just headers -> do
allowedHeaders <- corsAllowedHeaders options headers
if not $ HashSet.null $ headers `HashSet.difference` allowedHeaders
then m
else do
addAccessControlAllowOrigin origin
addAccessControlAllowCredentials
commaSepHeader
"Access-Control-Allow-Headers"
Char8.pack (HashSet.toList allowedHeaders)
commaSepHeader
"Access-Control-Allow-Methods"
(Char8.pack . show) (HashSet.toList allowedMethods)
mbMaxAge <- corsMaxAge options
for_ mbMaxAge addAccessControlMaxAge
else m
handleRequestFrom origin = do
addAccessControlAllowOrigin origin
addAccessControlAllowCredentials
exposeHeaders <- corsExposeHeaders options
when (not $ HashSet.null exposeHeaders) $
commaSepHeader
"Access-Control-Expose-Headers"
CI.original (HashSet.toList exposeHeaders)
m
addAccessControlAllowOrigin origin =
addHeader "Access-Control-Allow-Origin"
(encodeUtf8 $ Text.pack $ show origin)
addAccessControlMaxAge maxAge =
addHeader "Access-Control-Max-Age"
$ encodeUtf8 $ Text.pack $ show maxAge
addAccessControlAllowCredentials = do
allowCredentials <- corsAllowCredentials options
when (allowCredentials) $
addHeader "Access-Control-Allow-Credentials" "true"
decodeOrigin = fmap simplifyURI . parseURI . Text.unpack . decodeUtf8
addHeader k v = Snap.modifyResponse (Snap.addHeader k v)
commaSepHeader k f vs =
case vs of
[] -> return ()
_ -> addHeader k $ Char8.intercalate ", " (map f vs)
getHeader = Snap.getsRequest . Snap.getHeader
splitHeaders =
let spaces = Attoparsec.many' Attoparsec.space
headerC = Attoparsec.satisfy (not . (`elem` (" ," :: String)))
headerName = Attoparsec.many' headerC
header = spaces *> headerName <* spaces
parser = HashSet.fromList <$> header `Attoparsec.sepBy` (Attoparsec.char ',')
in either (const Nothing) Just . Attoparsec.parseOnly parser
mkOriginSet :: [URI] -> OriginSet
mkOriginSet = OriginSet . HashSet.fromList . map (HashableURI . simplifyURI)
simplifyURI :: URI -> URI
simplifyURI uri = uri { uriAuthority = fmap simplifyURIAuth (uriAuthority uri)
, uriPath = ""
, uriQuery = ""
, uriFragment = ""
}
where simplifyURIAuth auth = auth { uriUserInfo = "" }
--------------------------------------------------------------------------------
parseMethod :: String -> HashableMethod
parseMethod "GET" = HashableMethod Snap.GET
parseMethod "POST" = HashableMethod Snap.POST
parseMethod "HEAD" = HashableMethod Snap.HEAD
parseMethod "PUT" = HashableMethod Snap.PUT
parseMethod "DELETE" = HashableMethod Snap.DELETE
parseMethod "TRACE" = HashableMethod Snap.TRACE
parseMethod "OPTIONS" = HashableMethod Snap.OPTIONS
parseMethod "CONNECT" = HashableMethod Snap.CONNECT
parseMethod "PATCH" = HashableMethod Snap.PATCH
parseMethod s = HashableMethod $ Snap.Method (Char8.pack s)
--------------------------------------------------------------------------------
-- | A @newtype@ over 'URI' with a 'Hashable' instance.
newtype HashableURI = HashableURI URI
deriving (Eq)
instance Show HashableURI where
show (HashableURI u) = show u
instance Hashable HashableURI where
hashWithSalt s (HashableURI (URI scheme authority path query fragment)) =
s `hashWithSalt`
scheme `hashWithSalt`
fmap hashAuthority authority `hashWithSalt`
path `hashWithSalt`
query `hashWithSalt`
fragment
where
hashAuthority (URIAuth userInfo regName port) =
s `hashWithSalt`
userInfo `hashWithSalt`
regName `hashWithSalt`
port
inOriginList :: URI -> OriginList -> Bool
_ `inOriginList` Nowhere = False
_ `inOriginList` Everywhere = True
origin `inOriginList` (Origins (OriginSet xs)) =
HashableURI origin `HashSet.member` xs
--------------------------------------------------------------------------------
newtype HashableMethod = HashableMethod Snap.Method
deriving (Eq)
instance Hashable HashableMethod where
hashWithSalt s (HashableMethod Snap.GET) = s `hashWithSalt` (0 :: Int)
hashWithSalt s (HashableMethod Snap.HEAD) = s `hashWithSalt` (1 :: Int)
hashWithSalt s (HashableMethod Snap.POST) = s `hashWithSalt` (2 :: Int)
hashWithSalt s (HashableMethod Snap.PUT) = s `hashWithSalt` (3 :: Int)
hashWithSalt s (HashableMethod Snap.DELETE) = s `hashWithSalt` (4 :: Int)
hashWithSalt s (HashableMethod Snap.TRACE) = s `hashWithSalt` (5 :: Int)
hashWithSalt s (HashableMethod Snap.OPTIONS) = s `hashWithSalt` (6 :: Int)
hashWithSalt s (HashableMethod Snap.CONNECT) = s `hashWithSalt` (7 :: Int)
hashWithSalt s (HashableMethod Snap.PATCH) = s `hashWithSalt` (8 :: Int)
hashWithSalt s (HashableMethod (Snap.Method m)) =
s `hashWithSalt` (9 :: Int) `hashWithSalt` m
instance Show HashableMethod where
show (HashableMethod m) = show m
| GaloisInc/verification-game | web-prover/src/CORS.hs | bsd-3-clause | 10,675 | 0 | 28 | 2,374 | 2,159 | 1,176 | 983 | 178 | 8 |
-- Min Zhang
-- March 2, 2016
-- LongestAlignment
-- BLAST algorithm
-- Find longest strech of matching
-- random generation sequences that match the probability
-- Not working yet
seq1 = [0, -1, -2, -1, -2, -1, -2, -1, 0, 1, 0, -1, -2, -3, -4]
value = fst
pos = snd
f [] (a, b, c, d) = (a, b, c, d)
f (x:xs) (min_, max_, minLoc, maxLoc)
| value x < min_ && minLoc <= maxLoc = f xs (value x, max_, pos x, pos x)
| value x < min_ = f xs (min_, max_, minLoc, maxLoc)
| value x > max_ && (pos x) - minLoc + 1 > len = f xs (min_, value x, minLoc, pos x)
| otherwise = f xs (min_, max_, minLoc, maxLoc)
where len = maxLoc - minLoc + 1
| Min-/HaskellSandbox | src/LongestAlignment.hs | bsd-3-clause | 650 | 0 | 13 | 161 | 337 | 187 | 150 | 10 | 1 |
module ActorQueue where
import Control.Category
import Control.Lens
import qualified Data.Dequeue as DQ
import Prelude hiding (Either(..), id, (.))
import Entity
type ActorQueue = DQ.BankersDequeue EntityRef
dropFront :: ActorQueue -> ActorQueue
dropFront queue =
case DQ.popFront queue of
Nothing -> DQ.empty
Just (_ ,q) -> q
rotate :: ActorQueue -> ActorQueue
rotate queue = queueChoice
where
potentialQ = do
(exiting,queue') <- DQ.popFront queue
return $ DQ.pushBack queue' exiting
queueChoice =
case potentialQ of
Nothing -> queue
(Just q) -> q
actionPointsOfEntity :: Maybe Entity -> Maybe Int
actionPointsOfEntity eM = do
e <- eM
actor' <- e ^. actor
return $ actor' ^. actionPoints
enoughActionPoints :: Maybe Int -> Bool
enoughActionPoints p =
case p of
Nothing -> False
Just p' -> p' > 0
stillActive :: Maybe Entity -> Bool
stillActive = (enoughActionPoints <<< actionPointsOfEntity)
| fros1y/umbral | src/ActorQueue.hs | bsd-3-clause | 1,010 | 0 | 11 | 252 | 308 | 163 | 145 | 33 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fplugin Brisk.Plugin #-}
{-# OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-}
module Scratch where
import Control.Distributed.Process
main :: Process ()
main = do me <- getSelfPid
spawnLocal $ send me ()
expect
| abakst/brisk-prelude | examples/spawn01.hs | bsd-3-clause | 285 | 0 | 9 | 57 | 52 | 28 | 24 | 9 | 1 |
-- Quantities
-- Copyright (C) 2015-2016 Moritz Schulte <[email protected]>
-- API is not necessarily stable.
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Quantities.Parser
( parseNumber
, parseFraction
, parseInt
, parseDecimal
, parseMixed
, parseQuantity
) where
import Data.Char
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Formatting
import Numeric (readFloat, readSigned)
import Quantities.Types
import Quantities.Units
import Quantities.Util
import Text.Read
-------------
-- Parsers --
-------------
-- | Try to parse an Integer.
parseInt :: Text -> Either Text Integer
parseInt s =
let result = readMaybe (T.unpack s) :: Maybe Integer
in case result of
Nothing -> Left $ format ("Failed to parse integer `" % text % "'") s
Just x -> Right x
-- | Try to parse a fraction of the form "x/y" into a Rational.
parseFraction :: Text -> Either Text Rational
parseFraction s =
let result = readMaybe (T.unpack (T.replace "/" "%" s))
in case result of
Nothing -> Left $ format ("Failed to parse fraction `" % text % "'") s
Just x -> Right x
-- | Try to parse a decimal number.
parseDecimal :: Text -> Either Text Rational
parseDecimal s =
let result = readSigned readFloat (T.unpack s) :: [(Rational, String)]
in case result of
[(x, "")] -> Right x
_ -> Left $ format ("Failed to parse decimal number `" % text % "'") s
-- | Try to parse a mixed number, e.g. a number of the form "5 23/42".
parseMixed :: Text -> Either Text Rational
parseMixed s =
let components = T.words s
in case components of
[c0] ->
if contains '/' c0
then parseFraction c0
else fromInteger <$> parseInt c0
[c0, c1] -> do
i <- parseInt c0
frac <- parseFraction c1
case (i < 0, frac < 0) of
(False, False) -> Right $ fromInteger i + frac
(True, False) -> Right $ -1 * (fromInteger (abs i) + frac)
(False, True) -> Left errNoParse
(True, True) -> Left errNoParse
_ -> Left errNoParse
where errNoParse = "No Parse"
contains c t = (not . T.null . T.filter (== c)) t
-- | Try to parse a given number in string representation. First try
-- to parse it as a decimal number and if that fails, try to parse it
-- as a mixed number.
parseNumber :: Text -> Either Text Rational
parseNumber s' =
let s = T.strip s'
in eitherAlternative "Failed to parse number"
[parseDecimal s, parseMixed s]
-- | Parse a given quantity in its string representation, e.g. a
-- string of the form "0.7 l".
parseQuantity :: (Text -> Either Text Rational) -> Text -> Either Text Quantity
parseQuantity parser s = do
let (w0, w1) = splitAtUnit s
u = stringToUnit w1
num <- parser w0
return $ Quantity num u
where splitAtUnit t =
let num = T.takeWhile (not . isAlpha) t
u = T.drop (T.length num) t
in (num, u)
| mtesseract/quantities | src/Quantities/Parser.hs | bsd-3-clause | 3,083 | 0 | 20 | 851 | 872 | 453 | 419 | 70 | 7 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
module Common where
import Data.Proxy
import Servant.API
#if MIN_VERSION_servant(0,10,0)
import Servant.Utils.Links
#endif
import Miso
import Miso.String
data Model = Model { modelUri :: URI, modelMsg :: String }
deriving (Show, Eq)
data Action
= ServerMsg String
| NoOp
| ChangeURI URI
| HandleURI URI
deriving (Show, Eq)
home :: Model -> View Action
home (Model _ msg) =
div_ [] [div_ [] [h3_ [] [text "SSE (Server-sent events) Example"]], text $ ms msg]
-- There is only a single route in this example
type ClientRoutes = Home
type Home = View Action
handlers :: Model -> View Action
handlers = home
the404 :: View Action
the404 =
div_
[]
[ text "404: Page not found"
, a_ [onClick $ ChangeURI goHome] [text " - Go Home"]
]
goHome :: URI
goHome =
#if MIN_VERSION_servant(0,10,0)
linkURI (safeLink (Proxy :: Proxy ClientRoutes) (Proxy :: Proxy Home))
#else
safeLink (Proxy :: Proxy ClientRoutes) (Proxy :: Proxy Home)
#endif
| dmjio/miso | examples/sse/shared/Common.hs | bsd-3-clause | 1,030 | 0 | 11 | 210 | 293 | 163 | 130 | 31 | 1 |
module Tests.Twitch.Path where
import Test.Hspec
tests :: Spec
tests = return () | menelaos/twitch | tests/Tests/Twitch/Path.hs | mit | 81 | 0 | 6 | 12 | 27 | 16 | 11 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Maxl (runMaxl, MaxlOpt(..)) where
import RarecoalLib.MaxUtils (computeFrequencySpectrum,
makeInitialPoint, minFunc, penalty,
writeFullFitTable,
writeSummaryFitTable)
import RarecoalLib.ModelTemplate (ModelOptions (..),
ModelTemplate (..),
ParamOptions (..),
fillParameterDictWithDefaults,
getModelTemplate, getParamNames,
instantiateModel,
makeParameterDict)
import RarecoalLib.Powell (powellV)
import RarecoalLib.Utils (GeneralOptions (..),
HistogramOptions (..),
loadHistogram, setNrProcessors,
tryEither)
import Data.List (intercalate)
import qualified Data.Vector.Unboxed as V
import Numeric.GSL.Minimization (MinimizeMethod (..), minimize)
import Numeric.LinearAlgebra.Data (toList, toRows)
import System.IO (Handle, IOMode (..), hPutStr,
hPutStrLn, stderr, withFile)
data MaxlOpt = MaxlOpt
{ maGeneralOpts :: GeneralOptions
, maModelOpts :: ModelOptions
, maParamOpts :: ParamOptions
, maHistogramOpts :: HistogramOptions
, maMaxCycles :: Int
, maNrRestarts :: Int
, maOutPrefix :: FilePath
, maUsePowell :: Bool
, maPowellTolerance :: Double
}
runMaxl :: MaxlOpt -> IO ()
runMaxl opts = do
setNrProcessors (maGeneralOpts opts)
modelTemplate <- getModelTemplate (maModelOpts opts)
modelParams <- makeParameterDict (maParamOpts opts) >>= fillParameterDictWithDefaults modelTemplate
_ <- tryEither $ instantiateModel (maGeneralOpts opts) modelTemplate modelParams
let modelBranchNames = mtBranchNames modelTemplate
(hist, siteRed) <- loadHistogram (maHistogramOpts opts) modelBranchNames
xInit <- tryEither $ makeInitialPoint modelTemplate modelParams
_ <- tryEither $ minFunc (maGeneralOpts opts) modelTemplate hist siteRed xInit
let minFunc' = either (const penalty) id .
minFunc (maGeneralOpts opts) modelTemplate hist siteRed
(minResult, trace) <- if maUsePowell opts then do
(r, _, tr) <- powellV (maPowellTolerance opts) (maMaxCycles opts) minFunc' xInit
return (r, tr)
else do
let minimizationRoutine = minimizeV (maMaxCycles opts) minFunc'
minimizeWithRestarts (maNrRestarts opts) minimizationRoutine xInit
let outMaxlFN = maOutPrefix opts ++ ".paramEstimates.txt"
outTraceFN = maOutPrefix opts ++ ".trace.txt"
outFullFitTableFN = maOutPrefix opts ++ ".frequencyFitTable.txt"
outSummaryTableFN = maOutPrefix opts ++ ".summaryFitTable.txt"
withFile outMaxlFN WriteMode $ \h ->
reportMaxResult modelTemplate minResult (minFunc' minResult) h
withFile outTraceFN WriteMode $ \h ->
if maUsePowell opts then
reportTracePowell modelTemplate trace h
else
reportTraceSimplex modelTemplate trace h
let finalModelParams = [(n, r) | ((n, _), r) <- zip modelParams (V.toList minResult)]
finalModelSpec <- tryEither $ instantiateModel (maGeneralOpts opts) modelTemplate finalModelParams
finalSpectrum <- tryEither $ computeFrequencySpectrum finalModelSpec hist modelBranchNames
writeFullFitTable outFullFitTableFN finalSpectrum
writeSummaryFitTable outSummaryTableFN finalSpectrum hist
minimizeV :: Int -> (V.Vector Double -> Double) -> V.Vector Double ->
(V.Vector Double, [V.Vector Double])
minimizeV nrCycles minFunc' initial =
let (vec, trace) =
minimize NMSimplex2 1.0e-8 nrCycles stepWidths (minFunc' . V.fromList) . V.toList $
initial
in (V.fromList vec, map (V.fromList . toList) . toRows $ trace)
where
stepWidths = map (max 1.0e-4 . abs . (0.01*)) . V.toList $ initial
minimizeWithRestarts :: Int
-> (V.Vector Double -> (V.Vector Double, [V.Vector Double]))
-> V.Vector Double
-> IO (V.Vector Double, [V.Vector Double])
minimizeWithRestarts nrRestarts minimizationRoutine initialParams =
go nrRestarts minimizationRoutine (initialParams, [])
where
go 0 _ (res, trace) = return (res, trace)
go n minR (res, trace) = do
hPutStrLn stderr $ "minimizing from point " ++ show res
let (newRes, newTrace) = minR res
go (n - 1) minR (newRes, trace ++ newTrace)
reportMaxResult :: ModelTemplate -> V.Vector Double -> Double -> Handle -> IO ()
reportMaxResult modelTemplate result minScore h = do
hPutStrLn h $ "Score\t" ++ show minScore
hPutStr h . unlines $ zipWith (\p v -> p ++ "\t" ++ show v) (getParamNames modelTemplate) (V.toList result)
reportTraceSimplex :: ModelTemplate -> [V.Vector Double] -> Handle -> IO ()
reportTraceSimplex modelTemplate trace h = do
let header = intercalate "\t" $ ["Nr", "-Log-Likelihood", "Simplex size"] ++ getParamNames modelTemplate
body = map (intercalate "\t" . map show . V.toList) trace
hPutStr h . unlines $ header : body
reportTracePowell :: ModelTemplate -> [V.Vector Double] -> Handle -> IO ()
reportTracePowell modelTemplate trace h = do
let header = intercalate "\t" $ ["Nr", "-Log-Likelihood"] ++ getParamNames modelTemplate
body = do
(i, t) <- zip [(1::Int)..] trace
return $ intercalate "\t" (show i : [show par | par <- V.toList t])
hPutStr h . unlines $ header : body
| stschiff/rarecoal | src-rarecoal/Maxl.hs | gpl-3.0 | 6,005 | 0 | 20 | 1,849 | 1,625 | 840 | 785 | 102 | 3 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2013-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Succinct.Internal.Word4
( Word4(..)
, UM.MVector(MV_Word4)
, U.Vector(V_Word4)
, ny
, wds
, wd
) where
import Control.Monad
import Data.Bits
import Data.Vector.Generic as G
import Data.Vector.Generic.Mutable as GM
import Data.Vector.Primitive as P
import Data.Vector.Primitive.Mutable as PM
import Data.Vector.Unboxed as U
import Data.Vector.Unboxed.Mutable as UM
import Data.Word
newtype Word4 = Word4 Word8 deriving (Eq,Ord)
instance Show Word4 where
showsPrec d (Word4 n) = Prelude.showsPrec d n
instance Read Word4 where
readsPrec d r = [ (Word4 n, r') | (n,r') <- readsPrec d r, n <= 15 ]
instance Num Word4 where
Word4 n + Word4 m = Word4 $ (n + m) .&. 15
Word4 n - Word4 m = Word4 $ (n - m) .&. 15
Word4 n * Word4 m = Word4 $ (n * m) .&. 15
fromInteger n = Word4 (fromInteger n .&. 15)
abs n = n
signum (Word4 n) = Word4 $ signum n
instance Bits Word4 where
Word4 n .&. Word4 m = Word4 (n .&. m)
Word4 n .|. Word4 m = Word4 (n .|. m)
xor (Word4 n) (Word4 m) = Word4 (xor n m .&. 15)
complement (Word4 n) = Word4 (complement n .&. 15)
shift (Word4 n) i = Word4 (shift n i .&. 15)
shiftL (Word4 n) i = Word4 (shiftL n i .&. 15)
shiftR (Word4 n) i = Word4 (shiftR n i .&. 15)
unsafeShiftL (Word4 n) i = Word4 (unsafeShiftL n i .&. 15)
unsafeShiftR (Word4 n) i = Word4 (unsafeShiftR n i .&. 15)
rotate (Word4 n) i = Word4 $ (unsafeShiftL n (i .&. 3) .|. unsafeShiftR n (negate i .&. 3)) .&. 15
rotateL (Word4 n) i = Word4 $ (unsafeShiftL n (i .&. 3) .|. unsafeShiftR n (negate i .&. 3)) .&. 15
rotateR (Word4 n) i = Word4 $ (unsafeShiftL n (negate i .&. 3) .|. unsafeShiftR n (i .&. 3)) .&. 15
bit i = Word4 (bit i .&. 15)
setBit (Word4 n) i = Word4 (setBit n i .&. 15)
clearBit (Word4 n) i = Word4 (clearBit n i .&. 15)
complementBit (Word4 n) i = Word4 (complementBit n i .&. 15)
testBit (Word4 n) i = testBit n i
bitSize _ = 4
isSigned _ = False
popCount (Word4 n) = popCount n
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
bitSizeMaybe _ = Just 4
#endif
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
instance FiniteBits Word4 where
finiteBitSize _ = 4
#endif
instance Real Word4 where
toRational (Word4 n) = toRational n
instance Integral Word4 where
quot (Word4 m) (Word4 n) = Word4 (quot m n .&. 15)
rem (Word4 m) (Word4 n) = Word4 (rem m n .&. 15)
div (Word4 m) (Word4 n) = Word4 (div m n .&. 15)
mod (Word4 m) (Word4 n) = Word4 (mod m n .&. 15)
quotRem (Word4 m) (Word4 n) = case quotRem m n of
(q, r) -> (Word4 $ q .&. 15, Word4 $ r .&. 15)
divMod (Word4 m) (Word4 n) = case divMod m n of
(q, r) -> (Word4 $ q .&. 15, Word4 $ r .&. 15)
toInteger (Word4 n) = toInteger n
instance Bounded Word4 where
minBound = Word4 0
maxBound = Word4 15
instance Enum Word4 where
succ (Word4 n)
| n == 15 = error "Prelude.Enum.succ{Word4}: tried to take `succ' of maxBound"
| otherwise = Word4 (n + 1)
pred (Word4 n)
| n == 0 = error "Prelude.Enum.pred{Word4}: tried to take `pred' of minBound"
| otherwise = Word4 (n - 1)
toEnum n
| n == n .&. 15 = Word4 (fromIntegral n)
| otherwise = error $ "Enum.toEnum{Word4}: tag (" Prelude.++ show n Prelude.++ ") is outside of bounds (0,15)"
fromEnum (Word4 n) = fromEnum n
instance UM.Unbox Word4
ny :: Int -> Int
ny x = x .&. 15
{-# INLINE ny #-}
wd :: Int -> Int
wd x = unsafeShiftR x 4
{-# INLINE wd #-}
wds :: Int -> Int
wds x = unsafeShiftR (x + 15) 4
{-# INLINE wds #-}
getWord4 :: Word64 -> Int -> Word4
getWord4 w n = Word4 $ fromIntegral (unsafeShiftR w (4*n) .&. 0xf)
{-# INLINE getWord4 #-}
setWord4 :: Word64 -> Int -> Word4 -> Word64
setWord4 w n (Word4 w4) = w .&. complement (unsafeShiftL 0xf n4) .|. unsafeShiftL (fromIntegral w4) n4
where !n4 = 4*n
{-# INLINE setWord4 #-}
data instance UM.MVector s Word4 = MV_Word4 {-# UNPACK #-} !Int !(PM.MVector s Word64)
tile :: Word4 -> Word64
tile (Word4 b) = b4
where !b0 = fromIntegral b
!b1 = b0 .|. unsafeShiftL b0 4
!b2 = b1 .|. unsafeShiftL b1 8
!b3 = b2 .|. unsafeShiftL b2 16
!b4 = b3 .|. unsafeShiftL b3 32
instance GM.MVector U.MVector Word4 where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Word4 n _) = n
basicUnsafeSlice i n (MV_Word4 _ u) = MV_Word4 n $ GM.basicUnsafeSlice i (wds n) u
basicOverlaps (MV_Word4 _ v1) (MV_Word4 _ v2) = GM.basicOverlaps v1 v2
basicUnsafeNew n = do
v <- GM.basicUnsafeNew (wds n)
return $ MV_Word4 n v
basicUnsafeReplicate n w4 = do
v <- GM.basicUnsafeReplicate (wds n) (tile w4)
return $ MV_Word4 n v
basicUnsafeRead (MV_Word4 _ u) i = do
w <- GM.basicUnsafeRead u (wd i)
return $ getWord4 w (ny i)
basicUnsafeWrite (MV_Word4 _ u) i w4 = do
let wn = wd i
w <- GM.basicUnsafeRead u wn
GM.basicUnsafeWrite u wn (setWord4 w (ny i) w4)
basicClear (MV_Word4 _ u) = GM.basicClear u
basicSet (MV_Word4 _ u) w4 = GM.basicSet u (tile w4)
basicUnsafeCopy (MV_Word4 _ u1) (MV_Word4 _ u2) = GM.basicUnsafeCopy u1 u2
basicUnsafeMove (MV_Word4 _ u1) (MV_Word4 _ u2) = GM.basicUnsafeMove u1 u2
basicUnsafeGrow (MV_Word4 _ u) n = liftM (MV_Word4 n) (GM.basicUnsafeGrow u (wds n))
data instance U.Vector Word4 = V_Word4 {-# UNPACK #-} !Int !(P.Vector Word64)
instance G.Vector U.Vector Word4 where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicLength (V_Word4 n _) = n
basicUnsafeFreeze (MV_Word4 n u) = liftM (V_Word4 n) (G.basicUnsafeFreeze u)
basicUnsafeThaw (V_Word4 n u) = liftM (MV_Word4 n) (G.basicUnsafeThaw u)
basicUnsafeSlice i n (V_Word4 _ u) = V_Word4 n (G.basicUnsafeSlice i (wds n) u)
basicUnsafeIndexM (V_Word4 _ u) i = do
w <- G.basicUnsafeIndexM u (wd i)
return $ getWord4 w (ny i)
basicUnsafeCopy (MV_Word4 _ mu) (V_Word4 _ u) = G.basicUnsafeCopy mu u
elemseq _ b z = b `seq` z
| Gabriel439/succinct | src/Succinct/Internal/Word4.hs | bsd-2-clause | 6,818 | 0 | 13 | 1,500 | 2,690 | 1,347 | 1,343 | 163 | 1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Marshal
-- Copyright : (c) The FFI task force 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Marshalling support
--
-----------------------------------------------------------------------------
module Foreign.Marshal
( module Foreign.Marshal.Alloc
, module Foreign.Marshal.Array
, module Foreign.Marshal.Error
, module Foreign.Marshal.Pool
, module Foreign.Marshal.Utils
) where
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Error
import Foreign.Marshal.Pool
import Foreign.Marshal.Utils
| FranklinChen/hugs98-plus-Sep2006 | packages/base/Foreign/Marshal.hs | bsd-3-clause | 852 | 0 | 5 | 147 | 87 | 64 | 23 | 12 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module ServerMonad (
ServerMonad, evalServerMonad, mkServerState,
getUser,
getProtocolVersion,
getLastReadyTime, setLastReadyTime,
getUserInfo,
getDirectory, getNotifierVar,
-- XXX Don't really belong here:
Directory(..), MessagerRequest(..),
getConfig,
NVar,
CHVar, ConfigHandlerRequest(..),
TimeMasterVar, getLocalTimeInTz,
baseDir,
Ppr(..), Who(..), ClientThread(..), CoreThread(..),
verbose, verbose', warn, warn',
) where
import Builder.Config
import Builder.Handlelike
import Builder.Utils
import Control.Applicative
import Control.Concurrent.MVar
import Control.Monad.State
import Data.Time.Format
import Data.Time.LocalTime
import Network.Socket
#if !MIN_VERSION_time(1,5,0)
import System.Locale
#endif
type NVar = MVar (User, BuildNum)
type CHVar = MVar ConfigHandlerRequest
type MessagerVar = MVar MessagerRequest
type TimeMasterVar = MVar (String, MVar LocalTime)
data ConfigHandlerRequest = ReloadConfig
| GiveMeConfig (MVar Config)
data MessagerRequest = Message Verbosity String
| Reopen
baseDir :: FilePath
baseDir = "data"
newtype ServerMonad a = ServerMonad (StateT ServerState IO a)
deriving (Functor, Applicative, Monad, MonadIO)
data ServerState = ServerState {
ss_handleOrSsl :: HandleOrSsl,
ss_user :: String,
ss_protocolVersion :: ProtocolVersion,
ss_directory :: Directory,
ss_last_ready_time :: TimeOfDay
}
mkServerState :: HandleOrSsl
-> User
-> ProtocolVersion
-> Directory
-> TimeOfDay
-> ServerState
mkServerState h u pv directory lrt
= ServerState {
ss_handleOrSsl = h,
ss_user = u,
ss_protocolVersion = pv,
ss_directory = directory,
ss_last_ready_time = lrt
}
evalServerMonad :: ServerMonad a -> ServerState -> IO a
evalServerMonad (ServerMonad m) cs = evalStateT m cs
getHandleOrSsl :: ServerMonad HandleOrSsl
getHandleOrSsl = do st <- ServerMonad get
return $ ss_handleOrSsl st
getUser :: ServerMonad String
getUser = do st <- ServerMonad get
return $ ss_user st
getProtocolVersion :: ServerMonad ProtocolVersion
getProtocolVersion = do st <- ServerMonad get
return $ ss_protocolVersion st
getLastReadyTime :: ServerMonad TimeOfDay
getLastReadyTime = do st <- ServerMonad get
return $ ss_last_ready_time st
setLastReadyTime :: TimeOfDay -> ServerMonad ()
setLastReadyTime tod = do st <- ServerMonad get
ServerMonad $ put $ st { ss_last_ready_time = tod }
getUserInfo :: ServerMonad (Maybe UserInfo)
getUserInfo = do st <- ServerMonad get
config <- liftIO $ getConfig (ss_directory st)
return $ lookup (ss_user st) $ config_clients config
getDirectory :: ServerMonad Directory
getDirectory = do st <- ServerMonad get
return $ ss_directory st
getNotifierVar :: ServerMonad NVar
getNotifierVar = liftM dir_notifierVar $ getDirectory
instance HandlelikeM ServerMonad where
hlPutStrLn str = do h <- getHandleOrSsl
liftIO $ hlPutStrLn' h str
hlGetLine = do h <- getHandleOrSsl
liftIO $ hlGetLine' h
hlGet n = do h <- getHandleOrSsl
liftIO $ hlGet' h n
data Directory = Directory {
dir_messagerVar :: MessagerVar,
dir_notifierVar :: NVar,
dir_configHandlerVar :: CHVar,
dir_timeMasterVar :: TimeMasterVar
}
getConfig :: Directory -> IO Config
getConfig directory
= do mv <- newEmptyMVar
putMVar (dir_configHandlerVar directory) (GiveMeConfig mv)
takeMVar mv
verbose :: String -> ServerMonad ()
verbose str = do directory <- getDirectory
u <- getUser
liftIO $ verbose' directory (ClientThread (User u)) str
warn :: String -> ServerMonad ()
warn str = do directory <- getDirectory
u <- getUser
liftIO $ warn' directory (ClientThread (User u)) str
verbose' :: Directory -> Who -> String -> IO ()
verbose' directory who str = message' directory Verbose who str
warn' :: Directory -> Who -> String -> IO ()
warn' directory who str = message' directory Normal who ("Warning: " ++ str)
message' :: Directory -> Verbosity -> Who -> String -> IO ()
message' directory verbosity who str
= do lt <- getLocalTimeInTz directory "UTC"
let fmt = "[%Y-%m-%d %H:%M:%S]"
t = formatTime defaultTimeLocale fmt lt
putMVar (dir_messagerVar directory)
(Message verbosity $ unwords [t, ppr who, str])
data Who = ClientThread ClientThread
| CoreThread CoreThread
| AddrThread SockAddr
data ClientThread = User User
| Unauthed SockAddr
data CoreThread = MessagerThread
| NotifierThread
| ConfigThread
| TimeThread
| MainThread
class Ppr a where
ppr :: a -> String
instance Ppr Who where
ppr (ClientThread ct) = "[" ++ ppr ct ++ "]"
ppr (CoreThread ct) = "[core:" ++ ppr ct ++ "]"
ppr (AddrThread sa) = "[addr:" ++ ppr sa ++ "]"
instance Ppr ClientThread where
ppr (User u) = "U:" ++ u
ppr (Unauthed a) = "unauthed:" ++ ppr a
instance Ppr CoreThread where
ppr MessagerThread = "Messager"
ppr NotifierThread = "Notifier"
ppr ConfigThread = "Config handler"
ppr TimeThread = "Time"
ppr MainThread = "Main"
instance Ppr SockAddr where
ppr = show
getLocalTimeInTz :: Directory -> String -> IO LocalTime
getLocalTimeInTz directory tz
= do mv <- newEmptyMVar
putMVar (dir_timeMasterVar directory) (tz, mv)
takeMVar mv
| haskell/ghc-builder | server/ServerMonad.hs | bsd-3-clause | 6,274 | 0 | 12 | 1,999 | 1,585 | 825 | 760 | 152 | 1 |
module Syntax.Env where
import Syntax.Tree (Identifier)
import Data.Map as Map
-- Keeps track of declarations at this scope, and the scope above.
-- And the type of identifiers in the environment.
data Env a = Env {
-- Declarations in the scope above. These can be overwritten.
aboveScope :: Map Identifier a,
-- Declarations in the current scope. These cannot be overwritten.
used :: Map Identifier a
}
instance (Show a) => Show (Env a) where
show (Env a u) = "above: " ++ (show a) ++ ", used: " ++ (show u)
-- Returns the combination of both scopes to make for easier searching.
combinedScopes :: Env a -> Map Identifier a
-- used before above so conficts use the inner-most definiton.
combinedScopes (Env above used) = Map.union used above
empty :: Env a
empty = Env Map.empty Map.empty
-- State containing the list of used identifiers at the current scope.
fromList :: [(Identifier, a)] -> Env a
fromList usedIds = Env Map.empty (Map.fromList usedIds)
-- Adds a variable name to the current scope.
put :: Identifier -> a -> Env a -> Env a
put newId idType (Env above used) = Env above used' where
used' = Map.insert newId idType used
-- Returns whether a identifier can be used, i.e. if the identifier has been
-- declared in this scope or the scope above.
get :: Identifier -> Env a -> Maybe a
get i env = i `Map.lookup` (combinedScopes env)
-- Retrive the identifier from the environment and modify it. If the identifier
-- does not exist then the supplied env is returned.
modify :: Identifier -> (a -> a) -> Env a -> Env a
modify i f env = case get i env of
Nothing -> env
Just x -> put i (f x) env
-- Moves any used names into the scope above.
descendScope :: Env a -> Env a
descendScope env = Env (combinedScopes env) Map.empty
-- Returns whether a identifier has already been used to declare a variable/function.
-- i.e. if the name is in use at this scope.
isTaken :: Identifier -> Env a -> Bool
isTaken i (Env _ used) = i `Map.member` used
| BakerSmithA/Turing | src/Syntax/Env.hs | bsd-3-clause | 1,997 | 0 | 10 | 408 | 503 | 263 | 240 | 27 | 2 |
-- |
-- Module : Console.Options
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : Good
--
-- Options parsing using a simple DSL approach.
--
-- Using this API, your program should have the following shape:
--
-- >defaultMain $ do
-- > f1 <- flag ..
-- > f2 <- argument ..
-- > action $ \toParam ->
-- > something (toParam f1) (toParam f2) ..
--
-- You can also define subcommand using:
--
-- >defaultMain $ do
-- > subcommand "foo" $ do
-- > <..flags & parameters definitions...>
-- > action $ \toParam -> <..IO-action..>
-- > subcommand "bar" $ do
-- > <..flags & parameters definitions...>
-- > action $ \toParam -> <..IO-action..>
--
-- Example:
--
-- >main = defaultMain $ do
-- > programName "test-cli"
-- > programDescription "test CLI program"
-- > flagA <- flag $ FlagShort 'a' <> FlagLong "aaa"
-- > allArgs <- remainingArguments "FILE"
-- > action $ \toParam -> do
-- > putStrLn $ "using flag A : " ++ show (toParam flagA)
-- > putStrLn $ "args: " ++ show (toParam allArgs)
--
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
module Console.Options
(
-- * Running
defaultMain
, defaultMainWith
, parseOptions
, OptionRes(..)
, OptionDesc
-- * Description
, programName
, programVersion
, programDescription
, command
, FlagFrag(..)
, flag
, flagParam
, flagMany
-- , conflict
, argument
, remainingArguments
, action
, description
, Action
-- * Arguments
, ValueParser
, FlagParser(..)
, Flag
, FlagLevel
, FlagParam
, FlagMany
, Arg
, ArgRemaining
, Params
, paramsFlags
, getParams
) where
import Foundation (toList, toCount, fromList)
import Console.Options.Flags hiding (Flag)
import qualified Console.Options.Flags as F
import Console.Options.Nid
import Console.Options.Utils
import Console.Options.Monad
import Console.Options.Types
import Console.Display (justify, Justify(..))
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Data.List
import Data.Maybe (fromMaybe)
import Data.Version
import Data.Functor.Identity
import System.Environment (getArgs, getProgName)
import System.Exit
----------------------------------------------------------------------
setDescription :: String -> Command r -> Command r
setDescription desc (Command hier _ opts act) = Command hier desc opts act
setAction :: Action r -> Command r -> Command r
setAction act (Command hier desc opts _) = Command hier desc opts (ActionWrapped act)
addOption :: FlagDesc -> Command r -> Command r
addOption opt (Command hier desc opts act) = Command hier desc (opt : opts) act
tweakOption :: Nid -> (FlagDesc -> FlagDesc) -> Command r -> Command r
tweakOption nid mapFlagDesc (Command hier desc opts act) =
Command hier desc (modifyNid opts) act
where
modifyNid [] = []
modifyNid (f:fs)
| flagNid f == nid = mapFlagDesc f : fs
| otherwise = f : modifyNid fs
addArg :: Argument -> Command r -> Command r
addArg arg = modifyHier $ \hier ->
case hier of
CommandLeaf l -> CommandLeaf (arg:l)
CommandTree {} -> hier -- ignore argument in a hierarchy.
----------------------------------------------------------------------
-- | A parser for a flag's value, either optional or required.
data FlagParser a =
FlagRequired (ValueParser a) -- ^ flag value parser with a required parameter.
| FlagOptional a (ValueParser a) -- ^ Optional flag value parser: Default value if not present to a
-- | A parser for a value. In case parsing failed Left should be returned.
type ValueParser a = String -> Either String a
-- | return value of the option parser. only needed when using 'parseOptions' directly
data OptionRes r =
OptionSuccess Params (Action r)
| OptionHelp
| OptionError String -- user cmdline error in the arguments
| OptionInvalid String -- API has been misused
-- | run parse options description on the action
--
-- to be able to specify the arguments manually (e.g. pre-handling),
-- you can use 'defaultMainWith'.
-- >defaultMain dsl = getArgs >>= defaultMainWith dsl
defaultMain :: OptionDesc (IO ()) () -> IO ()
defaultMain dsl = getArgs >>= defaultMainWith dsl
-- | same as 'defaultMain', but with the argument
defaultMainWith :: OptionDesc (IO ()) () -> [String] -> IO ()
defaultMainWith dsl args = do
progrName <- getProgName
let (programDesc, res) = parseOptions (programName progrName >> dsl) args
in case res of
OptionError s -> putStrLn s >> exitFailure
OptionHelp -> help (stMeta programDesc) (stCT programDesc) >> exitSuccess
OptionSuccess params r -> r (getParams params)
OptionInvalid s -> putStrLn s >> exitFailure
-- | This is only useful when you want to handle all the description parsing
-- manually and need to not automatically execute any action or help/error handling.
--
-- Used for testing the parser.
parseOptions :: OptionDesc r () -> [String] -> (ProgramDesc r, OptionRes r)
parseOptions dsl args =
let descState = gatherDesc dsl
in (descState, runOptions (stCT descState) args)
--helpSubcommand :: [String] -> IO ()
help :: ProgramMeta -> Command (IO ()) -> IO ()
help pmeta (Command hier _ commandOpts _) = do
tell (fromMaybe "<program>" (programMetaName pmeta) ++ " version " ++ fromMaybe "<undefined>" (programMetaVersion pmeta) ++ "\n")
tell "\n"
maybe (return ()) (\d -> tell d >> tell "\n\n") (programMetaDescription pmeta)
tell "Options:\n"
tell "\n"
mapM_ (tell . printOpt 0) commandOpts
case hier of
CommandTree subs -> do
tell "\n"
tell "Commands:\n"
let cmdLength = maximum (map (length . fst) subs) + 2
forM_ subs $ \(n, c) -> tell $ indent 2 (toList (justify JustifyRight (toCount cmdLength) (fromList n)) ++ getCommandDescription c ++ "\n")
tell "\n"
mapM_ (printSub 2) subs
CommandLeaf _ ->
return ()
where
tell = putStr
printSub iLevel (name, cmdOpt) = do
tell $ "\nCommand `" ++ name ++ "':\n\n"
tell $ indent iLevel "Options:\n\n"
mapM_ (tell . printOpt iLevel) (getCommandOptions cmdOpt)
case getCommandHier cmdOpt of
CommandTree subs -> do
tell $ indent iLevel "Commands:\n"
let cmdLength = maximum (map (length . fst) subs) + 2 + iLevel
forM_ subs $ \(n, c) -> tell $ indent (iLevel + 2) (toList (justify JustifyRight (toCount cmdLength) (fromList n)) ++ getCommandDescription c ++ "\n")
tell "\n"
mapM_ (printSub (iLevel + 2)) subs
CommandLeaf _ -> pure ()
--tell . indent 2 ""
printOpt iLevel fd =
let optShort = maybe (replicate 2 ' ') (\c -> "-" ++ [c]) $ flagShort ff
optLong = maybe (replicate 8 ' ') (\s -> "--" ++ s) $ flagLong ff
optDesc = maybe "" (" " ++) $ flagDescription ff
in indent (iLevel + 2) $ intercalate " " [optShort, optLong, optDesc] ++ "\n"
where
ff = flagFragments fd
runOptions :: Command r -- commands
-> [String] -- arguments
-> OptionRes r
runOptions ct allArgs
| "--help" `elem` allArgs = OptionHelp
| "-h" `elem` allArgs = OptionHelp
| otherwise = go [] ct allArgs
where
-- parse recursively using a Command structure
go :: [[F.Flag]] -> Command r -> [String] -> OptionRes r
go parsedOpts (Command hier _ commandOpts act) unparsedArgs =
case parseFlags commandOpts unparsedArgs of
(opts, unparsed, []) -> do
case hier of
-- if we have sub commands, then we pass the unparsed options
-- to their parsers
CommandTree subs -> do
case unparsed of
[] -> errorExpectingMode subs
(x:xs) -> case lookup x subs of
Nothing -> errorInvalidMode x subs
Just subTree -> go (opts:parsedOpts) subTree xs
-- no more subcommand (or none to start with)
CommandLeaf unnamedArgs ->
case validateUnnamedArgs (reverse unnamedArgs) unparsed of
Left err -> errorUnnamedArgument err
Right (pinnedArgs, remainingArgs) -> do
let flags = concat (opts:parsedOpts)
case act of
NoActionWrapped -> OptionInvalid "no action defined"
ActionWrapped a ->
let params = Params flags
pinnedArgs
remainingArgs
in OptionSuccess params a
(_, _, ers) -> do
OptionError $ mconcat $ map showOptionError ers
validateUnnamedArgs :: [Argument] -> [String] -> Either String ([String], [String])
validateUnnamedArgs argOpts l =
v [] argOpts >>= \(opts, _hasCatchall) -> do
let unnamedRequired = length opts
if length l < unnamedRequired
then Left "missing arguments"
else Right $ splitAt unnamedRequired l
where
v :: [Argument] -> [Argument] -> Either String ([Argument], Bool)
v acc [] = Right (reverse acc, False)
v acc (a@(Argument {}):as) = v (a:acc) as
v acc ((ArgumentCatchAll {}):[]) = Right (reverse acc, True)
v _ ((ArgumentCatchAll {}):_ ) = Left "arguments expected after remainingArguments"
showOptionError (FlagError opt i s) = do
let optName = (maybe "" (:[]) $ flagShort $ flagFragments opt) ++ " " ++ (maybe "" id $ flagLong $ flagFragments opt)
in ("error: " ++ show i ++ " option " ++ optName ++ " : " ++ s ++ "\n")
errorUnnamedArgument err =
OptionError $ mconcat
[ "error: " ++ err
, ""
]
errorExpectingMode subs =
OptionError $ mconcat (
[ "error: expecting one of the following mode:\n"
, "\n"
] ++ map (indent 4 . (++ "\n") . fst) subs)
errorInvalidMode got subs =
OptionError $ mconcat (
[ "error: invalid mode '" ++ got ++ "', expecting one of the following mode:\n"
, ""
] ++ map (indent 4 . (++ "\n") . fst) subs)
indent :: Int -> String -> String
indent n s = replicate n ' ' ++ s
-- | Set the program name
--
-- default is the result of base's `getProgName`
programName :: String -> OptionDesc r ()
programName s = modify $ \st -> st { stMeta = (stMeta st) { programMetaName = Just s } }
-- | Set the program version
programVersion :: Version -> OptionDesc r ()
programVersion s = modify $ \st -> st { stMeta = (stMeta st) { programMetaVersion = Just $ showVersion s } }
-- | Set the program description
programDescription :: String -> OptionDesc r ()
programDescription s = modify $ \st -> st { stMeta = (stMeta st) { programMetaDescription = Just s } }
-- | Set the description for a command
description :: String -> OptionDesc r ()
description doc = modify $ \st -> st { stCT = setDescription doc (stCT st) }
modifyHier :: (CommandHier r -> CommandHier r) -> Command r -> Command r
modifyHier f (Command hier desc opts act) = Command (f hier) desc opts act
modifyCT :: (Command r -> Command r) -> OptionDesc r ()
modifyCT f = modify $ \st -> st { stCT = f (stCT st) }
-- | Create a new sub command
command :: String -> OptionDesc r () -> OptionDesc r ()
command name sub = do
let subSt = gatherDesc sub
modifyCT (addCommand (stCT subSt))
--modify $ \st -> st { stCT = addCommand (stCT subSt) $ stCT st }
where addCommand subTree = modifyHier $ \hier ->
case hier of
CommandLeaf _ -> CommandTree [(name,subTree)]
CommandTree t -> CommandTree ((name, subTree) : t)
-- | Set the action to run in this command
action :: Action r -> OptionDesc r ()
action ioAct = modify $ \st -> st { stCT = setAction ioAct (stCT st) }
-- | Flag option either of the form -short or --long
--
-- for flag that doesn't have parameter, use 'flag'
flagParam :: FlagFrag -> FlagParser a -> OptionDesc r (FlagParam a)
flagParam frag fp = do
nid <- getNextID
let fragmentFlatten = flattenFragments frag
let opt = FlagDesc
{ flagFragments = fragmentFlatten
, flagNid = nid
, F.flagArg = argp
, flagArgValidate = validator
, flagArity = 1
}
modify $ \st -> st { stCT = addOption opt (stCT st) }
case mopt of
Just a -> return (FlagParamOpt nid a parser)
Nothing -> return (FlagParam nid parser)
where
(argp, parser, mopt, validator) = case fp of
FlagRequired p -> (FlagArgHave, toArg p, Nothing, isValid p)
FlagOptional a p -> (FlagArgMaybe, toArg p, Just a, isValid p)
toArg :: (String -> Either String a) -> String -> a
toArg p = either (error "internal error toArg") id . p
isValid f = either FlagArgInvalid (const FlagArgValid) . f
-- | Apply on a 'flagParam' to turn into a flag that can
-- be invoked multiples, creating a list of values
-- in the action.
flagMany :: OptionDesc r (FlagParam a) -> OptionDesc r (FlagMany a)
flagMany fp = do
f <- fp
let nid = case f of
FlagParamOpt n _ _ -> n
FlagParam n _ -> n
modify $ \st -> st { stCT = tweakOption nid (\fd -> fd { flagArity = maxBound }) (stCT st) }
return $ FlagMany f
-- | Flag option either of the form -short or --long
--
-- for flag that expect a value (optional or mandatory), uses 'flagArg'
flag :: FlagFrag -> OptionDesc r (Flag Bool)
flag frag = do
nid <- getNextID
let fragmentFlatten = flattenFragments frag
let opt = FlagDesc
{ flagFragments = fragmentFlatten
, flagNid = nid
, F.flagArg = FlagArgNone
, flagArgValidate = error ""
, flagArity = 0
}
modify $ \st -> st { stCT = addOption opt (stCT st) }
return (Flag nid)
-- | An unnamed positional argument
--
-- For now, argument in a point of tree that contains sub trees will be ignored.
-- TODO: record a warning or add a strict mode (for developping the CLI) and error.
argument :: String -> ValueParser a -> OptionDesc r (Arg a)
argument name fp = do
idx <- getNextIndex
let a = Argument { argumentName = name
, argumentDescription = ""
, argumentValidate = either Just (const Nothing) . fp
}
modifyCT $ addArg a
return (Arg idx (either (error "internal error") id . fp))
-- | All the remaining position arguments
--
-- This is useful for example for a program that takes an unbounded list of files
-- as parameters.
remainingArguments :: String -> OptionDesc r (ArgRemaining [String])
remainingArguments name = do
let a = ArgumentCatchAll { argumentName = name
, argumentDescription = ""
}
modifyCT $ addArg a
return ArgsRemaining
-- | give the ability to set options that are conflicting with each other
-- if option a is given with option b then an conflicting error happens
-- conflict :: Flag a -> Flag b -> OptionDesc r ()
-- conflict = undefined
| NicolasDP/hs-cli | Console/Options.hs | bsd-3-clause | 16,457 | 23 | 27 | 5,268 | 4,019 | 2,118 | 1,901 | 271 | 11 |
module Countries where
import Data.Function (on)
import qualified Data.Set as S
import Text.Read
import qualified Text.Read.Lex as L
import Safe
data Country = Country {
countryCode :: String
, countryName :: String
}
instance Show Country where
show (Country c _) = c
showCountry :: Country -> String
showCountry (Country c n) = c ++ " - " ++ n
instance Read Country where
readPrec = parens
( do L.Ident s <- lexP
let i = S.intersection countries $ S.singleton $ Country s ""
case headMay $ S.toList i of
Nothing -> pfail
Just x -> return x
)
instance Eq Country where
(==) = (==) `on` countryCode
instance Ord Country where
compare = compare `on` countryCode
countries :: S.Set Country
countries = S.fromAscList
[ Country "AD" "Andorra"
, Country "AE" "United Arab Emirates"
, Country "AF" "Afghanistan"
, Country "AG" "Antigua and Barbuda"
, Country "AI" "Anguilla"
, Country "AL" "Albania"
, Country "AM" "Armenia"
, Country "AO" "Angola"
, Country "AQ" "Antarctica"
, Country "AR" "Argentina"
, Country "AS" "American Samoa"
, Country "AT" "Austria"
, Country "AU" "Australia"
, Country "AW" "Aruba"
, Country "AX" "Åland Islands"
, Country "AZ" "Azerbaijan"
, Country "BA" "Bosnia and Herzegovina"
, Country "BB" "Barbados"
, Country "BD" "Bangladesh"
, Country "BE" "Belgium"
, Country "BF" "Burkina Faso"
, Country "BG" "Bulgaria"
, Country "BH" "Bahrain"
, Country "BI" "Burundi"
, Country "BJ" "Benin"
, Country "BL" "Saint Barthélemy"
, Country "BM" "Bermuda"
, Country "BN" "Brunei Darussalam"
, Country "BO" "Bolivia (Plurinational State of)"
, Country "BR" "Brazil"
, Country "BS" "Bahamas"
, Country "BT" "Bhutan"
, Country "BV" "Bouvet Island"
, Country "BW" "Botswana"
, Country "BY" "Belarus"
, Country "BZ" "Belize"
, Country "CA" "Canada"
, Country "CC" "Cocos (Keeling) Islands"
, Country "CD" "Congo (Democratic Republic of the)"
, Country "CF" "Central African Republic"
, Country "CG" "Republic of the Congo"
, Country "CH" "Switzerland"
, Country "CI" "Côte d'Ivoire"
, Country "CK" "Cook Islands"
, Country "CL" "Chile"
, Country "CM" "Cameroon"
, Country "CN" "China"
, Country "CO" "Colombia"
, Country "CR" "Costa Rica"
, Country "CU" "Cuba"
, Country "CV" "Cabo Verde"
, Country "CX" "Christmas Island"
, Country "CY" "Cyprus"
, Country "CZ" "Czech Republic"
, Country "DJ" "Djibouti"
, Country "DE" "Germany"
, Country "DK" "Denmark"
, Country "DM" "Dominica"
, Country "DO" "Dominican Republic"
, Country "DZ" "Algeria"
, Country "EC" "Ecuador"
, Country "EE" "Estonia"
, Country "EG" "Egypt"
, Country "EH" "Western Sahara"
, Country "ER" "Eritrea"
, Country "ES" "Spain"
, Country "ET" "Ethiopia"
, Country "FI" "Finland"
, Country "FJ" "Fiji"
, Country "FK" "Falkland Islands (Malvinas)"
, Country "FM" "Micronesia (Federated States of)"
, Country "FO" "Faroe Islands"
, Country "FR" "France"
, Country "GA" "Gabon"
, Country "GB" "United Kingdom of Great Britain and Northern Ireland"
, Country "GD" "Grenada"
, Country "GE" "Georgia (country)"
, Country "GF" "French Guiana"
, Country "GG" "Guernsey"
, Country "GH" "Ghana"
, Country "GI" "Gibraltar"
, Country "GL" "Greenland"
, Country "GM" "Gambia"
, Country "GN" "Guinea"
, Country "GP" "Guadeloupe"
, Country "GQ" "Equatorial Guinea"
, Country "GR" "Greece"
, Country "GS" "South Georgia and the South Sandwich Islands"
, Country "GT" "Guatemala"
, Country "GU" "Guam"
, Country "GW" "Guinea-Bissau"
, Country "GY" "Guyana"
, Country "HK" "Hong Kong"
, Country "HM" "Heard Island and McDonald Islands"
, Country "HN" "Honduras"
, Country "HR" "Croatia"
, Country "HT" "Haiti"
, Country "HU" "Hungary"
, Country "ID" "Indonesia"
, Country "IE" "Republic of Ireland"
, Country "IL" "Israel"
, Country "IM" "Isle of Man"
, Country "IN" "India"
, Country "IO" "British Indian Ocean Territory"
, Country "IQ" "Iraq"
, Country "IR" "Iran (Islamic Republic of)"
, Country "IS" "Iceland"
, Country "IT" "Italy"
, Country "JE" "Jersey"
, Country "JM" "Jamaica"
, Country "JO" "Jordan"
, Country "JP" "Japan"
, Country "KE" "Kenya"
, Country "KG" "Kyrgyzstan"
, Country "KH" "Cambodia"
, Country "KI" "Kiribati"
, Country "KM" "Comoros"
, Country "KN" "Saint Kitts and Nevis"
, Country "KP" "North Korea"
, Country "KR" "Korea (Republic of)"
, Country "KW" "Kuwait"
, Country "KY" "Cayman Islands"
, Country "KZ" "Kazakhstan"
, Country "LA" "Lao People's Democratic Republic"
, Country "LB" "Lebanon"
, Country "LC" "Saint Lucia"
, Country "LI" "Liechtenstein"
, Country "LK" "Sri Lanka"
, Country "LR" "Liberia"
, Country "LS" "Lesotho"
, Country "LT" "Lithuania"
, Country "LU" "Luxembourg"
, Country "LV" "Latvia"
, Country "LY" "Libya"
, Country "MA" "Morocco"
, Country "MC" "Monaco"
, Country "MD" "Moldova (Republic of)"
, Country "ME" "Montenegro"
, Country "MG" "Madagascar"
, Country "MH" "Marshall Islands"
, Country "MK" "Republic of Macedonia"
, Country "ML" "Mali"
, Country "MM" "Myanmar"
, Country "MN" "Mongolia"
, Country "MO" "Macao"
, Country "MP" "Northern Mariana Islands"
, Country "MQ" "Martinique"
, Country "MR" "Mauritania"
, Country "MS" "Montserrat"
, Country "MT" "Malta"
, Country "MU" "Mauritius"
, Country "MV" "Maldives"
, Country "MW" "Malawi"
, Country "MX" "Mexico"
, Country "MY" "Malaysia"
, Country "MZ" "Mozambique"
, Country "NA" "Namibia"
, Country "NC" "New Caledonia"
, Country "NE" "Niger"
, Country "NF" "Norfolk Island"
, Country "NG" "Nigeria"
, Country "NI" "Nicaragua"
, Country "NL" "Netherlands"
, Country "NO" "Norway"
, Country "NP" "Nepal"
, Country "NR" "Nauru"
, Country "NU" "Niue"
, Country "NZ" "New Zealand"
, Country "OM" "Oman"
, Country "PA" "Panama"
, Country "PE" "Peru"
, Country "PF" "French Polynesia"
, Country "PG" "Papua New Guinea"
, Country "PH" "Philippines"
, Country "PK" "Pakistan"
, Country "PL" "Poland"
, Country "PM" "Saint Pierre and Miquelon"
, Country "PN" "Pitcairn"
, Country "PR" "Puerto Rico"
, Country "PS" "State of Palestine"
, Country "PT" "Portugal"
, Country "PW" "Palau"
, Country "PY" "Paraguay"
, Country "QA" "Qatar"
, Country "RE" "Réunion"
, Country "RO" "Romania"
, Country "RS" "Serbia"
, Country "RU" "Russian Federation"
, Country "RW" "Rwanda"
, Country "SA" "Saudi Arabia"
, Country "SB" "Solomon Islands"
, Country "SC" "Seychelles"
, Country "SD" "Sudan"
, Country "SE" "Sweden"
, Country "SG" "Singapore"
, Country "SH" "Saint Helena, Ascension and Tristan da Cunha"
, Country "SI" "Slovenia"
, Country "SJ" "Svalbard and Jan Mayen"
, Country "SK" "Slovakia"
, Country "SL" "Sierra Leone"
, Country "SM" "San Marino"
, Country "SN" "Senegal"
, Country "SO" "Somalia"
, Country "SR" "Suriname"
, Country "ST" "Sao Tome and Principe"
, Country "SV" "El Salvador"
, Country "SY" "Syrian Arab Republic"
, Country "SZ" "Swaziland"
, Country "TC" "Turks and Caicos Islands"
, Country "TD" "Chad"
, Country "TF" "French Southern Territories"
, Country "TG" "Togo"
, Country "TH" "Thailand"
, Country "TJ" "Tajikistan"
, Country "TK" "Tokelau"
, Country "TL" "Timor-Leste"
, Country "TM" "Turkmenistan"
, Country "TN" "Tunisia"
, Country "TO" "Tonga"
, Country "TR" "Turkey"
, Country "TT" "Trinidad and Tobago"
, Country "TV" "Tuvalu"
, Country "TW" "Taiwan"
, Country "TZ" "Tanzania, United Republic of"
, Country "UA" "Ukraine"
, Country "UG" "Uganda"
, Country "UM" "United States Minor Outlying Islands"
, Country "US" "United States of America"
, Country "UY" "Uruguay"
, Country "UZ" "Uzbekistan"
, Country "VA" "Vatican City State"
, Country "VC" "Saint Vincent and the Grenadines"
, Country "VE" "Venezuela (Bolivarian Republic of)"
, Country "VG" "British Virgin Islands"
, Country "VI" "United States Virgin Islands"
, Country "VN" "Viet Nam"
, Country "VU" "Vanuatu"
, Country "WF" "Wallis and Futuna"
, Country "WS" "Samoa"
, Country "YE" "Yemen"
, Country "YT" "Mayotte"
, Country "ZA" "South Africa"
, Country "ZM" "Zambia"
, Country "ZW" "Zimbabwe"
]
toFakeCountry :: [String] -> S.Set Country
toFakeCountry l = S.fromList $ map (flip Country "") l
| MicheleCastrovilli/EuPhBot | Bots/MusicBot/Countries.hs | bsd-3-clause | 9,043 | 0 | 16 | 2,363 | 2,269 | 1,146 | 1,123 | 272 | 1 |
{- |
Module : Data.Convertible.Instances.Map
Copyright : Copyright (C) 2009-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <[email protected]>
Stability : provisional
Portability: portable
Instances to convert between Map and association list.
Copyright (C) 2009-2011 John Goerzen <[email protected]>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
module Data.Convertible.Instances.Map()
where
import Data.Convertible.Base
import qualified Data.Map as Map
instance Ord k => Convertible [(k, a)] (Map.Map k a) where
safeConvert = return . Map.fromList
instance Convertible (Map.Map k a) [(k, a)] where
safeConvert = return . Map.toList
| hdbc/convertible | Data/Convertible/Instances/Map.hs | bsd-3-clause | 737 | 0 | 8 | 136 | 113 | 66 | 47 | -1 | -1 |
import Data.Indexable.Tests
import Utils.Tests
import Physics.Chipmunk.Types.Tests
import Physics.Chipmunk.StickyEdges.Tests
import Sorts.Terminal.Tests
import Sorts.Tiles.Baking.Tests
import Top.Main.Tests
main :: IO ()
main = do
Top.Main.Tests.tests
Data.Indexable.Tests.tests
Sorts.Terminal.Tests.tests
Utils.Tests.tests
Physics.Chipmunk.Types.Tests.tests
Physics.Chipmunk.StickyEdges.Tests.tests
Sorts.Tiles.Baking.Tests.tests
i :: Monad m => a -> m ()
i = const $ return ()
| changlinli/nikki | src/testsuite/testsuite.hs | lgpl-3.0 | 516 | 0 | 9 | 80 | 151 | 86 | 65 | 18 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : Extension of CFOL2IsabelleHOL to CoCASL
Copyright : (c) Till Mossakowski and Uni Bremen 2003-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports Logic.Logic)
The embedding comorphism from CoCASL to Isabelle-HOL.
-}
module Comorphisms.CoCFOL2IsabelleHOL (CoCFOL2IsabelleHOL (..)) where
import Logic.Logic as Logic
import Logic.Comorphism
-- CoCASL
import CoCASL.Logic_CoCASL
import CoCASL.CoCASLSign
import CoCASL.AS_CoCASL
import CoCASL.StatAna
import CoCASL.Sublogic
import CASL.Sublogic as SL
import CASL.AS_Basic_CASL
import CASL.Sign
import CASL.Morphism
import Comorphisms.CFOL2IsabelleHOL
-- Isabelle
import Isabelle.IsaSign as IsaSign
import Isabelle.IsaConsts
import Isabelle.Logic_Isabelle
import Common.Utils (number)
import Data.Char (ord, chr)
import Data.Maybe (fromMaybe)
-- | The identity of the comorphism
data CoCFOL2IsabelleHOL = CoCFOL2IsabelleHOL deriving Show
instance Language CoCFOL2IsabelleHOL where
language_name CoCFOL2IsabelleHOL = "CoCASL2Isabelle"
instance Comorphism CoCFOL2IsabelleHOL
CoCASL CoCASL_Sublogics
C_BASIC_SPEC CoCASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CSign
CoCASLMor
Symbol RawSymbol ()
Isabelle () () IsaSign.Sentence () ()
IsaSign.Sign
IsabelleMorphism () () () where
sourceLogic CoCFOL2IsabelleHOL = CoCASL
sourceSublogic CoCFOL2IsabelleHOL = SL.cFol
targetLogic CoCFOL2IsabelleHOL = Isabelle
mapSublogic cid sl = if sl `isSubElem` sourceSublogic cid
then Just () else Nothing
map_theory CoCFOL2IsabelleHOL =
return . transTheory sigTrCoCASL formTrCoCASL
map_sentence CoCFOL2IsabelleHOL sign =
return . mapSen formTrCoCASL sign (typeToks sign)
has_model_expansion CoCFOL2IsabelleHOL = True
is_weakly_amalgamable CoCFOL2IsabelleHOL = True
xvar :: Int -> String
xvar i = if i <= 26 then [chr (i + ord 'a')] else 'x' : show i
rvar :: Int -> String
rvar i = if i <= 9 then [chr (i + ord 'R' )] else 'R' : show i
-- | extended signature translation for CoCASL
sigTrCoCASL :: SignTranslator C_FORMULA CoCASLSign
sigTrCoCASL _ _ = id
conjs :: [Term] -> Term
conjs l = if null l then true else foldr1 binConj l
-- | extended formula translation for CoCASL
formTrCoCASL :: FormulaTranslator C_FORMULA CoCASLSign
formTrCoCASL sign tyToks (CoSort_gen_ax sorts ops _) =
foldr (quantifyIsa "All") phi $ predDecls ++ [("u", ts), ("v", ts)]
where
ts = transSort $ head sorts
-- phi expresses: all bisimulations are the equality
phi = prems `binImpl` concls
-- indices and predicates for all involved sorts
indexedSorts = number sorts
predDecls = map (\ (s, i) -> (rvar i, binPred s)) indexedSorts
binPred s = let s' = transSort s in mkCurryFunType [s', s'] boolType
-- premises: all relations are bisimulations
prems = conjs (map prem indexedSorts)
{- generate premise for s, where s is the i-th sort
for all x,y of that sort,
if all sel_j(x) R_j sel_j(y), where sel_j ranges over the selectors for s
then x R y
here, R_i is the relation for the result type of sel_j, or the equality
-}
prem (s, i) =
let -- get all selectors with first argument sort s
sels = filter isSelForS ops
isSelForS (Qual_op_name _ t _) = case args_OP_TYPE t of
s1 : _ -> s1 == s
_ -> False
isSelForS _ = False
premSel opsymb@(Qual_op_name _n t _) =
let -- get extra parameters of the selectors
args = tail $ args_OP_TYPE t
indicesArgs = number args
res = res_OP_TYPE t
-- variables for the extra parameters
varDecls = map (\ (a, j) -> (xvar j, transSort a))
indicesArgs
-- the selector ...
topC = con (transOpSymb sign tyToks opsymb)
-- applied to x and extra parameter vars
appFold = foldl termAppl
rhs = appFold (termAppl topC $ mkFree "x")
$ map (mkFree . xvar . snd) indicesArgs
-- applied to y and extra parameter vars
lhs = appFold (termAppl topC $ mkFree "y")
$ map (mkFree . xvar . snd) indicesArgs
chi = -- is the result of selector non-observable?
if res `elem` sorts
-- then apply corresponding relation
then termAppl (termAppl (mkFree $
rvar $ fromMaybe
(error "CoCASL2Isabelle.premSel.chi")
$ lookup res indexedSorts )
rhs) lhs
-- else use equality
else binEq rhs lhs
in foldr (quantifyIsa "All") chi varDecls
premSel _ = error "CoCASL2Isabelle.premSel"
prem1 = conjs (map premSel sels)
concl1 = termAppl (termAppl (mkFree $ rvar i) $ mkFree "x")
(mkFree "y")
psi = concl1 `binImpl` prem1
typS = transSort s
in foldr (quantifyIsa "All") psi [("x", typS), ("y", typS)]
-- conclusion: all relations are the equality
concls = conjs (map concl indexedSorts)
concl (_, i) = binImpl (termAppl (termAppl (mkFree $ rvar i) $ mkFree "u")
$ mkFree "v")
$ binEq (mkFree "u") $ mkFree "v"
formTrCoCASL _sign _ (BoxOrDiamond _ _mod _phi _) =
error "CoCFOL2IsabelleHOL.formTrCoCASL.BoxOrDiamond"
| keithodulaigh/Hets | Comorphisms/CoCFOL2IsabelleHOL.hs | gpl-2.0 | 5,768 | 0 | 24 | 1,676 | 1,306 | 691 | 615 | 102 | 5 |
-- Test purpose:
-- Ensure that not using -Wcompat does not enable its warnings
-- {-# OPTIONS_GHC -Wcompat #-}
-- {-# OPTIONS_GHC -Wno-compat #-}
module WCompatWarningsNotOn where
import qualified Data.Semigroup as Semi
monadFail :: Monad m => m a
monadFail = do
Just _ <- undefined
undefined
(<>) = undefined -- Semigroup warnings
-- -fwarn-noncanonical-monoid-instances
newtype S = S Int
instance Semi.Semigroup S where
(<>) = mappend
instance Monoid S where
S a `mappend` S b = S (a+b)
mempty = S 0
| shlevy/ghc | testsuite/tests/wcompat-warnings/WCompatWarningsNotOn.hs | bsd-3-clause | 525 | 0 | 8 | 105 | 128 | 72 | 56 | 13 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Bag: an unordered collection with duplicates
-}
{-# LANGUAGE ScopedTypeVariables, CPP #-}
module Bag (
Bag, -- abstract type
emptyBag, unitBag, unionBags, unionManyBags,
mapBag,
elemBag, lengthBag,
filterBag, partitionBag, partitionBagWith,
concatBag, catBagMaybes, foldBag, foldrBag, foldlBag,
isEmptyBag, isSingletonBag, consBag, snocBag, anyBag,
listToBag, bagToList, mapAccumBagL,
foldrBagM, foldlBagM, mapBagM, mapBagM_,
flatMapBagM, flatMapBagPairM,
mapAndUnzipBagM, mapAccumBagLM,
anyBagM, filterBagM
) where
import Outputable
import Util
import MonadUtils
import Control.Monad
import Data.Data
import Data.List ( partition, mapAccumL )
import qualified Data.Foldable as Foldable
infixr 3 `consBag`
infixl 3 `snocBag`
data Bag a
= EmptyBag
| UnitBag a
| TwoBags (Bag a) (Bag a) -- INVARIANT: neither branch is empty
| ListBag [a] -- INVARIANT: the list is non-empty
emptyBag :: Bag a
emptyBag = EmptyBag
unitBag :: a -> Bag a
unitBag = UnitBag
lengthBag :: Bag a -> Int
lengthBag EmptyBag = 0
lengthBag (UnitBag {}) = 1
lengthBag (TwoBags b1 b2) = lengthBag b1 + lengthBag b2
lengthBag (ListBag xs) = length xs
elemBag :: Eq a => a -> Bag a -> Bool
elemBag _ EmptyBag = False
elemBag x (UnitBag y) = x == y
elemBag x (TwoBags b1 b2) = x `elemBag` b1 || x `elemBag` b2
elemBag x (ListBag ys) = any (x ==) ys
unionManyBags :: [Bag a] -> Bag a
unionManyBags xs = foldr unionBags EmptyBag xs
-- This one is a bit stricter! The bag will get completely evaluated.
unionBags :: Bag a -> Bag a -> Bag a
unionBags EmptyBag b = b
unionBags b EmptyBag = b
unionBags b1 b2 = TwoBags b1 b2
consBag :: a -> Bag a -> Bag a
snocBag :: Bag a -> a -> Bag a
consBag elt bag = (unitBag elt) `unionBags` bag
snocBag bag elt = bag `unionBags` (unitBag elt)
isEmptyBag :: Bag a -> Bool
isEmptyBag EmptyBag = True
isEmptyBag _ = False -- NB invariants
isSingletonBag :: Bag a -> Bool
isSingletonBag EmptyBag = False
isSingletonBag (UnitBag _) = True
isSingletonBag (TwoBags _ _) = False -- Neither is empty
isSingletonBag (ListBag xs) = isSingleton xs
filterBag :: (a -> Bool) -> Bag a -> Bag a
filterBag _ EmptyBag = EmptyBag
filterBag pred b@(UnitBag val) = if pred val then b else EmptyBag
filterBag pred (TwoBags b1 b2) = sat1 `unionBags` sat2
where sat1 = filterBag pred b1
sat2 = filterBag pred b2
filterBag pred (ListBag vs) = listToBag (filter pred vs)
filterBagM :: Monad m => (a -> m Bool) -> Bag a -> m (Bag a)
filterBagM _ EmptyBag = return EmptyBag
filterBagM pred b@(UnitBag val) = do
flag <- pred val
if flag then return b
else return EmptyBag
filterBagM pred (TwoBags b1 b2) = do
sat1 <- filterBagM pred b1
sat2 <- filterBagM pred b2
return (sat1 `unionBags` sat2)
filterBagM pred (ListBag vs) = do
sat <- filterM pred vs
return (listToBag sat)
anyBag :: (a -> Bool) -> Bag a -> Bool
anyBag _ EmptyBag = False
anyBag p (UnitBag v) = p v
anyBag p (TwoBags b1 b2) = anyBag p b1 || anyBag p b2
anyBag p (ListBag xs) = any p xs
anyBagM :: Monad m => (a -> m Bool) -> Bag a -> m Bool
anyBagM _ EmptyBag = return False
anyBagM p (UnitBag v) = p v
anyBagM p (TwoBags b1 b2) = do flag <- anyBagM p b1
if flag then return True
else anyBagM p b2
anyBagM p (ListBag xs) = anyM p xs
concatBag :: Bag (Bag a) -> Bag a
concatBag bss = foldrBag add emptyBag bss
where
add bs rs = bs `unionBags` rs
catBagMaybes :: Bag (Maybe a) -> Bag a
catBagMaybes bs = foldrBag add emptyBag bs
where
add Nothing rs = rs
add (Just x) rs = x `consBag` rs
partitionBag :: (a -> Bool) -> Bag a -> (Bag a {- Satisfy predictate -},
Bag a {- Don't -})
partitionBag _ EmptyBag = (EmptyBag, EmptyBag)
partitionBag pred b@(UnitBag val)
= if pred val then (b, EmptyBag) else (EmptyBag, b)
partitionBag pred (TwoBags b1 b2)
= (sat1 `unionBags` sat2, fail1 `unionBags` fail2)
where (sat1, fail1) = partitionBag pred b1
(sat2, fail2) = partitionBag pred b2
partitionBag pred (ListBag vs) = (listToBag sats, listToBag fails)
where (sats, fails) = partition pred vs
partitionBagWith :: (a -> Either b c) -> Bag a
-> (Bag b {- Left -},
Bag c {- Right -})
partitionBagWith _ EmptyBag = (EmptyBag, EmptyBag)
partitionBagWith pred (UnitBag val)
= case pred val of
Left a -> (UnitBag a, EmptyBag)
Right b -> (EmptyBag, UnitBag b)
partitionBagWith pred (TwoBags b1 b2)
= (sat1 `unionBags` sat2, fail1 `unionBags` fail2)
where (sat1, fail1) = partitionBagWith pred b1
(sat2, fail2) = partitionBagWith pred b2
partitionBagWith pred (ListBag vs) = (listToBag sats, listToBag fails)
where (sats, fails) = partitionWith pred vs
foldBag :: (r -> r -> r) -- Replace TwoBags with this; should be associative
-> (a -> r) -- Replace UnitBag with this
-> r -- Replace EmptyBag with this
-> Bag a
-> r
{- Standard definition
foldBag t u e EmptyBag = e
foldBag t u e (UnitBag x) = u x
foldBag t u e (TwoBags b1 b2) = (foldBag t u e b1) `t` (foldBag t u e b2)
foldBag t u e (ListBag xs) = foldr (t.u) e xs
-}
-- More tail-recursive definition, exploiting associativity of "t"
foldBag _ _ e EmptyBag = e
foldBag t u e (UnitBag x) = u x `t` e
foldBag t u e (TwoBags b1 b2) = foldBag t u (foldBag t u e b2) b1
foldBag t u e (ListBag xs) = foldr (t.u) e xs
foldrBag :: (a -> r -> r) -> r
-> Bag a
-> r
foldrBag _ z EmptyBag = z
foldrBag k z (UnitBag x) = k x z
foldrBag k z (TwoBags b1 b2) = foldrBag k (foldrBag k z b2) b1
foldrBag k z (ListBag xs) = foldr k z xs
foldlBag :: (r -> a -> r) -> r
-> Bag a
-> r
foldlBag _ z EmptyBag = z
foldlBag k z (UnitBag x) = k z x
foldlBag k z (TwoBags b1 b2) = foldlBag k (foldlBag k z b1) b2
foldlBag k z (ListBag xs) = foldl k z xs
foldrBagM :: (Monad m) => (a -> b -> m b) -> b -> Bag a -> m b
foldrBagM _ z EmptyBag = return z
foldrBagM k z (UnitBag x) = k x z
foldrBagM k z (TwoBags b1 b2) = do { z' <- foldrBagM k z b2; foldrBagM k z' b1 }
foldrBagM k z (ListBag xs) = foldrM k z xs
foldlBagM :: (Monad m) => (b -> a -> m b) -> b -> Bag a -> m b
foldlBagM _ z EmptyBag = return z
foldlBagM k z (UnitBag x) = k z x
foldlBagM k z (TwoBags b1 b2) = do { z' <- foldlBagM k z b1; foldlBagM k z' b2 }
foldlBagM k z (ListBag xs) = foldlM k z xs
mapBag :: (a -> b) -> Bag a -> Bag b
mapBag _ EmptyBag = EmptyBag
mapBag f (UnitBag x) = UnitBag (f x)
mapBag f (TwoBags b1 b2) = TwoBags (mapBag f b1) (mapBag f b2)
mapBag f (ListBag xs) = ListBag (map f xs)
mapBagM :: Monad m => (a -> m b) -> Bag a -> m (Bag b)
mapBagM _ EmptyBag = return EmptyBag
mapBagM f (UnitBag x) = do r <- f x
return (UnitBag r)
mapBagM f (TwoBags b1 b2) = do r1 <- mapBagM f b1
r2 <- mapBagM f b2
return (TwoBags r1 r2)
mapBagM f (ListBag xs) = do rs <- mapM f xs
return (ListBag rs)
mapBagM_ :: Monad m => (a -> m b) -> Bag a -> m ()
mapBagM_ _ EmptyBag = return ()
mapBagM_ f (UnitBag x) = f x >> return ()
mapBagM_ f (TwoBags b1 b2) = mapBagM_ f b1 >> mapBagM_ f b2
mapBagM_ f (ListBag xs) = mapM_ f xs
flatMapBagM :: Monad m => (a -> m (Bag b)) -> Bag a -> m (Bag b)
flatMapBagM _ EmptyBag = return EmptyBag
flatMapBagM f (UnitBag x) = f x
flatMapBagM f (TwoBags b1 b2) = do r1 <- flatMapBagM f b1
r2 <- flatMapBagM f b2
return (r1 `unionBags` r2)
flatMapBagM f (ListBag xs) = foldrM k EmptyBag xs
where
k x b2 = do { b1 <- f x; return (b1 `unionBags` b2) }
flatMapBagPairM :: Monad m => (a -> m (Bag b, Bag c)) -> Bag a -> m (Bag b, Bag c)
flatMapBagPairM _ EmptyBag = return (EmptyBag, EmptyBag)
flatMapBagPairM f (UnitBag x) = f x
flatMapBagPairM f (TwoBags b1 b2) = do (r1,s1) <- flatMapBagPairM f b1
(r2,s2) <- flatMapBagPairM f b2
return (r1 `unionBags` r2, s1 `unionBags` s2)
flatMapBagPairM f (ListBag xs) = foldrM k (EmptyBag, EmptyBag) xs
where
k x (r2,s2) = do { (r1,s1) <- f x
; return (r1 `unionBags` r2, s1 `unionBags` s2) }
mapAndUnzipBagM :: Monad m => (a -> m (b,c)) -> Bag a -> m (Bag b, Bag c)
mapAndUnzipBagM _ EmptyBag = return (EmptyBag, EmptyBag)
mapAndUnzipBagM f (UnitBag x) = do (r,s) <- f x
return (UnitBag r, UnitBag s)
mapAndUnzipBagM f (TwoBags b1 b2) = do (r1,s1) <- mapAndUnzipBagM f b1
(r2,s2) <- mapAndUnzipBagM f b2
return (TwoBags r1 r2, TwoBags s1 s2)
mapAndUnzipBagM f (ListBag xs) = do ts <- mapM f xs
let (rs,ss) = unzip ts
return (ListBag rs, ListBag ss)
mapAccumBagL ::(acc -> x -> (acc, y)) -- ^ combining funcction
-> acc -- ^ initial state
-> Bag x -- ^ inputs
-> (acc, Bag y) -- ^ final state, outputs
mapAccumBagL _ s EmptyBag = (s, EmptyBag)
mapAccumBagL f s (UnitBag x) = let (s1, x1) = f s x in (s1, UnitBag x1)
mapAccumBagL f s (TwoBags b1 b2) = let (s1, b1') = mapAccumBagL f s b1
(s2, b2') = mapAccumBagL f s1 b2
in (s2, TwoBags b1' b2')
mapAccumBagL f s (ListBag xs) = let (s', xs') = mapAccumL f s xs
in (s', ListBag xs')
mapAccumBagLM :: Monad m
=> (acc -> x -> m (acc, y)) -- ^ combining funcction
-> acc -- ^ initial state
-> Bag x -- ^ inputs
-> m (acc, Bag y) -- ^ final state, outputs
mapAccumBagLM _ s EmptyBag = return (s, EmptyBag)
mapAccumBagLM f s (UnitBag x) = do { (s1, x1) <- f s x; return (s1, UnitBag x1) }
mapAccumBagLM f s (TwoBags b1 b2) = do { (s1, b1') <- mapAccumBagLM f s b1
; (s2, b2') <- mapAccumBagLM f s1 b2
; return (s2, TwoBags b1' b2') }
mapAccumBagLM f s (ListBag xs) = do { (s', xs') <- mapAccumLM f s xs
; return (s', ListBag xs') }
listToBag :: [a] -> Bag a
listToBag [] = EmptyBag
listToBag vs = ListBag vs
bagToList :: Bag a -> [a]
bagToList b = foldrBag (:) [] b
instance (Outputable a) => Outputable (Bag a) where
ppr bag = braces (pprWithCommas ppr (bagToList bag))
instance Data a => Data (Bag a) where
gfoldl k z b = z listToBag `k` bagToList b -- traverse abstract type abstractly
toConstr _ = abstractConstr $ "Bag("++show (typeOf (undefined::a))++")"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Bag"
dataCast1 x = gcast1 x
instance Foldable.Foldable Bag where
foldr = foldrBag
| mettekou/ghc | compiler/utils/Bag.hs | bsd-3-clause | 11,482 | 0 | 11 | 3,668 | 4,533 | 2,302 | 2,231 | 241 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
module Math.Hclaws.LinearAlgebra (
Point(..),
point,
Normable(..),
) where
import qualified Math.FTensor.Algebra as A
import qualified Math.FTensor.General as F
data Point = Point
{ x :: !Double
, t :: !Double
}
deriving (Show, Eq)
instance A.Additive Point where
(+.) p1 p2 = Point (x p1 + x p2) (t p1 + t p2)
instance A.WithZero Point where
zero = Point 0 0
instance A.WithNegatives Point where
neg Point{..} = Point (negate x) (negate t)
(-.) p1 p2 = Point (x p1 - x p2) (t p1 - t p2)
point :: Double -> Double -> Point
point x' t' = Point {x=x', t=t'}
class Normable a where
normP :: Double -> a -> Double
instance Normable Double where
normP _ = abs
instance Normable (F.TensorBoxed dims Double) where
normP p t
| p < 1 = error "normP called with p<1"
| p == (1/0) = maximum $ fmap abs t
| otherwise = (sum $ fmap (\x -> (abs x)**p) t)**(1/p)
instance Normable Point where
normP p Point{..}
| p < 1 = error "normP called with p<1"
| p == (1/0) = max (abs x) (abs t)
| otherwise = ((abs x)**p + (abs t)**p)**(1/p)
| mikebenfield/hclaws | src/Math/Hclaws/LinearAlgebra.hs | isc | 1,197 | 0 | 15 | 312 | 554 | 289 | 265 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-
This is a test of how the browser draws lines.
This is a second line.
This is a third.
That was a blank line above this.
@r@_Right justify
@c@_Center justify
@_Left justify
@bBold text
@iItalic text
@b@iBold Italic
@fFixed width
@f@bBold Fixed
@f@iItalic Fixed
@f@i@bBold Italic Fixed
@lLarge
@l@bLarge bold
@sSmall
@s@bSmall bold
@s@iSmall italic
@s@i@bSmall italic bold
@uunderscore
@C1RED
@C2Green
@C4Blue
You should try different browser types:
Fl_Browser
Fl_Select_Browser
Fl_Hold_Browser
Fl_Multi_Browser
-}
module Main where
import qualified Graphics.UI.FLTK.LowLevel.FL as FL
import Graphics.UI.FLTK.LowLevel.FLTKHS
import Control.Monad
import System.Environment
import qualified Data.Text as T
data CallbackType = Top | Middle | Bottom | Visible | Browser
bCb :: Ref SelectBrowser -> IO ()
bCb browser' = do
lineNumber <- getValue browser'
clicks <- FL.eventClicks
putStrLn ("callback, selection = " ++ (show lineNumber) ++ " eventClicks = " ++ (show clicks))
showCb :: CallbackType -> Ref Input -> Ref SelectBrowser -> IO ()
showCb buttontype' field' browser' = do
line' <- getValue field'
if (T.null line')
then print ("Please enter a number in the text field before clicking on the buttons." :: String)
else do
let lineNumber' = read (T.unpack line')
case buttontype' of
Top -> setTopline browser' (LineNumber lineNumber')
Bottom -> setBottomline browser' (LineNumber lineNumber')
Middle -> setMiddleline browser' (LineNumber lineNumber')
_ -> makeVisible browser' (LineNumber lineNumber')
swapCb :: Ref SelectBrowser -> Ref Button -> IO ()
swapCb browser' _ =
do
browserSize' <- getSize browser'
linesSelected' <- filterM (selected browser') (map LineNumber [0..(browserSize' - 1)])
case linesSelected' of
(l1:l2:_) -> swap browser' l1 l2
(l1:[]) -> swap browser' l1 (LineNumber (-1))
_ -> swap browser' (LineNumber (-1)) (LineNumber (-1))
sortCb :: Ref SelectBrowser -> Ref Button -> IO ()
sortCb browser' _ = sortWithSortType browser' SortAscending
btypeCb :: Ref SelectBrowser -> Ref Choice -> IO ()
btypeCb browser' btype' = do
numLines' <- getSize browser'
forM_ [1..(numLines' - 1)] (\l -> select browser' (LineNumber l) False)
_ <- select browser' (LineNumber 1) False -- leave focus box on first line
choice' <- getText btype'
case choice' of
"Normal" -> setType browser' NormalBrowserType
"Select" -> setType browser' SelectBrowserType
"Hold" -> setType browser' HoldBrowserType
"Multi" -> setType browser' MultiBrowserType
_ -> return ()
redraw browser'
main :: IO ()
main = do
args <- getArgs
if (null args) then print ("Enter the path to a text file as an argument. As an example use this file (./src/Examples/browser.hs) to see what Fl_Browser can do." :: String)
else do
let fname = T.pack (head args)
window <- doubleWindowNew (Size (Width 560) (Height 400)) Nothing (Just fname)
browser' <- selectBrowserNew (Rectangle (Position (X 0) (Y 0)) (Size (Width 560) (Height 350))) Nothing
setType browser' MultiBrowserType
setCallback browser' bCb
loadStatus' <- load browser' fname
case loadStatus' of
Left _ -> print ("Can't load " ++ T.unpack fname)
_ -> do
setPosition browser' (PixelPosition 0)
field <- inputNew (toRectangle (55,350,505,25)) (Just "Line #:") (Just FlIntInput)
setCallback field (\_ -> showCb Browser field browser')
top' <- buttonNew (toRectangle (0,375,80,25)) (Just "Top")
setCallback top' (\_ -> showCb Top field browser')
bottom' <- buttonNew (toRectangle (80,375,80,25)) (Just "Bottom")
setCallback bottom' (\_ -> showCb Bottom field browser')
middle' <- buttonNew (toRectangle (160,375,80,25)) (Just "Middle")
setCallback middle' (\_ -> showCb Middle field browser')
visible' <- buttonNew (toRectangle (240,375,80,25)) (Just "Make Vis.")
setCallback visible' (\_ -> showCb Visible field browser')
swap' <- buttonNew (toRectangle (320,375,80,25)) (Just "Swap")
setCallback swap' $ swapCb browser'
setTooltip swap' "Swaps two selected lines\n(Use CTRL-click to select two lines)"
sort' <- buttonNew (toRectangle (400,375,80,25)) (Just "Sort")
setCallback sort' (sortCb browser')
btype <- choiceNew (toRectangle (480,375,80,25)) Nothing
addName btype "Normal"
addName btype "Select"
addName btype "Hold"
addName btype "Multi"
setCallback btype $ btypeCb browser'
_ <- setValue btype (MenuItemByIndex (AtIndex 3))
setResizable window (Just browser')
showWidget window
_ <- FL.run
return ()
| deech/fltkhs-demos | src/Examples/browser.hs | mit | 4,793 | 0 | 20 | 1,043 | 1,509 | 735 | 774 | 90 | 5 |
main = interact wordCount
where wordCount input = show (length (words input)) ++ "\n" | manhong2112/CodeColle | Haskell/WC.hs | mit | 89 | 0 | 10 | 17 | 38 | 18 | 20 | 2 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
-- | Utilities for reifying simplified datatype info. It omits details
-- that aren't usually relevant to generating instances that work with
-- the datatype. This makes it easier to use TH to derive instances.
--
-- The \"Simple\" in the module name refers to the simplicity of the
-- datatypes, not the module itself, which exports quite a few things
-- which are useful in some circumstance or another. I anticipate that
-- the most common uses of this will be the following APIs:
--
-- * Getting info about a @data@ or @newtype@ declaration, via
-- 'DataType', 'reifyDataType', and 'DataCon'. This is useful for
-- writing something which generates declarations based on a datatype,
-- one of the most common uses of Template Haskell.
--
-- * Getting nicely structured info about a named type. See 'TypeInfo'
-- and 'reifyType'. This does not yet support reifying typeclasses,
-- primitive type constructors, or type variables ('TyVarI').
--
-- Currently, this module supports reifying simplified versions of the
-- following 'Info' constructors:
--
-- * 'TyConI' with 'DataD' and 'NewtypeD' (becomes a 'DataType' value)
--
-- * 'FamilyI' becomes a 'DataFamily' or 'TypeFamily' value.
--
-- * 'DataConI' becomes a 'DataCon' value.
--
-- In the future it will hopefully also have support for the remaining
-- 'Info' constructors, 'ClassI', 'ClassOpI', 'PrimTyConI', 'VarI', and
-- 'TyVarI'.
module TH.ReifySimple
(
-- * Reifying simplified type info
TypeInfo, reifyType, infoToType
, reifyTypeNoDataKinds, infoToTypeNoDataKinds
-- * Reifying simplified info for specific declaration varieties
-- ** Datatype info
, DataType(..), reifyDataType, infoToDataType
-- ** Data constructor info
, DataCon(..), reifyDataCon, infoToDataCon, typeToDataCon
-- ** Data family info
, DataFamily(..), DataInst(..), reifyDataFamily, infoToDataFamily
-- ** Type family info
, TypeFamily(..), TypeInst(..), reifyTypeFamily, infoToTypeFamily
-- * Other utilities
, conToDataCons
, reifyDataTypeSubstituted
) where
import Control.Applicative
import Data.Data (Data, gmapT)
import Data.Generics.Aliases (extT)
import qualified Data.Map as M
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Language.Haskell.TH
#if MIN_VERSION_template_haskell(2,16,0)
hiding (reifyType)
#endif
import Language.Haskell.TH.Instances ()
import TH.Utilities
data TypeInfo
= DataTypeInfo DataType
| DataFamilyInfo DataFamily
| TypeFamilyInfo TypeFamily
| LiftedDataConInfo DataCon
-- | Reifies a 'Name' as a 'TypeInfo', and calls 'fail' if this doesn't
-- work. Use 'reify' with 'infoToType' if you want to handle the failure
-- case more gracefully.
--
-- This does not yet support reifying typeclasses, primitive type
-- constructors, or type variables ('TyVarI').
reifyType :: Name -> Q TypeInfo
reifyType name = do
info <- reify name
mres <- infoToType info
case mres of
Just res -> return res
Nothing -> fail $
"Expected to reify a data type, data family, or type family. Instead got:\n" ++
pprint info
-- | Convert an 'Info' into a 'TypeInfo' if possible, and otherwise
-- yield 'Nothing'. Needs to run in 'Q' so that
infoToType :: Info -> Q (Maybe TypeInfo)
infoToType info =
case (infoToTypeNoDataKinds info, infoToDataCon info) of
(Just result, _) -> return (Just result)
(Nothing, Just dc) -> do
#if MIN_VERSION_template_haskell(2,11,0)
dataKindsEnabled <- isExtEnabled DataKinds
#else
reportWarning $
"For " ++ pprint (dcName dc) ++
", assuming DataKinds is on, and yielding LiftedDataConInfo."
let dataKindsEnabled = True
#endif
return $ if dataKindsEnabled then Just (LiftedDataConInfo dc) else Nothing
(Nothing, Nothing) -> return Nothing
-- | Reifies type info, but instead of yielding a 'LiftedDataConInfo',
-- will instead yield 'Nothing'.
reifyTypeNoDataKinds :: Name -> Q (Maybe TypeInfo)
reifyTypeNoDataKinds = fmap infoToTypeNoDataKinds . reify
-- | Convert an 'Info into a 'TypeInfo' if possible. If it's a data
-- constructor, instead of yielding 'LiftedDataConInfo', it will instead
-- yield 'Nothing'.
infoToTypeNoDataKinds :: Info -> Maybe TypeInfo
infoToTypeNoDataKinds info =
(DataTypeInfo <$> infoToDataType info) <|>
(DataFamilyInfo <$> infoToDataFamily info) <|>
(TypeFamilyInfo <$> infoToTypeFamily info)
--------------------------------------------------------------------------------
-- Reifying specific declaration varieties
-- | Simplified info about a 'DataD'. Omits deriving, strictness,
-- kind info, and whether it's @data@ or @newtype@.
data DataType = DataType
{ dtName :: Name
, dtTvs :: [Name]
, dtCxt :: Cxt
, dtCons :: [DataCon]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a 'Con'. Omits deriving, strictness, and kind
-- info. This is much nicer than consuming 'Con' directly, because it
-- unifies all the constructors into one.
data DataCon = DataCon
{ dcName :: Name
, dcTvs :: [Name]
, dcCxt :: Cxt
, dcFields :: [(Maybe Name, Type)]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a data family. Omits deriving, strictness, and
-- kind info.
data DataFamily = DataFamily
{ dfName :: Name
, dfTvs :: [Name]
, dfInsts :: [DataInst]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a data family instance. Omits deriving,
-- strictness, and kind info.
data DataInst = DataInst
{ diName :: Name
, diCxt :: Cxt
, diParams :: [Type]
, diCons :: [DataCon]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a type family. Omits kind info and injectivity
-- info.
data TypeFamily = TypeFamily
{ tfName :: Name
, tfTvs :: [Name]
, tfInsts :: [TypeInst]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a type family instance. Omits nothing.
data TypeInst = TypeInst
{ tiName :: Name
, tiParams :: [Type]
, tiType :: Type
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Reify the given data or newtype declaration, and yields its
-- 'DataType' representation.
reifyDataType :: Name -> Q DataType
reifyDataType name = do
info <- reify name
case infoToDataType info of
Nothing -> fail $ "Expected to reify a datatype. Instead got:\n" ++ pprint info
Just x -> return x
-- | Reify the given data constructor.
reifyDataCon :: Name -> Q DataCon
reifyDataCon name = do
info <- reify name
case infoToDataCon info of
Nothing -> fail $ "Expected to reify a constructor. Instead got:\n" ++ pprint info
Just x -> return x
-- | Reify the given data family, and yield its 'DataFamily'
-- representation.
reifyDataFamily :: Name -> Q DataFamily
reifyDataFamily name = do
info <- reify name
case infoToDataFamily info of
Nothing -> fail $ "Expected to reify a data family. Instead got:\n" ++ pprint info
Just x -> return x
-- | Reify the given type family instance declaration, and yields its
-- 'TypeInst' representation.
reifyTypeFamily :: Name -> Q TypeFamily
reifyTypeFamily name = do
info <- reify name
case infoToTypeFamily info of
Nothing -> fail $ "Expected to reify a type family. Instead got:\n" ++ pprint info
Just x -> return x
infoToDataType :: Info -> Maybe DataType
infoToDataType info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (DataD preds name tvs _kind cons _deriving) ->
#else
TyConI (DataD preds name tvs cons _deriving) ->
#endif
Just $ DataType name (map tyVarBndrName tvs) preds (concatMap conToDataCons cons)
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (NewtypeD preds name tvs _kind con _deriving) ->
#else
TyConI (NewtypeD preds name tvs con _deriving) ->
#endif
Just $ DataType name (map tyVarBndrName tvs) preds (conToDataCons con)
_ -> Nothing
infoToDataFamily :: Info -> Maybe DataFamily
infoToDataFamily info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
FamilyI (DataFamilyD name tvs _kind) insts ->
#else
FamilyI (FamilyD DataFam name tvs _kind) insts ->
#endif
Just $ DataFamily name (map tyVarBndrName tvs) (map go insts)
_ -> Nothing
where
#if MIN_VERSION_template_haskell(2,15,0)
go (NewtypeInstD preds _ lhs _kind con _deriving)
| ConT name:params <- unAppsT lhs
#elif MIN_VERSION_template_haskell(2,11,0)
go (NewtypeInstD preds name params _kind con _deriving)
#else
go (NewtypeInstD preds name params con _deriving)
#endif
= DataInst name preds params (conToDataCons con)
#if MIN_VERSION_template_haskell(2,15,0)
go (DataInstD preds _ lhs _kind cons _deriving)
| ConT name:params <- unAppsT lhs
#elif MIN_VERSION_template_haskell(2,11,0)
go (DataInstD preds name params _kind cons _deriving)
#else
go (DataInstD preds name params cons _deriving)
#endif
= DataInst name preds params (concatMap conToDataCons cons)
go info' = error $
"Unexpected instance in FamilyI in infoToDataInsts:\n" ++ pprint info'
infoToTypeFamily :: Info -> Maybe TypeFamily
infoToTypeFamily info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
FamilyI (ClosedTypeFamilyD (TypeFamilyHead name tvs _result _injectivity) eqns) _ ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goEqn name) eqns
FamilyI (OpenTypeFamilyD (TypeFamilyHead name tvs _result _injectivity)) insts ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goInst name) insts
#else
FamilyI (ClosedTypeFamilyD name tvs _kind eqns) [] ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goEqn name) eqns
FamilyI (FamilyD TypeFam name tvs _kind) insts ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goInst name) insts
#endif
_ -> Nothing
where
#if MIN_VERSION_template_haskell(2,15,0)
toParams ps (AppT ty p) = toParams (p : ps) ty
toParams ps (AppKindT ty _) = toParams ps ty
toParams ps _ = ps
goEqn name (TySynEqn _ lty rty) = TypeInst name (toParams [] lty) rty
goInst name (TySynInstD eqn) = goEqn name eqn
goInst _ info' = error $
"Unexpected instance in FamilyI in infoToTypeInsts:\n" ++ pprint info'
#else
goEqn name (TySynEqn params ty) = TypeInst name params ty
goInst name (TySynInstD _ eqn) = goEqn name eqn
goInst _ info' = error $
"Unexpected instance in FamilyI in infoToTypeInsts:\n" ++ pprint info'
#endif
infoToDataCon :: Info -> Maybe DataCon
infoToDataCon info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
DataConI name ty _parent ->
#else
DataConI name ty _parent _fixity ->
#endif
Just (typeToDataCon name ty)
_ -> Nothing
-- | Creates a 'DataCon' given the 'Name' and 'Type' of a
-- data-constructor. Note that the result the function type is *not* checked to match the provided 'Name'.
typeToDataCon :: Name -> Type -> DataCon
typeToDataCon dcName ty0 = DataCon {..}
where
(dcTvs, dcCxt, dcFields) = case ty0 of
ForallT tvs preds ty -> (map tyVarBndrName tvs, preds, typeToFields ty)
ty -> ([], [], typeToFields ty)
-- TODO: Should we sanity check the result type?
typeToFields = init . map (Nothing, ) . unAppsT
-- | Convert a 'Con' to a list of 'DataCon'. The result is a list
-- because 'GadtC' and 'RecGadtC' can define multiple constructors.
conToDataCons :: Con -> [DataCon]
conToDataCons = \case
NormalC name slots ->
[DataCon name [] [] (map (\(_, ty) -> (Nothing, ty)) slots)]
RecC name fields ->
[DataCon name [] [] (map (\(n, _, ty) -> (Just n, ty)) fields)]
InfixC (_, ty1) name (_, ty2) ->
[DataCon name [] [] [(Nothing, ty1), (Nothing, ty2)]]
ForallC tvs preds con ->
map (\(DataCon name tvs0 preds0 fields) ->
DataCon name (tvs0 ++ map tyVarBndrName tvs) (preds0 ++ preds) fields) (conToDataCons con)
#if MIN_VERSION_template_haskell(2,11,0)
GadtC ns slots _ ->
map (\dn -> DataCon dn [] [] (map (\(_, ty) -> (Nothing, ty)) slots)) ns
RecGadtC ns fields _ ->
map (\dn -> DataCon dn [] [] (map (\(fn, _, ty) -> (Just fn, ty)) fields)) ns
#endif
-- | Like 'reifyDataType', but takes a 'Type' instead of just the 'Name'
-- of the datatype. It expects a normal datatype argument (see
-- 'typeToNamedCon').
reifyDataTypeSubstituted :: Type -> Q DataType
reifyDataTypeSubstituted ty =
case typeToNamedCon ty of
Nothing -> fail $ "Expected a datatype, but reifyDataTypeSubstituted was applied to " ++ pprint ty
Just (n, args) -> do
dt <- reifyDataType n
let cons' = substituteTvs (M.fromList (zip (dtTvs dt) args)) (dtCons dt)
return (dt { dtCons = cons' })
-- TODO: add various handy generics based traversals to TH.Utilities
substituteTvs :: Data a => M.Map Name Type -> a -> a
substituteTvs mp = transformTypes go
where
go (VarT name) | Just ty <- M.lookup name mp = ty
go ty = gmapT (substituteTvs mp) ty
transformTypes :: Data a => (Type -> Type) -> a -> a
transformTypes f = gmapT (transformTypes f) `extT` (id :: String -> String) `extT` f
| fpco/th-utilities | src/TH/ReifySimple.hs | mit | 13,624 | 0 | 19 | 2,988 | 2,798 | 1,508 | 1,290 | 179 | 4 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.MediaKeyMessageEvent (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.MediaKeyMessageEvent
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.MediaKeyMessageEvent
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/MediaKeyMessageEvent.hs | mit | 373 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
import Data.Char (digitToInt)
asIntFold ('-' : s) = -1 * asIntFold s
asIntFold s = foldl (times_10) 0 (map digitToInt s)
where times_10 a b = a * 10 + b
concatFoldr a = foldr (\x y -> x ++ y) [] a
--takeCompare _ [] = ([], [])
--takeCompare _ (a: []) = ([a], [])
--takeCompare f (a: b: xs) =
-- if (f a b) then [a] ++ (takeCompare f (b: xs))
-- else [a]
--
| gefei/learning_haskell | real_world_haskell/ch06.hs | mit | 380 | 0 | 8 | 101 | 118 | 63 | 55 | 5 | 1 |
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Nauva.Client
( runClient
) where
import qualified Data.Text as T
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Data.Monoid
import Data.Maybe
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.Except
import Control.Monad.Writer
import System.IO.Unsafe
import Nauva.App
import Nauva.Handle
import Nauva.Internal.Types
import Nauva.View
import Nauva.Native.Bridge
import GHCJS.Types
import GHCJS.Marshal
import Data.JSString.Text
import qualified Data.JSString as JSS
import qualified JavaScript.Object as O
import JavaScript.Array.Internal (fromList)
newHeadH :: Handle -> Bridge -> IO HeadH
newHeadH nauvaH bridge = do
var <- newTVarIO []
pure $ HeadH
{ hElements = var
, hReplace = \newElements -> do
print (length newElements)
atomically $ writeTVar var newElements
processSignals nauvaH
h <- atomically $ do
instances <- mapM (\x -> fst <$> runWriterT (instantiate (Path []) x)) newElements
mapM instanceToJSVal instances
renderHead bridge (jsval $ fromList h)
}
newRouterH :: Handle -> IO RouterH
newRouterH nauvaH = do
var <- newTVarIO (Location "/")
chan <- newTChanIO
pure $ RouterH
{ hLocation = (var, chan)
, hPush = \url -> do
putStrLn $ "Router hPush: " <> T.unpack url
atomically $ do
writeTVar var (Location url)
writeTChan chan (Location url)
processSignals nauvaH
}
runClient :: App -> IO ()
runClient app = do
appEl <- getElementById ("app" :: JSString)
nauvaH <- newHandle
routerH <- newRouterH nauvaH
bridge <- newBridge appEl $ Impl
{ sendLocationImpl = \path -> void $ hPush routerH path
, componentEventImpl = \path val -> void $ dispatchComponentEventHandler nauvaH path val
, nodeEventImpl = \path val -> void $ dispatchNodeEventHandler nauvaH path val
, attachRefImpl = \path val -> void $ attachRefHandler nauvaH path val
, detachRefImpl = \path val -> void $ detachRefHandler nauvaH path val
, componentDidMountImpl = \path vals -> void $ componentDidMountHandler nauvaH path vals
, componentWillUnmountImpl = \path vals -> void $ componentWillUnmountHandler nauvaH path vals
}
headH <- newHeadH nauvaH bridge
appH <- AppH <$> pure headH <*> pure routerH
render nauvaH (rootElement app appH)
locationSignalCopy <- atomically $ dupTChan (snd $ hLocation routerH)
void $ forkIO $ forever $ do
path <- atomically $ do
locPathname <$> readTChan locationSignalCopy
pushLocation bridge (jsval $ textToJSString path)
changeSignalCopy <- atomically $ dupTChan (changeSignal nauvaH)
void $ forkIO $ forever $ do
change <- atomically $ readTChan changeSignalCopy
case change of
(ChangeRoot inst) -> do
spine <- atomically $ do
instanceToJSVal inst
-- rootInstance <- readTMVar (hInstance nauvaH)
-- instanceToJSVal rootInstance
renderSpine bridge spine
(ChangeComponent path inst) -> do
spine <- atomically $ instanceToJSVal inst
renderSpineAtPath bridge (unPath path) spine
-- spine <- atomically $ do
-- rootInstance <- readTMVar (hInstance nauvaH)
-- instanceToJSVal rootInstance
-- renderSpine bridge spine
spine <- atomically $ do
rootInstance <- readTMVar (hInstance nauvaH)
instanceToJSVal rootInstance
renderSpine bridge spine
pure ()
foreign import javascript unsafe "console.log($1)" js_log :: JSVal -> IO ()
hookHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO (Either String ())
hookHandler h path vals = do
res <- atomically $ runExceptT $ do
SomeComponentInstance (ComponentInstance _ component stateRef) <- contextForPath h path
state <- lift $ readTMVar stateRef
let rawHookActions = fromMaybe [] (unsafePerformIO (fromJSVal vals)) :: [A.Value]
forM rawHookActions $ \rawValue -> do
case A.parseEither parseValue rawValue of
Left e -> throwError e
Right value -> do
actions <- lift $ do
state <- takeTMVar stateRef
let (newState, actions) = processLifecycleEvent component value (componentProps state) (componentState state)
(newInst, _effects) <- runWriterT $ instantiate path $ renderComponent component (componentProps state) newState
putTMVar stateRef (State (componentProps state) newState (componentSignals state) newInst)
-- traceShowM path
writeTChan (changeSignal h) (ChangeComponent path $ IComponent path component stateRef)
pure actions
pure $ Effect (ComponentInstance path component stateRef) actions
case res of
Left e -> pure $ Left e
Right effects -> do
executeEffects h effects
pure $ Right ()
componentDidMountHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO (Either String ())
componentDidMountHandler = hookHandler
componentWillUnmountHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO (Either String ())
componentWillUnmountHandler = hookHandler
attachRefHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
attachRefHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchRef h path rawValue
case res of
Left e -> putStrLn $ "attachRefHandler: " <> e
Right () -> pure ()
detachRefHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
detachRefHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchRef h path rawValue
case res of
Left e -> putStrLn $ "detachRefHandler: " <> e
Right () -> pure ()
dispatchNodeEventHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
dispatchNodeEventHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchEvent h path rawValue
case res of
Left e -> putStrLn $ "dispatchNodeEventHandler: " <> e
Right () -> pure ()
dispatchComponentEventHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
dispatchComponentEventHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchEvent h path rawValue
case res of
Left e -> putStrLn $ "dispatchComponentEventHandler: " <> e
Right () -> pure ()
foreign import javascript unsafe "$r = $1"
js_intJSVal :: Int -> JSVal
foreign import javascript unsafe "$r = $1"
js_doubleJSVal :: Double -> JSVal
foreign import javascript unsafe "true"
js_true :: JSVal
foreign import javascript unsafe "false"
js_false :: JSVal
foreign import javascript unsafe "$r = null"
js_null :: JSVal
jsCondition :: Condition -> JSVal
jsCondition (CMedia x) = jsval $ fromList [js_intJSVal 1, jsval $ textToJSString x]
jsCondition (CSupports x) = jsval $ fromList [js_intJSVal 2, jsval $ textToJSString x]
jsCSSRule :: CSSRule -> JSVal
jsCSSRule (CSSStyleRule name hash conditions suffixes styleDeclaration) = jsval $ fromList
[ js_intJSVal 1
, jsval $ textToJSString name
, jsval $ textToJSString $ unHash hash
, jsval $ fromList $ map jsCondition conditions
, jsval $ fromList $ map (jsval . JSS.pack . T.unpack . unSuffix) suffixes
, unsafePerformIO $ do
o <- O.create
forM_ styleDeclaration $ \(k, v) -> do
O.setProp (JSS.pack $ T.unpack k) (jsval $ JSS.pack $ T.unpack $ unCSSValue v) o
pure $ jsval o
]
jsCSSRule (CSSFontFaceRule hash styleDeclaration) = jsval $ fromList
[ js_intJSVal 5
, jsval $ textToJSString $ unHash hash
, unsafePerformIO $ do
o <- O.create
forM_ styleDeclaration $ \(k, v) -> do
O.setProp (JSS.pack $ T.unpack k) (jsval $ JSS.pack $ T.unpack $ unCSSValue v) o
pure $ jsval o
]
fToJSVal :: F -> JSVal
fToJSVal f = unsafePerformIO $ do
o <- O.create
O.setProp "id" (jsval $ textToJSString $ unFID $ fId f) o
O.setProp "constructors" (jsval $ fromList $ map (jsval . textToJSString) $ fConstructors f) o
O.setProp "arguments" (jsval $ fromList $ map (jsval . textToJSString) $ fArguments f) o
O.setProp "body" (jsval $ textToJSString $ fBody f) o
pure $ jsval o
instanceToJSVal :: Instance -> STM JSVal
instanceToJSVal = go []
where
go :: [Key] -> Instance -> STM JSVal
go path inst = case inst of
(INull _) -> pure js_null
(IText _ text) -> pure $ jsval $ textToJSString text
(INode _ tag attrs children) -> do
newChildren <- forM children $ \(key, childI) -> do
newChild <- instanceToJSVal childI
key' <- case key of
(KIndex i) -> pure $ js_intJSVal i
(KString s) -> pure $ (jsval $ textToJSString s)
pure $ jsval $ fromList [key', newChild]
pure $ unsafePerformIO $ do
o <- O.create
attributes' <- pure $ jsval $ fromList $ flip map attrs $ \x -> case x of
AVAL an (AVBool b) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, if b then js_true else js_false]
AVAL an (AVString s) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, jsval $ textToJSString s]
AVAL an (AVInt i) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, js_intJSVal i]
AVAL an (AVDouble d) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, js_doubleJSVal d]
AEVL (EventListener n f) -> jsval $ fromList
[ jsval $ textToJSString "AEVL"
, jsval $ textToJSString n
, fToJSVal f
]
ASTY style -> jsval $ fromList
[ jsval $ textToJSString "ASTY"
, jsval $ fromList $ map jsCSSRule (unStyle style)
]
AREF (Ref mbRefKey fra frd) -> unsafePerformIO $ do
o <- O.create
case mbRefKey of
Nothing -> pure ()
Just (RefKey k) -> O.setProp "key" (js_intJSVal $ k) o
O.setProp "attach" (fToJSVal fra) o
O.setProp "detach" (fToJSVal frd) o
pure $ jsval $ fromList [jsval $ textToJSString "AREF", jsval o]
O.setProp "type" (jsval ("Node" :: JSString)) o
O.setProp "tag" (jsval $ textToJSString $ unTag tag) o
O.setProp "attributes" attributes' o
O.setProp "children" (jsval $ fromList newChildren) o
pure $ jsval o
(IThunk _ _ _ childI) ->
instanceToJSVal childI
(IComponent _ component stateRef) -> do
state <- readTMVar stateRef
spine <- instanceToJSVal $ componentInstance state
eventListeners' <- pure $ jsval $ fromList $ flip map (componentEventListeners component (componentState state)) $ \el -> case el of
(EventListener n f) -> jsval $ fromList
[ jsval $ textToJSString n
, fToJSVal f
]
pure $ unsafePerformIO $ do
o <- O.create
hooks <- O.create
O.setProp "componentDidMount" (jsval $ fromList $ map fToJSVal (componentDidMount (componentHooks component))) hooks
O.setProp "componentWillUnmount" (jsval $ fromList $ map fToJSVal (componentWillUnmount (componentHooks component))) hooks
O.setProp "type" (jsval ("Component" :: JSString)) o
O.setProp "id" (js_intJSVal $ unComponentId $ componentId component) o
O.setProp "displayName" (jsval $ textToJSString $ componentDisplayName component) o
O.setProp "eventListeners" eventListeners' o
O.setProp "hooks" (jsval hooks) o
O.setProp "spine" spine o
pure $ jsval o
| wereHamster/nauva | pkg/hs/nauva-native/src/Nauva/Client.hs | mit | 13,305 | 17 | 29 | 4,344 | 3,984 | 1,928 | 2,056 | 251 | 14 |
import Control.Monad
import Data.List
factorial n = product [1..n]
powerset :: [a] -> [[a]]
powerset = filterM $ \x->[True, False]
combination :: [a] -> Int -> [[a]]
combination list k = filter (\x -> length x == k) $ powerset list
permutation :: Eq a => [a] -> [[a]]
permutation = nub . perm
where perm [] = [[]]
perm list = [ x:xs | x <- list, xs <- perm $ delete x list ] | jwvg0425/HaskellScratchPad | src/factorial.hs | mit | 396 | 1 | 10 | 97 | 214 | 115 | 99 | 11 | 2 |
{-# htermination maximum :: (Ord a, Ord k) => [(Either a k)] -> (Either a k) #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_maximum_10.hs | mit | 81 | 0 | 2 | 17 | 3 | 2 | 1 | 1 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-}
module Util () where
import Data.ByteString.Builder (toLazyByteString)
import Text.Email.Validate
import Data.Text.Encoding
import Data.Aeson.Encode (encodeToByteStringBuilder)
import Data.Aeson.Types
import Happstack.Server
import Data.UUID.Aeson ()
import Hasql.Postgres
import Hasql.Backend
import Data.Text
instance ToMessage Value where
toContentType _ = "application/json; charset=utf-8"
toMessage = toLazyByteString . encodeToByteStringBuilder
toResponse x = toResponseBS (toContentType x) (toMessage x)
instance ToJSON EmailAddress where
toJSON e = String (decodeUtf8 $ toByteString e)
instance FromJSON EmailAddress where
parseJSON v = withText name (go . emailAddress . encodeUtf8) v where
go Nothing = typeMismatch name v
go (Just x) = return x
name = "EmailAddress"
instance CxValue Postgres EmailAddress where
encodeValue = encodeValue . decodeUtf8 . toByteString
decodeValue v = decodeValue v >>= \x -> case validate (encodeUtf8 x) of
Left l -> Left (pack $ l ++ show x)
Right r -> Right r
| L8D/cido-api | lib/Util.hs | mit | 1,190 | 0 | 14 | 231 | 322 | 170 | 152 | 29 | 0 |
module Main where
import PostgREST.App
import PostgREST.Config (AppConfig (..),
minimumPgVersion,
prettyVersion,
readOptions)
import PostgREST.DbStructure
import PostgREST.Error (PgError, pgErrResponse)
import PostgREST.Middleware
import Control.Concurrent (myThreadId)
import Control.Exception.Base (throwTo, AsyncException(..))
import Control.Monad (unless, void)
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (encode)
import Data.Functor.Identity
import Data.Monoid ((<>))
import Data.String.Conversions (cs)
import Data.Text (Text)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Hasql as H
import qualified Hasql.Postgres as P
import Network.Wai
import Network.Wai.Handler.Warp hiding (Connection)
import Network.Wai.Middleware.RequestLogger (logStdout)
import System.IO (BufferMode (..),
hSetBuffering, stderr,
stdin, stdout)
import System.Posix.Signals
import Web.JWT (secret)
isServerVersionSupported :: H.Session P.Postgres IO Bool
isServerVersionSupported = do
Identity (row :: Text) <- H.tx Nothing $ H.singleEx [H.stmt|SHOW server_version_num|]
return $ read (cs row) >= minimumPgVersion
hasqlError :: PgError -> IO a
hasqlError = error . cs . encode
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
hSetBuffering stderr NoBuffering
conf <- readOptions
let port = configPort conf
unless (secret "secret" /= configJwtSecret conf) $
putStrLn "WARNING, running in insecure mode, JWT secret is the default value"
Prelude.putStrLn $ "Listening on port " ++
(show $ configPort conf :: String)
let pgSettings = P.StringSettings $ cs (configDatabase conf)
appSettings = setPort port
. setServerName (cs $ "postgrest/" <> prettyVersion)
$ defaultSettings
middle = logStdout . defaultMiddle
poolSettings <- maybe (fail "Improper session settings") return $
H.poolSettings (fromIntegral $ configPool conf) 30
pool :: H.Pool P.Postgres <- H.acquirePool pgSettings poolSettings
supportedOrError <- H.session pool isServerVersionSupported
either hasqlError
(\supported ->
unless supported $
error (
"Cannot run in this PostgreSQL version, PostgREST needs at least "
<> show minimumPgVersion)
) supportedOrError
tid <- myThreadId
void $ installHandler keyboardSignal (Catch $ do
H.releasePool pool
throwTo tid UserInterrupt
) Nothing
let txSettings = Just (H.ReadCommitted, Just True)
dbOrError <- H.session pool $ H.tx txSettings $ getDbStructure (cs $ configSchema conf)
dbStructure <- either hasqlError return dbOrError
runSettings appSettings $ middle $ \ req respond -> do
time <- getPOSIXTime
body <- strictRequestBody req
resOrError <- liftIO $ H.session pool $ H.tx txSettings $
runWithClaims conf time (app dbStructure conf body) req
either (respond . pgErrResponse) respond resOrError
| NikolayS/postgrest | src/PostgREST/Main.hs | mit | 3,777 | 0 | 16 | 1,359 | 869 | 451 | 418 | -1 | -1 |
module Euler.E63 where
import Euler.Lib
( intLength
)
euler63 :: Int
euler63 = length $ concat $ takeWhile (not . null) $ map validNums [ 1 .. ]
validNums :: Integer -> [Integer]
validNums n = takeWhile ((== n) . intLength) $ dropWhile ((<n) . intLength) $
[ x^n
| x <- [ 1 .. ]
]
main :: IO ()
main = print $ euler63
| D4r1/project-euler | Euler/E63.hs | mit | 327 | 8 | 10 | 75 | 159 | 88 | 71 | 11 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Protolude (
-- * Base functions
module Base,
identity,
pass,
#if !MIN_VERSION_base(4,8,0)
(&),
scanl',
#endif
-- * Function functions
module Function,
applyN,
-- * List functions
module List,
map,
uncons,
unsnoc,
-- * Data Structures
module DataStructures,
-- * Show functions
module Show,
show,
print,
-- * Bool functions
module Bool,
-- * Monad functions
module Monad,
liftIO1,
liftIO2,
-- * Functor functions
module Functor,
-- * Either functions
module Either,
-- * Applicative functions
module Applicative,
guarded,
guardedA,
-- * String conversion
module ConvertText,
-- * Debug functions
module Debug,
-- * Panic functions
module Panic,
-- * Exception functions
module Exception,
Protolude.throwIO,
Protolude.throwTo,
-- * Semiring functions
module Semiring,
-- * String functions
module String,
-- * Safe functions
module Safe,
-- * Eq functions
module Eq,
-- * Ord functions
module Ord,
-- * Traversable functions
module Traversable,
-- * Foldable functions
module Foldable,
-- * Semigroup functions
#if MIN_VERSION_base(4,9,0)
module Semigroup,
#endif
-- * Monoid functions
module Monoid,
-- * Bifunctor functions
module Bifunctor,
-- * Bifunctor functions
module Hashable,
-- * Deepseq functions
module DeepSeq,
-- * Tuple functions
module Tuple,
module Typeable,
#if MIN_VERSION_base(4,7,0)
-- * Typelevel programming
module Typelevel,
#endif
-- * Monads
module Fail,
module State,
module Reader,
module Except,
module Trans,
module ST,
module STM,
-- * Integers
module Int,
module Bits,
-- * Complex functions
module Complex,
-- * Char functions
module Char,
-- * Maybe functions
module Maybe,
-- * Generics functions
module Generics,
-- * ByteString functions
module ByteString,
LByteString,
-- * Text functions
module Text,
LText,
-- * Read functions
module Read,
readMaybe,
readEither,
-- * System functions
module System,
die,
-- * Concurrency functions
module Concurrency,
-- * Foreign functions
module Foreign,
) where
-- Protolude module exports.
import Protolude.Debug as Debug
import Protolude.List as List
import Protolude.Show as Show
import Protolude.Bool as Bool
import Protolude.Monad as Monad
import Protolude.Functor as Functor
import Protolude.Either as Either
import Protolude.Applicative as Applicative
import Protolude.ConvertText as ConvertText
import Protolude.Panic as Panic
import Protolude.Exceptions as Exception
import Protolude.Semiring as Semiring
import qualified Protolude.Conv as Conv
import Protolude.Base as Base hiding (
putStr -- Overriden by Show.putStr
, putStrLn -- Overriden by Show.putStrLn
, print -- Overriden by Protolude.print
, show -- Overriden by Protolude.show
, showFloat -- Custom Show instances deprecated.
, showList -- Custom Show instances deprecated.
, showSigned -- Custom Show instances deprecated.
, showSignedFloat -- Custom Show instances deprecated.
, showsPrec -- Custom Show instances deprecated.
)
import qualified Protolude.Base as PBase
-- Used for 'show', not exported.
import Data.String (String)
import Data.String as String (IsString)
-- Maybe'ized version of partial functions
import Protolude.Safe as Safe (
headMay
, headDef
, initMay
, initDef
, initSafe
, tailMay
, tailDef
, tailSafe
, lastDef
, lastMay
, foldr1May
, foldl1May
, foldl1May'
, maximumMay
, minimumMay
, maximumDef
, minimumDef
, atMay
, atDef
)
-- Applicatives
import Control.Applicative as Applicative (
Applicative(..)
, Alternative(..)
, Const(Const,getConst)
, ZipList(ZipList,getZipList)
, (<**>)
, liftA
, liftA2
, liftA3
, optional
)
-- Base typeclasses
import Data.Eq as Eq (
Eq(..)
)
import Data.Ord as Ord (
Ord(..)
, Ordering(LT,EQ,GT)
, Down(Down)
, comparing
)
import Data.Traversable as Traversable
import Data.Foldable as Foldable (
Foldable,
fold,
foldMap,
foldr,
foldr',
foldl,
foldl',
toList,
#if MIN_VERSION_base(4,8,0)
null,
length,
#endif
elem,
maximum,
minimum,
foldrM,
foldlM,
traverse_,
for_,
mapM_,
forM_,
sequence_,
sequenceA_,
asum,
msum,
concat,
concatMap,
and,
or,
any,
all,
maximumBy,
minimumBy,
notElem,
find,
)
import Data.Functor.Identity as Functor (
Identity(Identity, runIdentity)
)
#if MIN_VERSION_base(4,9,0)
import Data.List.NonEmpty as List (
NonEmpty((:|))
, nonEmpty
)
import Data.Semigroup as Semigroup (
Semigroup(sconcat, stimes)
, WrappedMonoid
, Option(..)
, option
, diff
, cycle1
, stimesMonoid
, stimesIdempotent
, stimesIdempotentMonoid
, mtimesDefault
)
#endif
import Data.Monoid as Monoid
#if !MIN_VERSION_base(4,8,0)
import Protolude.Bifunctor as Bifunctor (Bifunctor(bimap, first, second))
#else
import Data.Bifunctor as Bifunctor (Bifunctor(bimap, first, second))
#endif
-- Deepseq
import Control.DeepSeq as DeepSeq (
NFData(..)
, ($!!)
, deepseq
, force
)
-- Data structures
import Data.Tuple as Tuple (
fst
, snd
, curry
, uncurry
, swap
)
import Data.List as List (
splitAt
, break
, intercalate
, isPrefixOf
, drop
, filter
, reverse
, replicate
, take
, sortBy
, sort
, intersperse
, transpose
, subsequences
, permutations
, scanl
#if MIN_VERSION_base(4,8,0)
, scanl'
#endif
, scanr
, iterate
, repeat
, cycle
, unfoldr
, takeWhile
, dropWhile
, group
, inits
, tails
, zipWith
, zip
, unzip
, genericLength
, genericTake
, genericDrop
, genericSplitAt
, genericReplicate
)
#if !MIN_VERSION_base(4,8,0)
-- These imports are required for the scanl' rewrite rules
import GHC.Exts (build)
import Data.List (tail)
#endif
-- Hashing
import Data.Hashable as Hashable (
Hashable
, hash
, hashWithSalt
, hashUsing
)
import Data.Map as DataStructures (Map)
import Data.Set as DataStructures (Set)
import Data.Sequence as DataStructures (Seq)
import Data.IntMap as DataStructures (IntMap)
import Data.IntSet as DataStructures (IntSet)
import Data.Typeable as Typeable (
TypeRep
, Typeable
, typeOf
, cast
, gcast
#if MIN_VERSION_base(4,7,0)
, typeRep
, eqT
#endif
)
#if MIN_VERSION_base(4,7,0)
import Data.Proxy as Typelevel (
Proxy(..)
)
import Data.Type.Coercion as Typelevel (
Coercion(..)
, coerceWith
, repr
)
import Data.Type.Equality as Typelevel (
(:~:)(..)
, type (==)
, sym
, trans
, castWith
, gcastWith
)
#endif
#if MIN_VERSION_base(4,8,0)
import Data.Void as Typelevel (
Void
, absurd
, vacuous
)
#endif
import Control.Monad.Fail as Fail (
MonadFail
)
-- Monad transformers
import Control.Monad.State as State (
MonadState
, State
, StateT(StateT)
, put
, get
, gets
, modify
, state
, withState
, runState
, execState
, evalState
, runStateT
, execStateT
, evalStateT
)
import Control.Monad.Reader as Reader (
MonadReader
, Reader
, ReaderT(ReaderT)
, ask
, asks
, local
, reader
, runReader
, runReaderT
)
import Control.Monad.Trans.Except as Except (
throwE
, catchE
)
import Control.Monad.Except as Except (
MonadError
, Except
, ExceptT(ExceptT)
, throwError
, catchError
, runExcept
, runExceptT
, mapExcept
, mapExceptT
, withExcept
, withExceptT
)
import Control.Monad.Trans as Trans (
MonadIO
, lift
, liftIO
)
-- Base types
import Data.Int as Int (
Int
, Int8
, Int16
, Int32
, Int64
)
import Data.Bits as Bits (
Bits,
(.&.),
(.|.),
xor,
complement,
shift,
rotate,
#if MIN_VERSION_base(4,7,0)
zeroBits,
#endif
bit,
setBit,
clearBit,
complementBit,
testBit,
#if MIN_VERSION_base(4,7,0)
bitSizeMaybe,
#endif
bitSize,
isSigned,
shiftL,
shiftR,
rotateL,
rotateR,
popCount,
#if MIN_VERSION_base(4,7,0)
FiniteBits,
finiteBitSize,
bitDefault,
testBitDefault,
popCountDefault,
#endif
#if MIN_VERSION_base(4,8,0)
toIntegralSized,
countLeadingZeros,
countTrailingZeros,
#endif
)
import Data.Word as Bits (
Word
, Word8
, Word16
, Word32
, Word64
#if MIN_VERSION_base(4,7,0)
, byteSwap16
, byteSwap32
, byteSwap64
#endif
)
import Data.Either as Either (
Either(Left,Right)
, either
, lefts
, rights
, partitionEithers
#if MIN_VERSION_base(4,7,0)
, isLeft
, isRight
#endif
)
import Data.Complex as Complex (
Complex((:+))
, realPart
, imagPart
, mkPolar
, cis
, polar
, magnitude
, phase
, conjugate
)
import Data.Char as Char (
Char
, ord
, chr
, digitToInt
, intToDigit
, toUpper
, toLower
, toTitle
, isAscii
, isLetter
, isDigit
, isHexDigit
, isPrint
, isAlpha
, isAlphaNum
, isUpper
, isLower
, isSpace
, isControl
)
import Data.Bool as Bool (
Bool(True, False),
(&&),
(||),
not,
otherwise
)
import Data.Maybe as Maybe (
Maybe(Nothing, Just)
, maybe
, isJust
, isNothing
, fromMaybe
, listToMaybe
, maybeToList
, catMaybes
, mapMaybe
)
import Data.Function as Function (
const
, (.)
, ($)
, flip
, fix
, on
#if MIN_VERSION_base(4,8,0)
, (&)
#endif
)
-- Genericss
import GHC.Generics as Generics (
Generic(..)
, Generic1
, Rep
, K1(..)
, M1(..)
, U1(..)
, V1
, D1
, C1
, S1
, (:+:)(..)
, (:*:)(..)
, (:.:)(..)
, Rec0
, Constructor(..)
, Datatype(..)
, Selector(..)
, Fixity(..)
, Associativity(..)
#if ( __GLASGOW_HASKELL__ >= 800 )
, Meta(..)
, FixityI(..)
, URec
#endif
)
-- ByteString
import qualified Data.ByteString.Lazy
import Data.ByteString as ByteString (ByteString)
-- Text
import Data.Text as Text (
Text
, lines
, words
, unlines
, unwords
)
import qualified Data.Text.Lazy
import Data.Text.IO as Text (
getLine
, getContents
, interact
, readFile
, writeFile
, appendFile
)
import Data.Text.Lazy as Text (
toStrict
, fromStrict
)
import Data.Text.Encoding as Text (
encodeUtf8
, decodeUtf8
, decodeUtf8'
, decodeUtf8With
)
import Data.Text.Encoding.Error as Text (
OnDecodeError
, OnError
, UnicodeException
, lenientDecode
, strictDecode
, ignore
, replace
)
-- IO
import System.Environment as System (getArgs)
import qualified System.Exit
import System.Exit as System (
ExitCode(..)
, exitWith
, exitFailure
, exitSuccess
)
import System.IO as System (
Handle
, FilePath
, IOMode(..)
, stdin
, stdout
, stderr
, withFile
, openFile
)
-- ST
import Control.Monad.ST as ST (
ST
, runST
, fixST
)
-- Concurrency and Parallelism
import Control.Exception as Exception (
Exception,
toException,
fromException,
#if MIN_VERSION_base(4,8,0)
displayException,
#endif
SomeException(SomeException)
, IOException
, ArithException(
Overflow,
Underflow,
LossOfPrecision,
DivideByZero,
Denormal,
RatioZeroDenominator
)
, ArrayException(IndexOutOfBounds, UndefinedElement)
, AssertionFailed(AssertionFailed)
#if MIN_VERSION_base(4,7,0)
, SomeAsyncException(SomeAsyncException)
, asyncExceptionToException
, asyncExceptionFromException
#endif
, AsyncException(StackOverflow, HeapOverflow, ThreadKilled, UserInterrupt)
, NonTermination(NonTermination)
, NestedAtomically(NestedAtomically)
, BlockedIndefinitelyOnMVar(BlockedIndefinitelyOnMVar)
, BlockedIndefinitelyOnSTM(BlockedIndefinitelyOnSTM)
#if MIN_VERSION_base(4,8,0)
, AllocationLimitExceeded(AllocationLimitExceeded)
#endif
#if MIN_VERSION_base(4,10,0)
, CompactionFailed(CompactionFailed)
#endif
, Deadlock(Deadlock)
, NoMethodError(NoMethodError)
, PatternMatchFail(PatternMatchFail)
, RecConError(RecConError)
, RecSelError(RecSelError)
, RecUpdError(RecUpdError)
#if MIN_VERSION_base(4,9,0)
, ErrorCall(ErrorCall, ErrorCallWithLocation)
#else
, ErrorCall(ErrorCall)
#endif
#if MIN_VERSION_base(4,9,0)
, TypeError(TypeError)
#endif
, ioError
, catch
, catches
, Handler(Handler)
, catchJust
, handle
, handleJust
, try
, tryJust
, evaluate
, mapException
, mask
, mask_
, uninterruptibleMask
, uninterruptibleMask_
, MaskingState(..)
, getMaskingState
#if MIN_VERSION_base(4,9,0)
, interruptible
#endif
, allowInterrupt
, bracket
, bracket_
, bracketOnError
, finally
, onException
)
import qualified Control.Exception as PException
import Control.Monad.STM as STM (
STM
, atomically
#if !(MIN_VERSION_stm(2,5,0))
, always
, alwaysSucceeds
#endif
, retry
, orElse
, check
, throwSTM
, catchSTM
)
import Control.Concurrent.MVar as Concurrency (
MVar
, newEmptyMVar
, newMVar
, takeMVar
, putMVar
, readMVar
, swapMVar
, tryTakeMVar
, tryPutMVar
, isEmptyMVar
, withMVar
#if MIN_VERSION_base(4,7,0)
, withMVarMasked
#endif
, modifyMVar_
, modifyMVar
, modifyMVarMasked_
, modifyMVarMasked
#if MIN_VERSION_base(4,7,0)
, tryReadMVar
, mkWeakMVar
#endif
, addMVarFinalizer
)
import Control.Concurrent.Chan as Concurrency (
Chan
, newChan
, writeChan
, readChan
, dupChan
, getChanContents
, writeList2Chan
)
import Control.Concurrent.QSem as Concurrency (
QSem
, newQSem
, waitQSem
, signalQSem
)
import Control.Concurrent.QSemN as Concurrency (
QSemN
, newQSemN
, waitQSemN
, signalQSemN
)
import Control.Concurrent as Concurrency (
ThreadId
, forkIO
, forkFinally
, forkIOWithUnmask
, killThread
, forkOn
, forkOnWithUnmask
, getNumCapabilities
, setNumCapabilities
, threadCapability
, yield
, threadDelay
, threadWaitRead
, threadWaitWrite
#if MIN_VERSION_base(4,7,0)
, threadWaitReadSTM
, threadWaitWriteSTM
#endif
, rtsSupportsBoundThreads
, forkOS
#if MIN_VERSION_base(4,9,0)
, forkOSWithUnmask
#endif
, isCurrentThreadBound
, runInBoundThread
, runInUnboundThread
, mkWeakThreadId
, myThreadId
)
import Control.Concurrent.Async as Concurrency (
Async(..)
, Concurrently(..)
, async
, asyncBound
, asyncOn
, withAsync
, withAsyncBound
, withAsyncOn
, wait
, poll
, waitCatch
, cancel
, cancelWith
, asyncThreadId
, waitAny
, waitAnyCatch
, waitAnyCancel
, waitAnyCatchCancel
, waitEither
, waitEitherCatch
, waitEitherCancel
, waitEitherCatchCancel
, waitEither_
, waitBoth
, link
, link2
, race
, race_
, concurrently
)
import Foreign.Ptr as Foreign (IntPtr, WordPtr)
import Foreign.Storable as Foreign (Storable)
import Foreign.StablePtr as Foreign (StablePtr)
-- Read instances hiding unsafe builtins (read)
import qualified Text.Read as Read
import Text.Read as Read (
Read
, reads
)
-- Type synonymss for lazy texts
type LText = Data.Text.Lazy.Text
type LByteString = Data.ByteString.Lazy.ByteString
#if !MIN_VERSION_base(4,8,0)
infixl 1 &
(&) :: a -> (a -> b) -> b
x & f = f x
#endif
-- | The identity function, returns the give value unchanged.
identity :: a -> a
identity x = x
map :: Functor.Functor f => (a -> b) -> f a -> f b
map = Functor.fmap
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x:xs) = Just (x, xs)
unsnoc :: [x] -> Maybe ([x],x)
unsnoc = Foldable.foldr go Nothing
where
go x mxs = Just (case mxs of
Nothing -> ([], x)
Just (xs, e) -> (x:xs, e))
-- | Apply a function n times to a given value
applyN :: Int -> (a -> a) -> a -> a
applyN n f = Foldable.foldr (.) identity (List.replicate n f)
-- | Parse a string using the 'Read' instance.
-- Succeeds if there is exactly one valid result.
--
-- >>> readMaybe ("123" :: Text) :: Maybe Int
-- Just 123
--
-- >>> readMaybe ("hello" :: Text) :: Maybe Int
-- Nothing
readMaybe :: (Read b, Conv.StringConv a String) => a -> Maybe b
readMaybe = Read.readMaybe . Conv.toS
-- | Parse a string using the 'Read' instance.
-- Succeeds if there is exactly one valid result.
-- A 'Left' value indicates a parse error.
--
-- >>> readEither "123" :: Either Text Int
-- Right 123
--
-- >>> readEither "hello" :: Either Text Int
-- Left "Prelude.read: no parse"
readEither :: (Read a, Conv.StringConv String e, Conv.StringConv e String) => e -> Either e a
readEither = first Conv.toS . Read.readEither . Conv.toS
-- | The print function outputs a value of any printable type to the standard
-- output device. Printable types are those that are instances of class Show;
-- print converts values to strings for output using the show operation and adds
-- a newline.
print :: (Trans.MonadIO m, PBase.Show a) => a -> m ()
print = liftIO . PBase.print
-- | Lifted throwIO
throwIO :: (Trans.MonadIO m, Exception e) => e -> m a
throwIO = liftIO . PException.throwIO
-- | Lifted throwTo
throwTo :: (Trans.MonadIO m, Exception e) => ThreadId -> e -> m ()
throwTo tid e = liftIO (PException.throwTo tid e)
-- | Do nothing returning unit inside applicative.
pass :: Applicative f => f ()
pass = pure ()
guarded :: (Alternative f) => (a -> Bool) -> a -> f a
guarded p x = Bool.bool empty (pure x) (p x)
guardedA :: (Functor.Functor f, Alternative t) => (a -> f Bool) -> a -> f (t a)
guardedA p x = Bool.bool empty (pure x) `Functor.fmap` p x
-- | Lift an 'IO' operation with 1 argument into another monad
liftIO1 :: MonadIO m => (a -> IO b) -> a -> m b
liftIO1 = (.) liftIO
-- | Lift an 'IO' operation with 2 arguments into another monad
liftIO2 :: MonadIO m => (a -> b -> IO c) -> a -> b -> m c
liftIO2 = ((.).(.)) liftIO
show :: (Show a, Conv.StringConv String b) => a -> b
show x = Conv.toS (PBase.show x)
{-# SPECIALIZE show :: Show a => a -> Text #-}
{-# SPECIALIZE show :: Show a => a -> LText #-}
{-# SPECIALIZE show :: Show a => a -> String #-}
#if MIN_VERSION_base(4,8,0)
-- | Terminate main process with failure
die :: Text -> IO a
die err = System.Exit.die (ConvertText.toS err)
#else
-- | Terminate main process with failure
die :: Text -> IO a
die err = hPutStrLn stderr err >> exitFailure
#endif
#if !MIN_VERSION_base(4,8,0)
-- This is a literal copy of the implementation in GHC.List in base-4.10.1.0.
-- | A strictly accumulating version of 'scanl'
{-# NOINLINE [1] scanl' #-}
scanl' :: (b -> a -> b) -> b -> [a] -> [b]
scanl' = scanlGo'
where
scanlGo' :: (b -> a -> b) -> b -> [a] -> [b]
scanlGo' f !q ls = q : (case ls of
[] -> []
x:xs -> scanlGo' f (f q x) xs)
{-# RULES
"scanl'" [~1] forall f a bs . scanl' f a bs =
build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a)
"scanlList'" [1] forall f a bs .
foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs)
#-}
{-# INLINE [0] scanlFB' #-}
scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c
scanlFB' f c = \b g -> \x -> let !b' = f x b in b' `c` g b'
{-# INLINE [0] flipSeqScanl' #-}
flipSeqScanl' :: a -> b -> a
flipSeqScanl' a !_b = a
#endif
| sdiehl/protolude | src/Protolude.hs | mit | 19,454 | 1 | 14 | 4,526 | 4,312 | 2,840 | 1,472 | 668 | 2 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{- |
Module : Data.Fix1
Description : Fixed point for types of kind (k -> *) -> k -> *
Copyright : (c) Paweł Nowak
License : MIT
Maintainer : [email protected]
Stability : experimental
-}
module Data.Fix1 where
import Prelude.Compat
-- | This is similar to an "endofunctor on the category of endofunctors", but
-- the forall is lifted outside.
--
-- I speculate that this hmap is implementable for exactly the same types as
-- a hmap of type @(f ~> g) -> (h f ~> h g)@, yet allows more uses.
class HFunctor (h :: (k -> *) -> (k -> *)) where
hmap :: (f a -> g a) -> (h f a -> h g a)
-- | Types such that @g f@ is a functor given that @f@ is a functor.
class Functor1 (g :: (* -> *) -> (* -> *)) where
map1 :: Functor f => (a -> b) -> (g f a -> g f b)
-- | Types such that @g f@ is foldable given that @f@ is foldable.
class Foldable1 (g :: (* -> *) -> (* -> *)) where
foldMap1 :: (Foldable f, Monoid m) => (a -> m) -> (g f a -> m)
-- | Types such that @h f@ is traversable given that @f@ is traversable.
class (Functor1 h, Foldable1 h) => Traversable1 (h :: (* -> *) -> (* -> *)) where
traverse1 :: (Traversable f, Applicative g) => (a -> g b) -> (h f a -> g (h f b))
-- | Fixed point of a type with kind (k -> *) -> k -> *
data Fix1 (f :: (k -> *) -> k -> *) (a :: k) = Fix1 { unFix1 :: f (Fix1 f) a }
instance Functor1 f => Functor (Fix1 f) where
fmap f = Fix1 . map1 f . unFix1
instance Foldable1 f => Foldable (Fix1 f) where
foldMap f = foldMap1 f . unFix1
instance Traversable1 f => Traversable (Fix1 f) where
traverse f (Fix1 a) = Fix1 <$> traverse1 f a
cata1 :: HFunctor f => (f g a -> g a) -> Fix1 f a -> g a
cata1 f = f . hmap (cata1 f) . unFix1
ana1 :: HFunctor f => (g a -> f g a) -> g a -> Fix1 f a
ana1 f = Fix1 . hmap (ana1 f) . f
hylo1 :: HFunctor f => (f g a -> g a) -> (h a -> f h a) -> (h a -> g a)
hylo1 phi psi = cata1 phi . ana1 psi
infixr 9 .:
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.:) = (.) . (.)
infixr 9 .::
(.::) :: (d -> e) -> (a -> b -> c -> d) -> a -> b -> c -> e
(.::) = (.:) . (.)
| pawel-n/data-fix1 | src/Data/Fix1.hs | mit | 2,175 | 0 | 13 | 565 | 876 | 462 | 414 | 32 | 1 |
module Alarm where
import Control.Probability
bool :: (Probability p, MonadProb p m) => p -> m p Bool
bool p = choose p True False
filterDist :: (Ord a, MonadProb p m) => (a -> Bool) -> m p a -> m p a
filterDist f m = do x <- m
condition (f x)
returning x
(>>=?) :: (Ord a, MonadProb p m) => m p a -> (a -> Bool) -> m p a
(>>=?) = flip filterDist
(?=<<) :: (Ord a, MonadProb p m) => (a -> Bool) -> m p a -> m p a
(?=<<) = filterDist
-- | prior burglary is 1%
b :: Dist Bool
b = bool 0.01
-- | prior earthqauke is 0.1%
e :: Dist Bool
e = bool 0.001
-- | conditional prob of alarm | burglary, earthquake
a :: Bool -> Bool -> Dist Bool
a b0 e0 =
case (b0,e0) of
(False,False) -> bool 0.01
(False,True) -> bool 0.1
(True,False) -> bool 0.7
(True,True) -> bool 0.9
-- | conditional prob of john calling | alarm
j :: Bool -> Dist Bool
j a = if a then bool 0.8 else bool 0.05
-- | conditional prob of mary calling | alarm
m :: Bool -> Dist Bool
m a = if a then bool 0.9 else bool 0.1
-- | full joint distribution
data Burglary = B
{ burglary :: Bool
, earthquake :: Bool
, alarm :: Bool
, john :: Bool
, mary :: Bool }
deriving (Eq,Ord,Show)
joint :: Dist Burglary
joint = do
b' <- b
e' <- e
a' <- a b' e'
j' <- j a'
m' <- m a'
returning $ B b' e' a' j' m'
-- | probability that mary calls given john calls
mj = mary ?? john ?=<< joint
-- | probability of burglary given mary calls
bm = burglary ?? mary ?=<< joint
-- | probability of burglary given john calls
bj = burglary ?? john ?=<< joint | chris-taylor/hs-probability-examples | Alarm.hs | mit | 1,651 | 0 | 9 | 498 | 627 | 329 | 298 | 45 | 4 |
module Moonbase.Desktop.Gtk.Background
( justImage
, BackgroundImage (..)
) where
import Control.Applicative
import Control.Monad.Except
import Control.Monad.State
import System.Glib.GError
import Data.Maybe
import Graphics.UI.Gtk hiding ( get )
import Graphics.Rendering.Cairo
import Moonbase.Core
import Moonbase.Log
import Moonbase.Hook.Gtk
data BackgroundImage = BackgroundImage
{ biMonitor :: Int
, biScreen :: Maybe Int
, biImage :: FilePath }
instance Component BackgroundImage where
start = backgroundStart
stop = backgroundStop
isRunning = return True
backgroundStart :: ComponentM BackgroundImage Bool
backgroundStart = do
conf <- get
disp <- checkDisplay =<< io displayGetDefault
scr <- getScreen disp (biScreen conf)
geo@(Rectangle x y w h) <- io $ screenGetMonitorGeometry scr (biMonitor conf) -- Add monitor check
win <- io windowNew
io $ windowSetScreen win scr
io $ setupDesktop win w h
image <- loadImage (biImage conf) geo
imageWidget <- io $ imageNewFromPixbuf image
-- setup basic cursor
cursor <- io $ cursorNewForDisplay disp Arrow
setupCursor cursor
io $ containerAdd win imageWidget
io $ widgetQueueDraw win
io $ widgetShowAll win
return True
where
checkDisplay (Just disp) = return disp
checkDisplay _ = throwError (InitFailed "BackgroundImage: Could not open display")
setupDesktop :: Window -> Int -> Int -> IO ()
setupDesktop win w h = do
widgetSetName win "desktop"
windowSetTypeHint win WindowTypeHintDesktop
windowSetGravity win GravityStatic
widgetSetCanFocus win False
windowSetDefaultSize win w h
widgetSetSizeRequest win w h
windowResize win w h
windowMove win 0 0
windowSetGeometryHints win noWidget (Just (w,h)) (Just (w,h)) Nothing Nothing Nothing
where
noWidget = Nothing :: Maybe Widget
getScreen :: Display -> Maybe Int -> ComponentM BackgroundImage Screen
getScreen disp Nothing = io $ displayGetDefaultScreen disp
getScreen disp (Just i) = do
sNum <- io $ displayGetNScreens disp
when (i > sNum || i < 0) $ throwError (InitFailed "BackgroundImage: Invalid screen number")
io $ displayGetScreen disp i
loadImage :: FilePath -> Rectangle -> ComponentM BackgroundImage Pixbuf
loadImage path (Rectangle x y w h) = io $ catchGErrorJustDomain (load path) (blackPixbuf w h)
where
load img = pixbufNewFromFileAtScale img w h False
blackPixbuf :: Int -> Int -> PixbufError -> GErrorMessage -> IO Pixbuf
blackPixbuf w h _ _= do
pixbuf <- pixbufNew ColorspaceRgb False 8 w h
pixbufFill pixbuf 0 0 0 255
return pixbuf
drawImage :: DrawWindow -> Rectangle -> Pixbuf -> IO ()
drawImage area geo@(Rectangle x y w h) image = do
drawWindowBeginPaintRect area geo
renderWithDrawWindow area $ setSourcePixbuf image (fromIntegral x) (fromIntegral y) >> paint >> fill
drawWindowEndPaint area
backgroundStop :: ComponentM BackgroundImage ()
backgroundStop = return () -- implement me!
justImage :: FilePath -> Int -> Maybe Int -> Desktop
justImage path monitor mScreen = Desktop "background-image" [gtkInit, gtkMain, gtkQuit] $ BackgroundImage monitor mScreen path
| felixsch/moonbase-gtk | src/Moonbase/Desktop/Gtk/Background.hs | gpl-2.0 | 3,335 | 0 | 12 | 779 | 1,008 | 491 | 517 | 75 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module XMonad.Hooks.DynamicLog.Status.Bars where
import XMonad
import XMonad.Layout.LayoutModifier
import XMonad.Util.Run
import qualified XMonad.Hooks.DynamicLog.Status.StatusText as ST
import XMonad.Hooks.ManageDocks
import qualified XMonad.Hooks.DynamicLog.Status.DZen2.Universal as U
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.Map as M
import qualified Data.List as L
import qualified System.IO as IO
import Data.Monoid
-- | A bunch of StatusTexts that belong together in the same area of
-- the StatusBar.
newtype StatusBarSection = StatusBarSection [ST.StatusText]
-- | Left, center, and right sections of the StatusBar respectively.
newtype StatusBar = StatusBar (StatusBarSection, StatusBarSection, StatusBarSection)
makeStatusBarSection :: [ST.StatusText] -> StatusBarSection
makeStatusBarSection sbs = StatusBarSection sbs
makeStatusBar :: StatusBarSection -> StatusBarSection -> StatusBarSection -> StatusBar
makeStatusBar l c r = StatusBar (l, c, r)
-- | Return the logical length of the StatusBarSection, without the
-- control characters.
length :: StatusBarSection -> Int
length (StatusBarSection xs) = sum $ fmap ST.length $ xs
-- | Return the number of different StatusTexts inside the
-- StatusBarSection.
numberOfTexts :: StatusBarSection -> Int
numberOfTexts (StatusBarSection xs) = L.length xs
-- | Return the number of non-empty StatusTexts inside.
numberOfNonemptyTexts :: StatusBarSection -> Int
numberOfNonemptyTexts (StatusBarSection xs) = L.length $ filter ST.isEmpty xs
-- | Return the left section of the StatusBar.
left :: StatusBar -> StatusBarSection
left (StatusBar (l,c,r)) = l
-- | Return the center section of the StatusBar.
center :: StatusBar -> StatusBarSection
center (StatusBar (l,c,r)) = c
-- | Return the right section of the StatusBar.
right :: StatusBar -> StatusBarSection
right (StatusBar (l,c,r)) = r
-- | Return the rendered StatusBarSection with StatusTexts separated by the
-- String sep.
simpleRenderStatusBarSection :: StatusBarSection -> String -> String
simpleRenderStatusBarSection (StatusBarSection sbs) sep = mconcat $ fmap ST.render $ L.intersperse (ST.simpleStatusText sep) sbs
-- | TODO: Fix the placement of the text.
simpleRenderBar :: StatusBar -> String -> String
simpleRenderBar sb sep =
let l = left sb
c = center sb
r = right sb
leftAlignedL = ST.render $ const (simpleRenderStatusBarSection l sep) <$> U.p U.LEFT U.HERE
centerAlignedC = ST.render $ const (simpleRenderStatusBarSection c sep) <$> U.p U.CENTER U.HERE
rightAlignedR = ST.render $ const (simpleRenderStatusBarSection r sep) <$> U.p U.RIGHT U.HERE
in
leftAlignedL <> centerAlignedC <> rightAlignedR
defaultRenderBar :: StatusBar -> String
defaultRenderBar bar = simpleRenderBar bar sep
where
sep = " | "
hPrintStatusBar :: IO.Handle -> StatusBar -> (StatusBar -> String) -> X ()
hPrintStatusBar h bar renderF = liftIO $ hPutStrLn h $ renderF bar
statusBar :: LayoutClass l Window
=> String -- ^ The command line to launch the status bar.
-> X StatusBar -- ^ The StatusTexts to print
-> X (StatusBar -> String)
-> (XConfig Layout -> (KeyMask, KeySym))
-- ^ The desired key binding to toggle bar visibility.
-> XConfig l -- ^ The base config.
-> IO (XConfig (ModifiedLayout AvoidStruts l))
statusBar cmd bar renderF k conf = do
h <- spawnPipe cmd
return $ conf
{ layoutHook = avoidStruts $ layoutHook conf
, logHook = do
logHook conf
theBar <- bar
theRenderer <- renderF
hPrintStatusBar h theBar theRenderer
, manageHook = manageHook conf <+> manageDocks
, keys = liftM2 M.union keys' (keys conf)
}
where
keys' = (`M.singleton` sendMessage ToggleStruts) . k
defaultStatusBar :: LayoutClass l Window
=> String
-> X StatusBar
-> (XConfig Layout -> (KeyMask, KeySym))
-> XConfig l
-> IO (XConfig (ModifiedLayout AvoidStruts l))
defaultStatusBar cmd bar k conf = statusBar cmd bar (return defaultRenderBar) k conf
| Fizzixnerd/xmonad-config | site-haskell/src/XMonad/Hooks/DynamicLog/Status/Bars.hs | gpl-3.0 | 4,246 | 0 | 15 | 901 | 1,043 | 561 | 482 | 74 | 1 |
module Link
( link
) where
import System.Process (runProcess, waitForProcess)
link :: [String] -> String -> IO ()
link objects output = do
_ <- waitForProcess =<< runProcess "gcc" (objects ++ ["-o", output]) Nothing Nothing Nothing Nothing Nothing
return ()
| UndeadMastodon/HsBFC | Link.hs | gpl-3.0 | 268 | 0 | 12 | 50 | 100 | 53 | 47 | 7 | 1 |
{-
oso2pdf --- Better conversion of Oxford Scholarship Online material to PDF
Copyright (C) 2015 Sean Whitton
This file is part of oso2pdf.
oso2pdf is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
oso2pdf is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with oso2pdf. If not, see <http://www.gnu.org/licenses/>.
-}
import Data.List (isPrefixOf, isSuffixOf)
import Data.Monoid ((<>))
import Text.Pandoc.JSON
data Page = Page Int [Block]
instance Monoid Page where
mempty = Page 1 []
(Page n xs) `mappend` (Page _ ys) = Page n (xs ++ ys)
pagesToBlocks :: [Page] -> [Block]
pagesToBlocks [Page _ xs] = xs
pagesToBlocks ps@( _ : (Page n _) : _) =
RawBlock (Format "tex") ("\\setcounter{page}{" ++ show (n - 1) ++ "}")
: (drop 1 $ foldr step [] ps) -- drop first \\pagebreak
where
step (Page n p) ps = RawBlock (Format "tex") "\\pagebreak" : p ++ ps
-- TODO factor out joining Pages together and appending or just
-- putting side by side
blocksToPages :: [Block] -> [Page]
blocksToPages = foldr step []
where
step (Para xs) [] = paraToPages xs
step x [] = [Page 1 [x]]
step (Para xs) ( y@(Page n _) : ys ) =
case paraToPages xs of
[a, b] -> if n /= 1 then a : b : y : ys else a : (b <> y) : ys
[a] -> if n /= 1 then a : y : ys else (a <> y) : ys
step x (y:ys) = ((Page 1 [x]) <> y) : ys
-- ASSUME: not more than one page break per paragraph!
paraToPages :: [Inline] -> [Page]
paraToPages para = let (first, n, second) = foldr step ([], 1, []) para
in if n == 1
then [Page 1 [Para second]]
else if null first
then [Page 1 [Para first], Page n [Para second]]
else [ Page 1 [Para first]
, Page n [Para (RawInline (Format "tex") "\\noindent"
: second)]]
where
step chunk (xs, n, ys) =
if n /= 1
then (chunk : xs, n, ys)
else case chunk of
(Str x) -> if "(p." `isPrefixOf` x && ")" `isSuffixOf` x
then let m = read . drop 3 . init $ x
in (xs, m, ys) -- TODO: what about [Space, Space] left behind?
else (xs, n, chunk : ys)
_ -> (xs, n, chunk : ys)
main = toJSONFilter process
where
process (Pandoc meta blocks) = Pandoc meta (pagesToBlocks . blocksToPages $ blocks)
| spwhitton/oso2pdf | src/pandoc-oso2tex.hs | gpl-3.0 | 3,033 | 2 | 17 | 1,034 | 887 | 474 | 413 | 42 | 7 |
module Main( main ) where
import System (getArgs)
import System.IO
import Control.Monad (forM_,liftM)
import Geda.Parser (readGSchem)
tryParse :: String -> String -> IO ()
tryParse fn x = case readGSchem x of
Left err -> hPutStrLn stderr $ fn ++ " FAILED!\nReason: " ++ show err
Right _ -> putStrLn $ fn ++ " PASSED!"
main :: IO ()
main = do
args <- getArgs
forM_ args printFile
where
printFile fn = do
handel <- openFile fn ReadMode
contents <- hGetContents handel
tryParse fn contents
hClose handel
| xcthulhu/lambda-geda | parse-test.hs | gpl-3.0 | 546 | 0 | 11 | 132 | 200 | 98 | 102 | 18 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdSense.Savedadstyles.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Get a specific saved ad style from the user\'s account.
--
-- /See:/ <https://developers.google.com/adsense/management/ AdSense Management API Reference> for @adsense.savedadstyles.get@.
module Network.Google.Resource.AdSense.Savedadstyles.Get
(
-- * REST Resource
SavedadstylesGetResource
-- * Creating a Request
, savedadstylesGet
, SavedadstylesGet
-- * Request Lenses
, sgSavedAdStyleId
) where
import Network.Google.AdSense.Types
import Network.Google.Prelude
-- | A resource alias for @adsense.savedadstyles.get@ method which the
-- 'SavedadstylesGet' request conforms to.
type SavedadstylesGetResource =
"adsense" :>
"v1.4" :>
"savedadstyles" :>
Capture "savedAdStyleId" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] SavedAdStyle
-- | Get a specific saved ad style from the user\'s account.
--
-- /See:/ 'savedadstylesGet' smart constructor.
newtype SavedadstylesGet = SavedadstylesGet'
{ _sgSavedAdStyleId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SavedadstylesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sgSavedAdStyleId'
savedadstylesGet
:: Text -- ^ 'sgSavedAdStyleId'
-> SavedadstylesGet
savedadstylesGet pSgSavedAdStyleId_ =
SavedadstylesGet'
{ _sgSavedAdStyleId = pSgSavedAdStyleId_
}
-- | Saved ad style to retrieve.
sgSavedAdStyleId :: Lens' SavedadstylesGet Text
sgSavedAdStyleId
= lens _sgSavedAdStyleId
(\ s a -> s{_sgSavedAdStyleId = a})
instance GoogleRequest SavedadstylesGet where
type Rs SavedadstylesGet = SavedAdStyle
type Scopes SavedadstylesGet =
'["https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"]
requestClient SavedadstylesGet'{..}
= go _sgSavedAdStyleId (Just AltJSON) adSenseService
where go
= buildClient
(Proxy :: Proxy SavedadstylesGetResource)
mempty
| rueshyna/gogol | gogol-adsense/gen/Network/Google/Resource/AdSense/Savedadstyles/Get.hs | mpl-2.0 | 2,919 | 0 | 12 | 642 | 302 | 186 | 116 | 50 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ElasticTranscoder.ListPipelines
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | The ListPipelines operation gets a list of the pipelines associated with the
-- current AWS account.
--
-- <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/ListPipelines.html>
module Network.AWS.ElasticTranscoder.ListPipelines
(
-- * Request
ListPipelines
-- ** Request constructor
, listPipelines
-- ** Request lenses
, lpAscending
, lpPageToken
-- * Response
, ListPipelinesResponse
-- ** Response constructor
, listPipelinesResponse
-- ** Response lenses
, lprNextPageToken
, lprPipelines
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.ElasticTranscoder.Types
import qualified GHC.Exts
data ListPipelines = ListPipelines
{ _lpAscending :: Maybe Text
, _lpPageToken :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListPipelines' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lpAscending' @::@ 'Maybe' 'Text'
--
-- * 'lpPageToken' @::@ 'Maybe' 'Text'
--
listPipelines :: ListPipelines
listPipelines = ListPipelines
{ _lpAscending = Nothing
, _lpPageToken = Nothing
}
-- | To list pipelines in chronological order by the date and time that they were
-- created, enter 'true'. To list pipelines in reverse chronological order, enter 'false'.
lpAscending :: Lens' ListPipelines (Maybe Text)
lpAscending = lens _lpAscending (\s a -> s { _lpAscending = a })
-- | When Elastic Transcoder returns more than one page of results, use 'pageToken'
-- in subsequent 'GET' requests to get each successive page of results.
lpPageToken :: Lens' ListPipelines (Maybe Text)
lpPageToken = lens _lpPageToken (\s a -> s { _lpPageToken = a })
data ListPipelinesResponse = ListPipelinesResponse
{ _lprNextPageToken :: Maybe Text
, _lprPipelines :: List "Pipelines" Pipeline
} deriving (Eq, Read, Show)
-- | 'ListPipelinesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lprNextPageToken' @::@ 'Maybe' 'Text'
--
-- * 'lprPipelines' @::@ ['Pipeline']
--
listPipelinesResponse :: ListPipelinesResponse
listPipelinesResponse = ListPipelinesResponse
{ _lprPipelines = mempty
, _lprNextPageToken = Nothing
}
-- | A value that you use to access the second and subsequent pages of results, if
-- any. When the pipelines fit on one page or when you've reached the last page
-- of results, the value of 'NextPageToken' is 'null'.
lprNextPageToken :: Lens' ListPipelinesResponse (Maybe Text)
lprNextPageToken = lens _lprNextPageToken (\s a -> s { _lprNextPageToken = a })
-- | An array of 'Pipeline' objects.
lprPipelines :: Lens' ListPipelinesResponse [Pipeline]
lprPipelines = lens _lprPipelines (\s a -> s { _lprPipelines = a }) . _List
instance ToPath ListPipelines where
toPath = const "/2012-09-25/pipelines"
instance ToQuery ListPipelines where
toQuery ListPipelines{..} = mconcat
[ "Ascending" =? _lpAscending
, "PageToken" =? _lpPageToken
]
instance ToHeaders ListPipelines
instance ToJSON ListPipelines where
toJSON = const (toJSON Empty)
instance AWSRequest ListPipelines where
type Sv ListPipelines = ElasticTranscoder
type Rs ListPipelines = ListPipelinesResponse
request = get
response = jsonResponse
instance FromJSON ListPipelinesResponse where
parseJSON = withObject "ListPipelinesResponse" $ \o -> ListPipelinesResponse
<$> o .:? "NextPageToken"
<*> o .:? "Pipelines" .!= mempty
instance AWSPager ListPipelines where
page rq rs
| stop (rs ^. lprNextPageToken) = Nothing
| otherwise = (\x -> rq & lpPageToken ?~ x)
<$> (rs ^. lprNextPageToken)
| dysinger/amazonka | amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/ListPipelines.hs | mpl-2.0 | 4,773 | 0 | 12 | 1,016 | 665 | 392 | 273 | 71 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.Debugger
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Examines the call stack and variables of a running application without
-- stopping or slowing it down.
--
-- /See:/ <http://cloud.google.com/debugger Stackdriver Debugger API Reference>
module Network.Google.Debugger
(
-- * Service Configuration
debuggerService
-- * OAuth Scopes
, cloudDebuggerScope
, cloudPlatformScope
-- * API Declaration
, DebuggerAPI
-- * Resources
-- ** clouddebugger.controller.debuggees.breakpoints.list
, module Network.Google.Resource.CloudDebugger.Controller.Debuggees.Breakpoints.List
-- ** clouddebugger.controller.debuggees.breakpoints.update
, module Network.Google.Resource.CloudDebugger.Controller.Debuggees.Breakpoints.Update
-- ** clouddebugger.controller.debuggees.register
, module Network.Google.Resource.CloudDebugger.Controller.Debuggees.Register
-- ** clouddebugger.debugger.debuggees.breakpoints.delete
, module Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Delete
-- ** clouddebugger.debugger.debuggees.breakpoints.get
, module Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Get
-- ** clouddebugger.debugger.debuggees.breakpoints.list
, module Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.List
-- ** clouddebugger.debugger.debuggees.breakpoints.set
, module Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Set
-- ** clouddebugger.debugger.debuggees.list
, module Network.Google.Resource.CloudDebugger.Debugger.Debuggees.List
-- * Types
-- ** RegisterDebuggeeResponse
, RegisterDebuggeeResponse
, registerDebuggeeResponse
, rdrDebuggee
-- ** SourceContext
, SourceContext
, sourceContext
, scCloudWorkspace
, scCloudRepo
, scGerrit
, scGit
-- ** SetBreakpointResponse
, SetBreakpointResponse
, setBreakpointResponse
, sbrBreakpoint
-- ** Empty
, Empty
, empty
-- ** UpdateActiveBreakpointResponse
, UpdateActiveBreakpointResponse
, updateActiveBreakpointResponse
-- ** GerritSourceContext
, GerritSourceContext
, gerritSourceContext
, gscGerritProject
, gscAliasName
, gscRevisionId
, gscHostURI
, gscAliasContext
-- ** RepoId
, RepoId
, repoId
, riUid
, riProjectRepoId
-- ** ExtendedSourceContextLabels
, ExtendedSourceContextLabels
, extendedSourceContextLabels
, esclAddtional
-- ** ProjectRepoId
, ProjectRepoId
, projectRepoId
, priRepoName
, priProjectId
-- ** FormatMessage
, FormatMessage
, formatMessage
, fmFormat
, fmParameters
-- ** Breakpoint
, Breakpoint
, breakpoint
, bStatus
, bLogLevel
, bLocation
, bAction
, bFinalTime
, bExpressions
, bLogMessageFormat
, bId
, bLabels
, bUserEmail
, bVariableTable
, bStackFrames
, bCondition
, bEvaluatedExpressions
, bCreateTime
, bIsFinalState
-- ** BreakpointLabels
, BreakpointLabels
, breakpointLabels
, blAddtional
-- ** GetBreakpointResponse
, GetBreakpointResponse
, getBreakpointResponse
, gbrBreakpoint
-- ** Variable
, Variable
, variable
, vStatus
, vVarTableIndex
, vMembers
, vValue
, vName
, vType
-- ** ListBreakpointsResponse
, ListBreakpointsResponse
, listBreakpointsResponse
, lbrNextWaitToken
, lbrBreakpoints
-- ** StatusMessageRefersTo
, StatusMessageRefersTo (..)
-- ** BreakpointLogLevel
, BreakpointLogLevel (..)
-- ** ListDebuggeesResponse
, ListDebuggeesResponse
, listDebuggeesResponse
, ldrDebuggees
-- ** UpdateActiveBreakpointRequest
, UpdateActiveBreakpointRequest
, updateActiveBreakpointRequest
, uabrBreakpoint
-- ** StatusMessage
, StatusMessage
, statusMessage
, smRefersTo
, smIsError
, smDescription
-- ** Xgafv
, Xgafv (..)
-- ** BreakpointAction
, BreakpointAction (..)
-- ** ListActiveBreakpointsResponse
, ListActiveBreakpointsResponse
, listActiveBreakpointsResponse
, labrNextWaitToken
, labrBreakpoints
, labrWaitExpired
-- ** ExtendedSourceContext
, ExtendedSourceContext
, extendedSourceContext
, escContext
, escLabels
-- ** GitSourceContext
, GitSourceContext
, gitSourceContext
, gURL
, gRevisionId
-- ** SourceLocation
, SourceLocation
, sourceLocation
, slPath
, slLine
-- ** StackFrame
, StackFrame
, stackFrame
, sfFunction
, sfLocation
, sfArguments
, sfLocals
-- ** CloudRepoSourceContext
, CloudRepoSourceContext
, cloudRepoSourceContext
, crscRepoId
, crscAliasName
, crscRevisionId
, crscAliasContext
-- ** DebuggeeLabels
, DebuggeeLabels
, debuggeeLabels
, dlAddtional
-- ** Debuggee
, Debuggee
, debuggee
, dStatus
, dUniquifier
, dProject
, dExtSourceContexts
, dAgentVersion
, dIsDisabled
, dId
, dLabels
, dDescription
, dIsInactive
, dSourceContexts
-- ** CloudWorkspaceSourceContext
, CloudWorkspaceSourceContext
, cloudWorkspaceSourceContext
, cwscWorkspaceId
, cwscSnapshotId
-- ** RegisterDebuggeeRequest
, RegisterDebuggeeRequest
, registerDebuggeeRequest
, rDebuggee
-- ** AliasContext
, AliasContext
, aliasContext
, acKind
, acName
-- ** AliasContextKind
, AliasContextKind (..)
-- ** CloudWorkspaceId
, CloudWorkspaceId
, cloudWorkspaceId
, cwiRepoId
, cwiName
) where
import Network.Google.Debugger.Types
import Network.Google.Prelude
import Network.Google.Resource.CloudDebugger.Controller.Debuggees.Breakpoints.List
import Network.Google.Resource.CloudDebugger.Controller.Debuggees.Breakpoints.Update
import Network.Google.Resource.CloudDebugger.Controller.Debuggees.Register
import Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Delete
import Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Get
import Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.List
import Network.Google.Resource.CloudDebugger.Debugger.Debuggees.Breakpoints.Set
import Network.Google.Resource.CloudDebugger.Debugger.Debuggees.List
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Stackdriver Debugger API service.
type DebuggerAPI =
ControllerDebuggeesBreakpointsListResource :<|>
ControllerDebuggeesBreakpointsUpdateResource
:<|> ControllerDebuggeesRegisterResource
:<|> DebuggerDebuggeesBreakpointsSetResource
:<|> DebuggerDebuggeesBreakpointsListResource
:<|> DebuggerDebuggeesBreakpointsGetResource
:<|> DebuggerDebuggeesBreakpointsDeleteResource
:<|> DebuggerDebuggeesListResource
| rueshyna/gogol | gogol-debugger/gen/Network/Google/Debugger.hs | mpl-2.0 | 7,578 | 0 | 11 | 1,716 | 785 | 571 | 214 | 188 | 0 |
{-|
Module : $Header$
Copyright : (c) 2015 Edward O'Callaghan
License : LGPL-2.1
Maintainer : [email protected]
Stability : provisional
Portability : portable
This module encapsulates types libFtdi library functions.
-}
{-# LANGUAGE Trustworthy #-}
module LibFtdi.Types ( FtdiChipType(..)
, FtdiParityType(..)
, FtdiStopBitsType(..)
, FtdiBitsType(..)
, FtdiBreakType(..)
, FtdiMPSSEMode(..)
, FtdiInterface(..)
, FtdiModuleDetactMode(..)
, FtdiEEPROMValue(..)
) where
-- import Bindings.LibFtdi
-- import Foreign.C.Types
-- import Data.Word
-- import Data.Maybe
-- import Data.Tuple
-- import Data.Coerce
-- import GHC.Generics
-- | FTDI chip type
data FtdiChipType = TYPE_AM -- ^ ..
| TYPE_BM -- ^ ..
| TYPE_2232C -- ^ ..
| TYPE_R -- ^ ..
| TYPE_2232H -- ^ ..
| TYPE_4232H -- ^ ..
| TYPE_232H -- ^ ..
| TYPE_230X -- ^ ..
deriving (Eq, Enum)
-- instance Enum FtdiChipType where
-- fromEnum = fromJust . flip lookup chiptypes
-- toEnum = fromJust . flip lookup (map swap chiptypes)
--
-- chiptypes = [ (TYPE_AM, C'TYPE_AM)
-- , (TYPE_BM, C'TYPE_BM)
-- , (TYPE_2232C, C'TYPE_2232C)
-- , (TYPE_R, C'TYPE_R)
-- , (TYPE_2232H, C'TYPE_2232H)
-- , (TYPE_4232H, C'TYPE_4232H)
-- , (TYPE_232H, C'TYPE_232H)
-- , (TYPE_230X, C'TYPE_230X)
-- ]
-- | Parity mode for ftdi_set_line_property()
data FtdiParityType = None
| Odd
| Even
| Mark
| Space
deriving (Eq, Enum)
-- | Number of stop bits for ftdi_set_line_property()
data FtdiStopBitsType = StopBit1
| StopBit15
| StopBit2
deriving (Eq, Enum)
-- | Number of bits for ftdi_set_line_property()
data FtdiBitsType = Bits7
| Bits8
deriving Eq
instance Enum FtdiBitsType where
fromEnum Bits7 = 7
fromEnum Bits8 = 8
toEnum 7 = Bits7
toEnum 8 = Bits8
-- | Break type for ftdi_set_line_property2()
data FtdiBreakType = BreakOff
| BreakOn
deriving (Eq, Enum)
-- | MPSSE bitbang modes
data FtdiMPSSEMode = BITMODE_RESET -- ^ switch off bitbang mode, back to regular serial/FIFO
| BITMODE_BITBANG -- ^ classical asynchronous bitbang mode, introduced with B-type chips
| BITMODE_MPSSE -- ^ MPSSE mode, available on 2232x chips
| BITMODE_SYNCBB -- ^ synchronous bitbang mode, available on 2232x and R-type chips
| BITMODE_MCU -- ^ MCU Host Bus Emulation mode, available on 2232x chips
-- CPU-style fifo mode gets set via EEPROM
| BITMODE_OPTO -- ^ Fast Opto-Isolated Serial Interface Mode, available on 2232x chips
| BITMODE_CBUS -- ^ Bitbang on CBUS pins of R-type chips, configure in EEPROM before
| BITMODE_SYNCFF -- ^ Single Channel Synchronous FIFO mode, available on 2232H chips
| BITMODE_FT1284 -- ^ FT1284 mode, available on 232H chips
deriving Eq
instance Enum FtdiMPSSEMode where
fromEnum BITMODE_RESET = 0x00
fromEnum BITMODE_BITBANG = 0x01
fromEnum BITMODE_MPSSE = 0x02
fromEnum BITMODE_SYNCBB = 0x04
fromEnum BITMODE_MCU = 0x08
fromEnum BITMODE_OPTO = 0x10
fromEnum BITMODE_CBUS = 0x20
fromEnum BITMODE_SYNCFF = 0x40
fromEnum BITMODE_FT1284 = 0x80
-- | Port interface for chips with multiple interfaces
data FtdiInterface = INTERFACE_ANY
| INTERFACE_A
| INTERFACE_B
| INTERFACE_C
| INTERFACE_D
deriving (Eq, Enum)
-- | Automatic loading / unloading of kernel modules
data FtdiModuleDetactMode = AUTO_DETACH_SIO_MODULE
| DONT_DETACH_SIO_MODULE
deriving (Eq, Enum)
-- | List all handled EEPROM values.
data FtdiEEPROMValue = VENDOR_ID
| PRODUCT_ID
| SELF_POWERED
| REMOTE_WAKEUP
| IS_NOT_PNP
| SUSPEND_DBUS7
| IN_IS_ISOCHRONOUS
| OUT_IS_ISOCHRONOUS
| SUSPEND_PULL_DOWNS
| USE_SERIAL
| USB_VERSION
| USE_USB_VERSION
| MAX_POWER
| CHANNEL_A_TYPE
| CHANNEL_B_TYPE
| CHANNEL_A_DRIVER
| CHANNEL_B_DRIVER
| CBUS_FUNCTION_0
| CBUS_FUNCTION_1
| CBUS_FUNCTION_2
| CBUS_FUNCTION_3
| CBUS_FUNCTION_4
| CBUS_FUNCTION_5
| CBUS_FUNCTION_6
| CBUS_FUNCTION_7
| CBUS_FUNCTION_8
| CBUS_FUNCTION_9
| HIGH_CURRENT
| HIGH_CURRENT_A
| HIGH_CURRENT_B
| INVERT
| GROUP0_DRIVE
| GROUP0_SCHMITT
| GROUP0_SLEW
| GROUP1_DRIVE
| GROUP1_SCHMITT
| GROUP1_SLEW
| GROUP2_DRIVE
| GROUP2_SCHMITT
| GROUP2_SLEW
| GROUP3_DRIVE
| GROUP3_SCHMITT
| GROUP3_SLEW
| CHIP_SIZE
| CHIP_TYPE
| POWER_SAVE
| CLOCK_POLARITY
| DATA_ORDER
| FLOW_CONTROL
| CHANNEL_C_DRIVER
| CHANNEL_D_DRIVER
| CHANNEL_A_RS485
| CHANNEL_B_RS485
| CHANNEL_C_RS485
| CHANNEL_D_RS485
| RELEASE_NUMBER
deriving (Eq, Enum)
| victoredwardocallaghan/bindings-libftdi | src/LibFtdi/Types.hs | lgpl-2.1 | 6,443 | 8 | 6 | 2,854 | 643 | 411 | 232 | 126 | 0 |
{-# LANGUAGE
GeneralizedNewtypeDeriving
, FlexibleContexts #-}
import Text.XML.HaXml
import qualified Text.XML.HaXml.Pretty as P
import System.Environment ( getArgs )
import Data.LookupTable ( LookupTable )
import qualified Data.LookupTable as LT
import Data.Map ( Map )
import Data.Maybe ( fromMaybe )
import Control.Monad ( liftM )
import Control.Applicative ( (<$>) )
import Data.FIX.Parser ( tBeginString, tBodyLength, tCheckSum, tMsgType )
import qualified Data.FIX.Message as FM ( tName )
main = do
args <- getArgs
xmlContent <- readFile $ xmlFile args
let xmlDoc = xmlParse "/dev/null" xmlContent
modName = moduleName args in
do --- print the module header with all the imports ---
putStr $ moduleHeader modName xmlDoc ++ "\n\n"
{-putStr $ concatMap (show . P.content) $ content $ getFieldSpec xmlDoc-}
--- declare all FIX Tags ---
putStr $ genFIXFields xmlDoc
--- declare the FIX header ---
putStr $ genFIXHeader xmlDoc
--- declare the FIX trailer ---
putStr $ genFIXTrailer xmlDoc
--- declare all FIX messages ---
putStr $ genFIXMessages xmlDoc
{-putStr $ genFIXGroups xmlDoc-}
putStr $ genFIXSpec xmlDoc
where
moduleHeader mod' doc =
"module " ++ mod' ++ " ( " ++ fixSpecName doc ++ " ) where\n" ++
"import qualified Data.ByteString.Char8 as C\n" ++
"import qualified Data.LookupTable as LT ( new, insert )\n" ++
"import Data.FIX.Message\n" ++
"import Data.FIX.Parser\n" ++
"import Data.Functor ( (<$>) )\n" ++
"import Data.FIX.Arbitrary \n" ++
"import Test.QuickCheck ( arbitrary )\n"
-- command line options
xmlFile :: [String] -> String
xmlFile = head
moduleName :: [String] -> String
moduleName xs | length xs > 1 = head $ tail xs
| otherwise = error
"you need to specify a name for the module"
_commonTag :: Content a -> Bool
_commonTag (CElem e _) =
let tags = map FM.tName [tBeginString, tBodyLength, tCheckSum, tMsgType]
tag = getNameAttr e
in
elem tag tags
_commonTag _ = False
genFIXHeader :: Document a -> String
genFIXHeader doc = let name = headerName doc in
name ++ " :: FIXTags\n" ++
name ++ " = \n" ++ tags' ++ "\n\n"
where
tags' = let h = getHeaderSpec doc
header = filter (not . _commonTag) $ content h
in
fieldsOf 1 header
genFIXTrailer :: Document a -> String
genFIXTrailer doc = let name = trailerName doc in
name ++ " :: FIXTags\n" ++
name ++ " = \n" ++ tags' ++ "\n\n"
where
tags' = let h = getTrailerSpec doc
trailer = filter (not . _commonTag) $ content h
in
fieldsOf 1 trailer
genFIXMessages :: Document a -> String
genFIXMessages doc = concatMap genMessage $ messagesOf doc
where
genMessage :: Content a -> String
genMessage (CElem e _) =
let msg' = getNameAttr e
msg = mName msg'
msgBody' = msg ++ "Body"
mType = getMsgTypeAttr e
tags' = fieldsOf 2 $ content e
indent = replicate 3 ' '
in
msg ++ " :: FIXMessageSpec\n" ++
msg ++ " = FMSpec\n" ++
indent ++ "{ msName = \"" ++ msg' ++ "\"\n" ++
indent ++ ", msType = C.pack \"" ++ mType ++ "\"\n" ++
indent ++ ", msHeader = " ++ headerName doc ++ '\n' :
indent ++ ", msBody = " ++ msgBody' ++ '\n' :
indent ++ ", msTrailer = " ++ trailerName doc ++ " }\n" ++
indent ++ "where\n" ++
indent ++ msgBody' ++ " = \n" ++ tags' ++ "\n\n"
getMsgTypeAttr = getAttr "msgtype"
genFIXFields :: Document a -> String
genFIXFields doc = let fields = filter (not . _commonTag) $
content $ getFieldSpec doc
in concatMap fieldDef fields
genFIXSpec :: Document a -> String
genFIXSpec doc = let
spec' = fixSpecName doc
fix = getFIXSpec doc
major = getAttr "major" fix
minor = getAttr "minor" fix
in
spec' ++ " :: FIXSpec\n" ++
spec' ++ " = FSpec\n" ++
" { fsVersion = \"FIX." ++
major ++ "." ++ minor++ "\"\n" ++
" , fsHeader = " ++ headerName doc ++ '\n' :
" , fsTrailer = " ++ trailerName doc ++ '\n' :
" , fsMessages = " ++ spec' ++ "Messages \n" ++
" , fsTags = " ++ spec' ++ "Tags }\n" ++
" where\n" ++
" " ++ spec' ++ "Messages =\n" ++ messageMap ++
" LT.new \n" ++
" " ++ spec' ++ "Tags =\n" ++ tagsMap ++
" LT.new \n"
where
rmLastNewline text | length text > 2 = init . init $ text
| otherwise = text
messageMap = rmLastNewline (concatMap _insertMsg $ messagesOf doc)
_insertMsg (CElem e _) =
let msg' = mName $ getNameAttr e in
" LT.insert (msType " ++ msg' ++ ") " ++
msg' ++ " $\n"
_insertMsg _ = undefined
tagsMap = concatMap _insertTag $ content $ getFieldSpec doc
_insertTag (CElem e _) = let fname = tName (getNameAttr e) in
" LT.insert (tnum " ++ fname ++ ") " ++ fname ++ " $\n"
_insertTag _ = ""
type Groups a = Map String [Content a]
-- ?Name :: String -> String
tName = (:) 't'
mName = (:) 'm'
fName = (:) 'f'
gName = (:) 'g'
versionFIX :: Document a -> String
versionFIX doc = major ++ minor
where
fix = getFIXSpec doc
major = getAttr "major" fix
minor = getAttr "minor" fix
-- *Name :: Document a -> String
headerName d = "headerFIX" ++ versionFIX d
trailerName d = "trailerFIX" ++ versionFIX d
fixSpecName a = "fix" ++ versionFIX a
content :: Element a -> [Content a]
content (Elem _ _ cs) = cs
cElement :: Content a -> Element a
cElement (CElem e _) = e
cElement _ = error "not an element"
attributes :: Element a -> [Attribute]
attributes (Elem _ as _) = as
getFIXSpec :: Document a -> Element a
getFIXSpec doc = case doc of
Document _ _ (es@(Elem (N n) _ _)) _
-> if n == "fix" then es else error "no specification for fix"
_ -> error "unknown error"
_matchName :: String -> Content a -> Bool
_matchName name (CElem (Elem (N n) _ _) _) = n == name
_matchName name _ = False
_lookup :: (LookupTable t, Show (LT.KeyOf t)) => LT.KeyOf t -> t -> LT.ValueOf t
_lookup key t = fromMaybe (error $ "couldn't find key " ++ show key)
$ LT.lookup key t
getSpec :: String -> Document a -> Maybe (Element a)
getSpec name doc =
let fix = getFIXSpec doc in
case filter (_matchName name) (content fix) of
CElem es _ : _ -> Just es
_ -> Nothing
getFieldSpec = fromMaybe (error "fields not defined") . getSpec "fields"
getHeaderSpec = fromMaybe (error "header not defined") . getSpec "header"
getTrailerSpec = fromMaybe (error "trailer not defined") . getSpec "trailer"
getMessagesSpec = fromMaybe (error "messages not defined") . getSpec "messages"
getComponentsSpec = fromMaybe (Elem (N "components") [] []) . getSpec "components"
getAttr :: String -> Element a -> String
getAttr name e = _lookup name $ fromAttributes $ attributes e
getNameAttr = getAttr "name"
fromAttributes :: [Attribute] -> Map String String
fromAttributes = foldr _insert LT.new
where
_insert :: Attribute -> Map String String -> Map String String
_insert (N k, AttValue (Left v : _)) = LT.insert k v
_insert (N k, _) = LT.insert k ""
fieldDef :: Content a -> String
fieldDef (CElem e _) =
let name = getNameAttr e
fname = tName name
fenum = getAttr "number" e
ftype = getAttr "type" e
tparser = "to" ++ typeOfFIX ftype
arbValue' = let t' = typeOfFIX ftype in
case t' of
"FIXChar" -> "FIXChar <$> (return 'A')"
"FIXDouble" -> "FIXDouble <$> (return (-2.112 :: Double))"
_ -> t' ++ " <$> arbitrary"
in
fname ++ " :: FIXTag\n" ++
fname ++ " = FIXTag \n" ++
" { tName = \"" ++ name ++ "\"\n" ++
" , tnum = " ++ fenum ++ '\n' :
" , tparser = " ++ tparser ++ '\n' :
" , arbitraryValue = " ++ arbValue' ++ " }\n\n"
where
typeOfFIX :: String -> String
typeOfFIX x = fromMaybe (error $ "unknown type " ++ x) $
LT.lookup x values'
where
values' :: Map String String
values' =
LT.insert "INT" "FIXInt" $
LT.insert "STRING" "FIXString" $
LT.insert "DAYOFMONTH" "FIXInt" $
LT.insert "CHAR" "FIXChar" $
LT.insert "FLOAT" "FIXDouble" $
LT.insert "QTY" "FIXDouble" $
LT.insert "PRICE" "FIXDouble" $
LT.insert "QUANTITY" "FIXDouble" $
LT.insert "PRICEOFFSET" "FIXDouble" $
LT.insert "AMT" "FIXDouble" $
LT.insert "BOOLEAN" "FIXBool" $
LT.insert "MULTIPLEVALUESTRING" "FIXMultipleValueString" $
LT.insert "CURRENCY" "FIXString" $
LT.insert "EXCHANGE" "FIXString" $
LT.insert "UTCTIMESTAMP" "FIXTimestamp" $
LT.insert "UTCTIMEONLY" "FIXTimeOnly" $
LT.insert "UTCDATE" "FIXDateOnly" $
LT.insert "MONTHYEAR" "FIXMonthYear" $
LT.insert "LOCALMKTDATE" "FIXDateOnly" $
LT.insert "DATA" "FIXData" $
LT.insert "LENGTH" "FIXInt" $
LT.insert "TIME" "FIXTimestamp" $
LT.insert "SEQNUM" "FIXInt" $
LT.insert "NUMINGROUP" "FIXInt" $
LT.insert "PERCENTAGE" "FIXDouble" $
LT.insert "COUNTRY" "FIXString" $
LT.insert "UTCDATEONLY" "FIXDateOnly" $
LT.insert "DATE" "FIXDateOnly"
LT.new
fieldDef _ = ""
type Components a = [(String, [Content a])]
componentsOf :: Document a -> Components a
componentsOf doc = let spec' = getComponentsSpec doc in
foldr _insert LT.new $ content spec'
where
_insert c t
| _matchName "component" c = let elem = cElement c in
LT.insert (getNameAttr elem) (content elem) t
| otherwise = t
expandComp :: Components a -> Content a -> Content a
expandComp comps c@(CElem (Elem n as cs) i) =
CElem (Elem n as (concatMap _expand cs)) i
where
_expand c | _matchName "component" c =
let name = getNameAttr $ cElement c
compCont = _lookup name comps
in
concatMap _expand compCont
| otherwise = [ expandComp comps c ]
expandComp comps c = c
messagesOf :: Document a -> [Content a]
messagesOf doc =
let all = getMessagesSpec doc
msgOnly = filter (_matchName "message") (content all)
in
map (expandComp (componentsOf doc)) msgOnly
fieldsOf :: Int -> [Content a] -> String
fieldsOf l cs =
let groups = LT.toList $ groupsOf cs
rmLastNewline text | length text > 2 = init . init $ text
| otherwise = text
in
rmLastNewline (concatMap _insertTag cs) ++
indent ++ "LT.new\n" ++
if not (null groups) then
indent ++ "where\n" ++ concatMap (genGroups (l + 1)) groups
else ""
where
indent = replicate (l * 3) ' '
suffix = replicate (l + 1) '\''
_insertTag c
| _matchName "field" c =
let n' = tName $ getNameAttr $ cElement c
in indent ++ "LT.insert (tnum " ++ n' ++ ") " ++ n' ++ " $\n"
| _matchName "group" c =
let n = getNameAttr $ cElement c
in indent ++ "LT.insert (tnum " ++ tName n ++ ") " ++ gName n ++ suffix ++ " $\n"
| otherwise = ""
genGroups _ (_, _:[]) = error "group should have a sperator"
genGroups l (n, gcs') =
let (s, gcs) = getSepAndCont gcs'
sname = tName $ getNameAttr $ cElement s
gname = gName n
indent' = replicate (l * 3) ' '
indent'' = replicate ((l + 1) * 3) ' '
suffix' = replicate l '\''
tags' = fieldsOf (l + 2) gcs
in
indent' ++ gname ++ suffix' ++ " = FIXTag\n" ++
indent'' ++ "{ tName = \"" ++ n ++ "\"\n" ++
indent'' ++ ", tnum = tnum " ++ tName n ++ '\n' :
indent'' ++ ", tparser = " ++ gname ++ "P" ++ suffix' ++ '\n' :
indent'' ++ ", arbitraryValue = arbibtraryFIXGroup " ++
gname ++ "Spec" ++ suffix' ++ " }\n\n" ++
indent' ++ gname ++ "P" ++ suffix' ++ " = groupP " ++ gname ++ "Spec" ++ suffix' ++ '\n' :
indent' ++ gname ++ "Spec" ++ suffix' ++ " = FGSpec\n" ++
indent'' ++ "{ gsLength = " ++ tName n ++ '\n' :
indent'' ++ ", gsSeperator = " ++ sname ++ '\n' :
indent'' ++ ", gsBody = " ++ gname ++ "Body" ++ suffix' ++ " }\n" ++
indent'' ++ "where\n" ++
indent'' ++ gname ++ "Body" ++ suffix' ++ " = \n" ++ tags' ++ "\n"
where
getSepAndCont [] = undefined
getSepAndCont (c@(CElem _ _):ds) = (c, ds)
getSepAndCont (_ : ds) = getSepAndCont ds
groupsOf :: [Content a] -> Groups a
groupsOf = addGroups LT.new
where
addGroups :: Groups a -> [Content a] -> Groups a
addGroups = foldr _insert
where
_insert :: Content a -> Groups a -> Groups a
_insert c@(CElem e _) gs
| _matchName "group" c =
let gname = getNameAttr e
gcontent = content e
in LT.insert gname gcontent gs
| _matchName "message" c =
let mcontent = content e in
addGroups gs mcontent
| otherwise = gs
_insert _ gs = gs
| urv/fixhs | src/Utils/Generator.hs | lgpl-2.1 | 15,187 | 317 | 69 | 5,913 | 4,136 | 2,054 | 2,082 | 301 | 5 |
module Constant where
newtype Constant a b =
Constant { getConstant :: a }
deriving (Eq, Ord, Show)
instance Functor (Constant a) where
fmap _ (Constant b) = Constant b
instance Monoid a => Applicative (Constant a) where
pure _ = Constant mempty
(Constant a) <*> (Constant a') = Constant $ a `mappend` a'
| thewoolleyman/haskellbook | 17/05/haskell-club/Constant.hs | unlicense | 319 | 0 | 8 | 68 | 132 | 70 | 62 | 9 | 0 |
module Lib
( verifySumIsFunctor
, verifySumIsApplicative
, verifyValidationIsFunctor
, verifyValidationIsApplicative
) where
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
data Sum a b =
First a
| Second b
deriving (Eq, Show)
-- Arbitrary instance for Sum
instance (Arbitrary a, Arbitrary b) => Arbitrary (Sum a b) where
arbitrary = do
first <- arbitrary
second <- arbitrary
list <- elements [First first, Second second]
return $ list
instance Functor (Sum a) where
fmap _ (First x) = First x
fmap f (Second x) = Second (f x)
-- Required for checkers
instance (Eq a, Eq b) => EqProp (Sum a b) where (=-=) = eq
-- Use checkers to verify the Fuctor for Sum is valid
verifySumIsFunctor :: IO ()
verifySumIsFunctor = quickBatch $ functor (undefined::Sum (Int, Int, Int) (Int, Int, Int))
instance Applicative (Sum a) where
pure = Second
(<*>) (Second f) (Second x) = Second (f x)
(<*>) (First x) _ = First x
(<*>) _ (First x) = First x
-- Use checkers to verify the Fuctor for Sum is valid
verifySumIsApplicative :: IO ()
verifySumIsApplicative = quickBatch $ applicative (undefined::Sum (Int, Int, Int) (Int, Int, Int))
data Validation e a =
Error e
| Success a
deriving (Eq, Show)
-- Arbitrary instance for Validation
instance (Arbitrary a, Arbitrary b) => Arbitrary (Validation a b) where
arbitrary = do
e <- arbitrary
s <- arbitrary
list <- elements [Error e, Lib.Success s]
return $ list
-- same as Sum/Either
instance Functor (Validation e) where
fmap _ (Error x) = Error x
fmap f (Lib.Success x) = Lib.Success (f x)
-- Required for checkers
instance (Eq a, Eq b) => EqProp (Validation a b) where (=-=) = eq
-- Use checkers to verify the Functor for Validation is valid
verifyValidationIsFunctor :: IO ()
verifyValidationIsFunctor = quickBatch $ functor (undefined::Validation (Int, Int, Int) (Int, Int, Int))
instance Monoid e => Applicative (Validation e) where
pure = Lib.Success
(<*>) (Lib.Success f) (Lib.Success x) = Lib.Success $ f x
(<*>) (Error e1) (Error e2) = Error (e1 `mappend` e2)
(<*>) (Error e) _ = Error e
(<*>) _ (Error e) = Error e
-- Use checkers to verify the Applicative for Validation is valid
verifyValidationIsApplicative :: IO ()
verifyValidationIsApplicative = quickBatch $ applicative (undefined::Validation (String, String, String) (String, String, String))
| dmp1ce/Haskell-Programming-Exercises | Chapter 17/VariationsOnEither/src/Lib.hs | unlicense | 2,493 | 0 | 12 | 544 | 895 | 481 | 414 | 55 | 1 |
module P8 where
import Data.List
{-
(**) Eliminate consecutive duplicates of list elements.
If a list contains repeated elements they should be replaced with a single copy of the element.
The order of the elements should not be changed.
Example:
* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)
-}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress list = foldr (\y acc -> if elem y acc then acc else y : acc) [] list
compress' :: (Eq a) => [a] -> [a]
compress' (x:ys@(y:_))
| x == y = compress ys
| otherwise = x : compress ys
compress' ys = ys
compress'' :: (Eq a) => [a] -> [a]
compress'' = map head . group | nikolaspapirniywork/99_problems | haskell/src/P8.hs | apache-2.0 | 685 | 0 | 10 | 193 | 212 | 114 | 98 | 12 | 2 |
{-# LANGUAGE BangPatterns #-}
{-|
Module : Data.Snowflake
Description : Unique id generator. Port of Twitter Snowflake.
License : Apache 2.0
Maintainer : [email protected]
Stability : experimental
This generates unique(guaranteed) identifiers build from time stamp,
counter(inside same millisecond) and node id - if you wish to generate
ids across several nodes. Identifiers are convertible to `Integer`
values which are monotonically increasing with respect to time.
-}
module Data.Snowflake
( SnowflakeConfig(..)
, Snowflake
, SnowflakeGen
, newSnowflakeGen
, nextSnowflake
, defaultConfig
, snowflakeToInteger
) where
import Data.Bits ((.|.), (.&.), shift, Bits)
import Control.Concurrent.MVar (MVar, newMVar, putMVar, takeMVar)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Control.Monad (when)
import Control.Concurrent (threadDelay)
{-|
Configuration that specifies how much bits are used for each part of the id.
There are no limits to total bit sum.
-}
data SnowflakeConfig = SnowflakeConfig { confTimeBits :: {-# UNPACK #-} !Int
, confCountBits :: {-# UNPACK #-} !Int
, confNodeBits :: {-# UNPACK #-} !Int
} deriving (Eq, Show)
-- |Default configuration using 40 bits for time, 16 for count and 8 for node id.
defaultConfig :: SnowflakeConfig
defaultConfig = SnowflakeConfig 40 16 8
-- |Generator which contains needed state. You should use `newSnowflakeGen` to create instances.
newtype SnowflakeGen = SnowflakeGen { genLastSnowflake :: MVar Snowflake }
-- |Generated identifier. Can be converted to `Integer`.
data Snowflake = Snowflake { snowflakeTime :: !Integer
, snowflakeCount :: !Integer
, snowflakeNode :: !Integer
, snowflakeConf :: !SnowflakeConfig
} deriving (Eq)
-- |Converts an identifier to an integer with respect to configuration used to generate it.
snowflakeToInteger :: Snowflake -> Integer
snowflakeToInteger (Snowflake time count node config) = let
SnowflakeConfig _ countBits nodeBits = config
in
(time `shift` (countBits + nodeBits))
.|.
(count `shift` nodeBits)
.|.
node
instance Show Snowflake where
show = show . snowflakeToInteger
cutBits :: (Num a, Bits a) => a -> Int -> a
cutBits n bits = n .&. ((1 `shift` bits) - 1)
currentTimestamp :: IO Integer
currentTimestamp = (round . (*1000)) `fmap` getPOSIXTime
currentTimestampFixed :: Int -> IO Integer
currentTimestampFixed n = fmap (`cutBits` n) currentTimestamp
-- |Create a new generator. Takes a configuration and node id.
newSnowflakeGen :: SnowflakeConfig -> Integer -> IO SnowflakeGen
newSnowflakeGen conf@(SnowflakeConfig timeBits _ nodeBits) nodeIdRaw = do
timestamp <- currentTimestampFixed timeBits
let nodeId = nodeIdRaw `cutBits` nodeBits
initial = Snowflake timestamp 0 nodeId conf
mvar <- newMVar initial
return $ SnowflakeGen mvar
-- |Generates next id. The bread and butter. See module description for details.
nextSnowflake :: SnowflakeGen -> IO Snowflake
nextSnowflake (SnowflakeGen lastRef) = do
Snowflake lastTime lastCount node conf <- takeMVar lastRef
let SnowflakeConfig timeBits countBits _ = conf
getNextTime = do
time <- currentTimestampFixed timeBits
if (lastTime > time) then do
threadDelay $ fromInteger $ (lastTime - time) * 1000
getNextTime
else
return time
loop = do
timestamp <- getNextTime
let count = if timestamp == lastTime then lastCount + 1 else 0
if ((count `shift` (-1 * countBits)) /= 0) then
loop
else
return $ Snowflake timestamp count node conf
new <- loop
putMVar lastRef new
return new
| edofic/snowflake-haskell | src/Data/Snowflake.hs | apache-2.0 | 3,881 | 0 | 19 | 957 | 783 | 428 | 355 | 76 | 4 |
-- -*- coding: utf-8; -*-
module Filter where
import Model
import qualified Data.Map as Map
filterElements :: Map.Map String String -- props jakie muszą być znalezione żeby element był zwrócony
-> [Element] -- filtrowane elementy
-> [Element]
filterElements pattern (e@(Element _ props _):es) | areCompatible pattern props = e : filterElements pattern es
filterElements pattern (e@(Element _ _ subelements):es) = filterElements pattern subelements ++ filterElements pattern es
filterElements pattern (e@(Text props _ _):es) | areCompatible pattern props = e : filterElements pattern es
filterElements pattern (_:es) = filterElements pattern es
filterElements pattern [] = []
areCompatible template props = Map.intersection props template == template
| grzegorzbalcerek/orgmode | Filter.hs | bsd-2-clause | 809 | 0 | 10 | 158 | 245 | 126 | 119 | 12 | 1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
-- | High-level API for CouchDB design documents. These methods are very
-- convenient for bootstrapping and testing.
module Database.CouchDB.Conduit.Design (
couchPutView
) where
import Prelude hiding (catch)
import Control.Monad (void)
import Control.Exception.Lifted (catch)
import qualified Data.ByteString as B
import Data.Text (Text)
import qualified Data.Text.Encoding as TE
import qualified Data.HashMap.Lazy as M
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as AT
import Database.CouchDB.Conduit.Internal.Connection
(MonadCouch, CouchError, Path, mkPath, Revision)
import Database.CouchDB.Conduit.Internal.Doc (couchGetWith, couchPutWith')
-- | Put view to design document. If design document does not exist,
-- it will be created.
couchPutView :: MonadCouch m =>
Path -- ^ Database
-> Path -- ^ Design document
-> Path -- ^ View name
-> B.ByteString -- ^ Map function
-> Maybe B.ByteString -- ^ Reduce function
-> m ()
couchPutView db designName viewName mapF reduceF = do
(_, A.Object d) <- getDesignDoc path
void $ couchPutWith' A.encode path [] $ inferViews (purge_ d)
where
path = designDocPath db designName
inferViews d = A.Object $ M.insert "views" (addView d) d
addView d = A.Object $ M.insert
(TE.decodeUtf8 viewName)
(constructView mapF reduceF)
(extractViews d)
constructView :: B.ByteString -> Maybe B.ByteString -> A.Value
constructView m (Just r) = A.object ["map" A..= m, "reduce" A..= r]
constructView m Nothing = A.object ["map" A..= m]
-----------------------------------------------------------------------------
-- Internal
-----------------------------------------------------------------------------
getDesignDoc :: MonadCouch m =>
Path
-> m (Revision, AT.Value)
getDesignDoc designName = catch
(couchGetWith A.Success designName [])
(\(_ :: CouchError) -> return (B.empty, AT.emptyObject))
designDocPath :: Path -> Path -> Path
designDocPath db dn = mkPath [db, "_design", dn]
-- | Purge underscore fields
purge_ :: AT.Object -> AT.Object
purge_ = M.filterWithKey (\k _ -> k `notElem` ["_id", "_rev"])
-- | Strip 'A.Value'
stripObject :: AT.Value -> AT.Object
stripObject (A.Object a) = a
stripObject _ = M.empty
-- Extract views field or return empty map
extractViews :: M.HashMap Text AT.Value -> M.HashMap Text AT.Value
extractViews o = maybe M.empty stripObject $ M.lookup "views" o
| lostbean/neo4j-conduit | src/Database/CouchDB/Conduit/Design.hs | bsd-2-clause | 2,689 | 0 | 12 | 614 | 690 | 382 | 308 | 49 | 2 |
module GTL.Text (
gtlToText
) where
import GTL.Parser
import qualified Data.Map as Map
import Data.List ((\\), partition, sort, intercalate, foldl')
import Data.Tree
gtlToText :: MyTree -> [String]
gtlToText tree = reverse
$ concat
$ reverse
$ flatten
$ fmap (stringify time) tree
where
(time, _, _, _) = rootLabel tree
stringify :: ErlTime -> (ErlTime, Dur, Pid, [BRecord]) -> [String]
stringify startGTLTs (startPidTs, _, _, rs) = lines
where
(_, lines) = foldl' p (startPidTs,[]) rs
p (prevTs, lines) r = (time, line:lines)
where
(time, pid, m, f, a) = (rTime r, rPid r, rModule r, rFunction r, rArg r)
diffPrev = (time - prevTs) `div` 1000
diffBegin = (time - startGTLTs) `div` 1000
line = pid ++ " ( " ++ show diffPrev ++ " / "
++ show diffBegin ++ " ) "
++ m ++ ":" ++ f ++ " " ++ a
| EchoTeam/gtl | tools/GTL/Text.hs | bsd-2-clause | 993 | 0 | 18 | 350 | 371 | 211 | 160 | 23 | 1 |
-- 248155780267521
import Data.List(sort)
import Euler(digitSum)
kk = 20
nn = 10^kk-1
mm = digitSum nn
vv = 30
findPowerSums n = map fst $ filter (\x -> snd x == n) ns
where ps = takeWhile (nn>) $ map (n^) [2..]
ns = map (\x -> (x, digitSum x)) ps
allPowerSums = sort $ concatMap findPowerSums [2..mm]
main = putStrLn $ show $ allPowerSums !! (vv-1)
| higgsd/euler | hs/119.hs | bsd-2-clause | 368 | 7 | 10 | 85 | 200 | 101 | 99 | 11 | 1 |
-- Exercise 5 in chapter 3 of "Real World Haskell"
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome ys@(x:xs) | odd (length ys) = False
isPalindrome ys@(x:xs) | ys == (reverse ys) = True
isPalindrome (x:xs) = False
| ploverlake/practice_of_haskell | src/isPalindrome.hs | bsd-2-clause | 299 | 0 | 10 | 102 | 115 | 59 | 56 | 5 | 1 |
module Graphics.Pastel.WX.Test ( testWX ) where
import Graphics.UI.WX hiding (circle)
import Graphics.UI.WXCore.Image
import Graphics.Pastel
import Graphics.Pastel.WX.Draw
testWX :: (Int, Int) -> Drawing -> IO ()
testWX (w,h) d = start gui
where gui = do
window <- frame [text := "Pastel WX Runner"]
canvas <- panel window [on paint := redraw]
return ()
redraw dc viewArea = do image <- drawWX (w,h) d
drawImage dc image (Point 0 0) []
| willdonnelly/pastel | Graphics/Pastel/WX/Test.hs | bsd-3-clause | 529 | 0 | 13 | 163 | 191 | 102 | 89 | 13 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash #-}
{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Exception.Base
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (extended exceptions)
--
-- Extensible exceptions, except for multiple handlers.
--
-----------------------------------------------------------------------------
module Control.Exception.Base (
-- * The Exception type
SomeException(..),
Exception(..),
IOException,
ArithException(..),
ArrayException(..),
AssertionFailed(..),
SomeAsyncException(..), AsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
NonTermination(..),
NestedAtomically(..),
BlockedIndefinitelyOnMVar(..),
BlockedIndefinitelyOnSTM(..),
AllocationLimitExceeded(..),
Deadlock(..),
NoMethodError(..),
PatternMatchFail(..),
RecConError(..),
RecSelError(..),
RecUpdError(..),
ErrorCall(..),
-- * Throwing exceptions
throwIO,
throw,
ioError,
throwTo,
-- * Catching Exceptions
-- ** The @catch@ functions
catch,
catchJust,
-- ** The @handle@ functions
handle,
handleJust,
-- ** The @try@ functions
try,
tryJust,
onException,
-- ** The @evaluate@ function
evaluate,
-- ** The @mapException@ function
mapException,
-- * Asynchronous Exceptions
-- ** Asynchronous exception control
mask,
mask_,
uninterruptibleMask,
uninterruptibleMask_,
MaskingState(..),
getMaskingState,
-- * Assertions
assert,
-- * Utilities
bracket,
bracket_,
bracketOnError,
finally,
-- * Calls for GHC runtime
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError,
nonTermination, nestedAtomically,
) where
import GHC.Base
import GHC.IO hiding (bracket,finally,onException)
import GHC.IO.Exception
import GHC.Exception
import GHC.Show
-- import GHC.Exception hiding ( Exception )
import GHC.Conc.Sync
import Data.Dynamic
import Data.Either
-----------------------------------------------------------------------------
-- Catching exceptions
-- |This is the simplest of the exception-catching functions. It
-- takes a single argument, runs it, and if an exception is raised
-- the \"handler\" is executed, with the value of the exception passed as an
-- argument. Otherwise, the result is returned as normal. For example:
--
-- > catch (readFile f)
-- > (\e -> do let err = show (e :: IOException)
-- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
-- > return "")
--
-- Note that we have to give a type signature to @e@, or the program
-- will not typecheck as the type is ambiguous. While it is possible
-- to catch exceptions of any type, see the section \"Catching all
-- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
--
-- For catching exceptions in pure (non-'IO') expressions, see the
-- function 'evaluate'.
--
-- Note that due to Haskell\'s unspecified evaluation order, an
-- expression may throw one of several possible exceptions: consider
-- the expression @(error \"urk\") + (1 \`div\` 0)@. Does
-- the expression throw
-- @ErrorCall \"urk\"@, or @DivideByZero@?
--
-- The answer is \"it might throw either\"; the choice is
-- non-deterministic. If you are catching any type of exception then you
-- might catch either. If you are calling @catch@ with type
-- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
-- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
-- exception may be propogated further up. If you call it again, you
-- might get a the opposite behaviour. This is ok, because 'catch' is an
-- 'IO' computation.
--
catch :: Exception e
=> IO a -- ^ The computation to run
-> (e -> IO a) -- ^ Handler to invoke if an exception is raised
-> IO a
catch = catchException
-- | The function 'catchJust' is like 'catch', but it takes an extra
-- argument which is an /exception predicate/, a function which
-- selects which type of exceptions we\'re interested in.
--
-- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- > (readFile f)
-- > (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- > return "")
--
-- Any other exceptions which are not matched by the predicate
-- are re-raised, and may be caught by an enclosing
-- 'catch', 'catchJust', etc.
catchJust
:: Exception e
=> (e -> Maybe b) -- ^ Predicate to select exceptions
-> IO a -- ^ Computation to run
-> (b -> IO a) -- ^ Handler
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throwIO e
Just b -> handler b
-- | A version of 'catch' with the arguments swapped around; useful in
-- situations where the code for the handler is shorter. For example:
--
-- > do handle (\NonTermination -> exitWith (ExitFailure 1)) $
-- > ...
handle :: Exception e => (e -> IO a) -> IO a -> IO a
handle = flip catch
-- | A version of 'catchJust' with the arguments swapped around (see
-- 'handle').
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
-----------------------------------------------------------------------------
-- 'mapException'
-- | This function maps one exception into another as proposed in the
-- paper \"A semantics for imprecise exceptions\".
-- Notice that the usage of 'unsafePerformIO' is safe here.
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throwIO (f x)))
-----------------------------------------------------------------------------
-- 'try' and variations.
-- | Similar to 'catch', but returns an 'Either' result which is
-- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@
-- if an exception of type @e@ was raised and its value is @ex@.
-- If any other type of exception is raised than it will be propogated
-- up to the next enclosing exception handler.
--
-- > try a = catch (Right `liftM` a) (return . Left)
try :: Exception e => IO a -> IO (Either e a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
-- | A variant of 'try' that takes an exception predicate to select
-- which exceptions are caught (c.f. 'catchJust'). If the exception
-- does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throwIO e
Just b -> return (Left b)
-- | Like 'finally', but only performs the final action if there was an
-- exception raised by the computation.
onException :: IO a -> IO b -> IO a
onException io what = io `catch` \e -> do _ <- what
throwIO (e :: SomeException)
-----------------------------------------------------------------------------
-- Some Useful Functions
-- | When you want to acquire a resource, do some work with it, and
-- then release the resource, it is a good idea to use 'bracket',
-- because 'bracket' will install the necessary exception handler to
-- release the resource in the event that an exception is raised
-- during the computation. If an exception is raised, then 'bracket' will
-- re-raise the exception (after performing the release).
--
-- A common example is opening a file:
--
-- > bracket
-- > (openFile "filename" ReadMode)
-- > (hClose)
-- > (\fileHandle -> do { ... })
--
-- The arguments to 'bracket' are in this order so that we can partially apply
-- it, e.g.:
--
-- > withFile name mode = bracket (openFile name mode) hClose
--
bracket
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracket before after thing =
mask $ \restore -> do
a <- before
-- 执行中间的过程的时候,不再屏蔽异常
-- 出现异常或者正常运行结束后再运行after
r <- restore (thing a) `onException` after a
_ <- after a
return r
-- | A specialised variant of 'bracket' with just a computation to run
-- afterward.
--
finally :: IO a -- ^ computation to run first
-> IO b -- ^ computation to run afterward (even if an exception
-- was raised)
-> IO a -- returns the value from the first computation
a `finally` sequel =
mask $ \restore -> do
r <- restore a `onException` sequel
_ <- sequel
return r
-- | A variant of 'bracket' where the return value from the first computation
-- is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
-- | Like 'bracket', but only performs the final action if there was an
-- exception raised by the in-between computation.
bracketOnError
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracketOnError before after thing =
mask $ \restore -> do
a <- before
restore (thing a) `onException` after a
-----
-- |A pattern match failed. The @String@ gives information about the
-- source location of the pattern.
data PatternMatchFail = PatternMatchFail String deriving Typeable
instance Show PatternMatchFail where
showsPrec _ (PatternMatchFail err) = showString err
instance Exception PatternMatchFail
-----
-- |A record selector was applied to a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record selector.
data RecSelError = RecSelError String deriving Typeable
instance Show RecSelError where
showsPrec _ (RecSelError err) = showString err
instance Exception RecSelError
-----
-- |An uninitialised record field was used. The @String@ gives
-- information about the source location where the record was
-- constructed.
data RecConError = RecConError String deriving Typeable
instance Show RecConError where
showsPrec _ (RecConError err) = showString err
instance Exception RecConError
-----
-- |A record update was performed on a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record update.
data RecUpdError = RecUpdError String deriving Typeable
instance Show RecUpdError where
showsPrec _ (RecUpdError err) = showString err
instance Exception RecUpdError
-----
-- |A class method without a definition (neither a default definition,
-- nor a definition in the appropriate instance) was called. The
-- @String@ gives information about which method it was.
data NoMethodError = NoMethodError String deriving Typeable
instance Show NoMethodError where
showsPrec _ (NoMethodError err) = showString err
instance Exception NoMethodError
-----
-- |Thrown when the runtime system detects that the computation is
-- guaranteed not to terminate. Note that there is no guarantee that
-- the runtime system will notice whether any given computation is
-- guaranteed to terminate or not.
data NonTermination = NonTermination deriving Typeable
instance Show NonTermination where
showsPrec _ NonTermination = showString "<<loop>>"
instance Exception NonTermination
-----
-- |Thrown when the program attempts to call @atomically@, from the @stm@
-- package, inside another call to @atomically@.
data NestedAtomically = NestedAtomically deriving Typeable
instance Show NestedAtomically where
showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
instance Exception NestedAtomically
-----
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError
:: Addr# -> a -- All take a UTF8-encoded C string
recSelError s = throw (RecSelError ("No match in record selector "
++ unpackCStringUtf8# s)) -- No location info unfortunately
runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
absentError s = error ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
recConError s = throw (RecConError (untangle s "Missing field in record construction"))
noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
-- GHC's RTS calls this
nonTermination :: SomeException
nonTermination = toException NonTermination
-- GHC's RTS calls this
nestedAtomically :: SomeException
nestedAtomically = toException NestedAtomically
| DavidAlphaFox/ghc | libraries/base/Control/Exception/Base.hs | bsd-3-clause | 14,530 | 0 | 15 | 3,453 | 1,992 | 1,132 | 860 | 170 | 3 |
{-# LANGUAGE Arrows, OverloadedStrings #-}
import FRP.Yampa
import FRP.Yampa.Utilities
import Data.Colour.Names
import Graphics
import Shapes
import Input
type Scalar = Double
type Vector = (Scalar, Scalar)
type Position = (Scalar, Scalar)
main :: IO ()
main = animate "Demo" 640 480 (parseWinInput >>> ((demo >>> render) &&& handleExit))
-- | A ball will rest until the first click.
-- After the click it starts to fall.
-- The ball can be kicked with another click.
-- Ball has no limits, although you can bring it back.
demo :: SF AppInput Ball
demo = switch (constant ball &&& lbp) (const $ kickableBall ball)
gravity :: Vector
gravity = (0, -200)
data Ball = Ball { position :: Position
, velocity :: Vector
}
ball :: Ball
ball = Ball (320, 240) (0, 0)
-- | Kicks the ball in the direction of the specified point
kick :: Position -> Ball -> Ball
kick (tx, ty) (Ball p v) = Ball p (v ^+^ impulse)
where impulse = (tx,ty) ^-^ p
fallingBall :: Ball -> SF a Ball
fallingBall (Ball p0 v0) = lift2 Ball pos vel
where vel = constant gravity >>> imIntegral v0
pos = vel >>> imIntegral p0
kickableBall :: Ball -> SF AppInput Ball
kickableBall b0 =
kSwitch (fallingBall b0) -- initial SF
(first lbpPos >>^ uncurry attach) -- switch trigger
(\_old -> kickableBall . uncurry kick) -- create a new SF
render :: SF Ball Object
render = scene_ . (:[]) ^<< arr renderBall
-- Here is your wooden rectangular ball, son. Go play with your buddies.
where renderBall (Ball pos _) =
circle_ 100 ! pos_ pos
! colour_ red
-- | Returns False when there is a signal to exit
-- You might also want to handle other signals here (e.g. Esc button press)
handleExit :: SF AppInput Bool
handleExit = quitEvent >>> arr isEvent
| pyrtsa/yampa-demos-template | src/Main.hs | bsd-3-clause | 1,890 | 0 | 11 | 501 | 504 | 276 | 228 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GADTs #-}
module DodgerBlue.Types
(CustomDsl(..),
customCmd,
ConcurrentDslCmd(..),
CustomCommandStep) where
import Data.Text (Text)
import Data.Typeable
import Control.Monad.Free.Church
data ConcurrentDslCmd q d next where
NewQueue' :: Typeable a => (q a -> next) -> ConcurrentDslCmd q d next
WriteQueue' :: Typeable a => q a -> a -> next -> ConcurrentDslCmd q d next
TryReadQueue' :: Typeable a => q a -> (Maybe a -> next) -> ConcurrentDslCmd q d next
ReadQueue' :: Typeable a => q a -> (a -> next) -> ConcurrentDslCmd q d next
ForkChild' :: Text -> F (CustomDsl q d) () -> next -> ConcurrentDslCmd q d next
SetPulseStatus' :: Bool -> next -> ConcurrentDslCmd q d next
deriving instance Functor (ConcurrentDslCmd q d)
data CustomDsl q d next =
DslBase (ConcurrentDslCmd q d next)
| DslCustom (d next)
instance Functor d => Functor (CustomDsl q d) where
fmap f (DslBase a) = DslBase $ fmap f a
fmap f (DslCustom a) = DslCustom $ fmap f a
type CustomCommandStep t m = forall a. t (m a) -> m a
customCmd :: (Functor t, MonadFree (CustomDsl q t) m) => t a -> m a
customCmd x = liftF . DodgerBlue.Types.DslCustom $ x
| adbrowne/dodgerblue | src/DodgerBlue/Types.hs | bsd-3-clause | 1,297 | 0 | 10 | 257 | 475 | 250 | 225 | 30 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.