summaryrefslogtreecommitdiff
path: root/Presence/ConfigFiles.hs
blob: ee0d5b8529ae43747e1d9dfac182a0eaec9220cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{-# LANGUAGE OverloadedStrings #-}
module ConfigFiles where

import Data.ByteString.Lazy.Char8 as L
import System.Posix.User
import System.FilePath
import System.Directory
import System.IO
-- import System.IO.Strict
import System.IO.Error
import Control.Exception
import Control.Monad
import Todo
import Control.DeepSeq
import ByteStringOperators

type User = ByteString

configDir = ".presence"
buddyFile = "buddies"
subscriberFile = "subscribers"

buddyPath :: User -> IO String 
buddyPath user = do
    ue <- getUserEntryForName (unpack user)
    return $ (++("/"++configDir++"/"++buddyFile)) $ homeDirectory ue

subscriberPath :: User -> IO String
subscriberPath user = do
    ue <- getUserEntryForName (unpack user)
    return $ (++("/"++configDir++"/"++subscriberFile)) $ homeDirectory ue

createConfigFile tag path = do
    let dir = dropFileName path
    doesDirectoryExist dir >>= flip unless (do
            createDirectory dir 
        )
    withFile path WriteMode $ \h -> 
        L.hPutStrLn h tag

addItem item tag path =
    let doit = do
         handle (\e -> when (isDoesNotExistError e) 
                       (createConfigFile tag path >> doit))
           $ withFile path AppendMode $ \h ->
               L.hPutStrLn h item
    in doit

addBuddy :: User -> ByteString -> IO ()
addBuddy user buddy =
    buddyPath user >>= addItem buddy "<? buddies ?>"

addSubscriber :: User -> ByteString -> IO ()
addSubscriber user subscriber =
    subscriberPath user >>= addItem subscriber "<? subscribers ?>"

getConfigList path = withFile path ReadMode $
    L.hGetContents 
    >=> return . Prelude.tail . L.lines 
    >=> (\a -> seq (rnf a) (return a))

getBuddies :: User -> IO [ByteString]
getBuddies user = buddyPath user >>= getConfigList

getSubscribers :: User -> IO [ByteString]
getSubscribers user = subscriberPath user >>= getConfigList