packages feed

mp-1.0.0: src/Mp/Player/Daemon.hs

{-
 *  Programmer:	Piotr Borek
 *  E-mail:     piotrborek@op.pl
 *  Copyright 2014 Piotr Borek
 *
 *  Distributed under the terms of the GPL (GNU Public License)
 *
 *  This program 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-}
{-# LANGUAGE MultiWayIf #-}

module Mp.Player.Daemon (
    runPlayerDaemon,
    printDaemonLog
) where

import           Control.Concurrent
import           Control.Monad
import           Control.Monad.Catch
import           Control.Monad.Trans.Resource
import           Data.List
import           System.Directory
import           System.FilePath.Posix
import           System.IO
import           System.Posix.Daemon

import           Mp.Configuration.Configuration
import           Mp.Player.Server

runPlayerDaemon :: IO ()
runPlayerDaemon = do
    confDir <- configDirFilePath
    let pidFile    = confDir </> "pid"
    let output_log = confDir </> "daemon_log"
    let socName = confDir </> "mp.socket"

    alreadyRunning <- isRunning pidFile
    unless alreadyRunning $ do
        catchAll (removeFile socName) (const $ return ())
        catchAll (removeFile output_log) (const $ return ())
        runDetached (Just pidFile) (ToFile output_log) $
            catchAll
                (void $ runResourceT $ startServerBlocking socName)
                print

        threadDelay 250000

printDaemonLog :: IO ()
printDaemonLog = do
    confDir <- configDirFilePath
    withFile (confDir </> "daemon_log") ReadMode $ \h -> do
        text <- hGetContents h
        forM_ (lines text) $ \s ->
            -- get rid of warning from gst
            if | isSubsequenceOf "gst_structure_free" s -> return ()
               | null s                                 -> return ()
               | True                                   -> putStrLn s