packages feed

hoovie-0.1: src/Main.hs

{-# LANGUAGE OverloadedStrings #-}
module Main where

import Network.Socket       (withSocketsDo)
import System.Posix.Signals (installHandler, sigPIPE, Handler(Ignore))
import Data.List            (find)
import Data.Maybe           (catMaybes)
import Control.Exception    (bracket)
import Network.Info         (getNetworkInterfaces, NetworkInterface(..), MAC(..), IPv4(..))
import System.Directory     (getUserDocumentsDirectory, getAppUserDataDirectory, createDirectoryIfMissing)
import System.Environment   (getArgs)
import System.FilePath      (joinPath)

import qualified Data.Text               as T
import qualified Data.Configurator       as C
import qualified Data.Configurator.Types as CT

import Hoovie.Server

main :: IO ()
main = withSocketsDo $ do
        _      <- installHandler sigPIPE Ignore Nothing
        args   <- getArgs
        path   <- getDefaultPath
        db     <- getDefaultDatabase

        --files <- listFiles ["/home/peter/movies"] ["avi", "mp4"]
        --let x = map (getTitle . fst) files
        --putStrLn $ concat $ intersperse "\n" x

        config <- C.load $ [ C.Optional "/etc/hoovie.conf", C.Optional "$(HOME)/.hoovie.conf" ] ++ map C.Required args
        port   <- C.lookupDefault 8123   config "listen.port"
        iface  <- C.lookupDefault "auto" config "listen.interface"
        paths  <- C.lookupDefault path   config "paths"
        dbFile <- C.lookupDefault db     config "database"

        iface' <- case iface of
                    "auto" -> getDefaultNetworkInterface
                    iname  -> getInterfaceByName iname
        case iface' of
            Nothing -> do
                putStrLn "The network interface does not exist or has no IP address."
                putStrLn "Please make sure the network is configured correctly."
            Just ni -> do
                bracket (startHoovieServer $ HoovieService ni port (toStringList paths) dbFile)
                        (stopHoovieServer)
                        (\_ -> getChar >> return ())

toStringList :: CT.Value -> [String]
toStringList (CT.List values) = catMaybes $ map CT.convert values
toStringList _ = []

getDefaultDatabase :: IO FilePath
getDefaultDatabase = do
    path <- getAppUserDataDirectory "hoovie"
    createDirectoryIfMissing True path
    return $ joinPath [path, "hoovie.db"]

getDefaultPath :: IO CT.Value
getDefaultPath = do
    path <- getUserDocumentsDirectory
    return $ CT.List [CT.String $ T.pack path]

getDefaultNetworkInterface :: IO (Maybe NetworkInterface)
getDefaultNetworkInterface = do
    interfaces <- getNetworkInterfaces
    return $ find (\i -> mac i /= MAC 0 0 0 0 0 0 && ipv4 i /= IPv4 0) interfaces

getInterfaceByName :: String -> IO (Maybe NetworkInterface)
getInterfaceByName interface = do
    interfaces <- getNetworkInterfaces
    return $ find (\i -> name i == interface && mac i /= MAC 0 0 0 0 0 0 && ipv4 i /= IPv4 0) interfaces