1 {-# LANGUAGE BangPatterns #-}
2 {-# LANGUAGE DoAndIfThenElse #-}
7 import Control.Concurrent (threadDelay)
8 import Control.Exception.Base (bracket)
9 import Control.Monad (when)
10 import Data.List (isPrefixOf)
11 import Data.Maybe (isNothing)
12 import Data.Monoid ((<>))
16 import System.Console.CmdArgs (def)
17 import System.Directory (doesFileExist)
18 import System.Exit (ExitCode(..), exitWith)
19 import System.FilePath ((</>))
21 BufferMode (NoBuffering),
30 import System.IO.Error (catchIOError)
31 import System.Timeout (timeout)
33 import CommandLine (get_args)
34 import Configuration (Configuration(..), merge_optional)
39 import FeedHosts (FeedHosts(..))
40 import qualified OptionalConfiguration as OC (
41 OptionalConfiguration(..),
43 import Terminal (hPutRedLn, putGreenLn)
44 import TSN.Xml (parse_xmlfid, xml_prologue)
47 report_error :: String -> IO ()
48 report_error = hPutRedLn stderr
51 recv_line :: Handle -> IO String
58 save_document :: Configuration -> String -> IO ()
59 save_document cfg doc = do
62 report_error "ERROR: document missing XML_File_ID element."
64 already_exists <- doesFileExist path
65 when already_exists $ do
66 let msg = "WARNING: file " ++ path ++ " already exists. Overwriting."
70 xmlfid = fmap show (parse_xmlfid doc)
71 filename = fmap (++ ".xml") xmlfid
72 maybe_path = fmap ((output_directory cfg) </>) filename
74 -- | Loop forever, writing the buffer to file whenever a new XML
76 loop :: Configuration -> Handle -> [String] -> IO ()
77 loop !cfg !h !buffer = do
80 if (xml_prologue `isPrefixOf` line && not (null buffer))
82 -- This is the beginning of a new document, and we have an "old"
83 -- one to save. The buffer is in reverse (newest first) order,
84 -- though, so we have to reverse it first. We then concatenate all
85 -- of its lines into one big string.
86 let document = concat $ reverse buffer
87 save_document cfg document
88 loop cfg h [line] -- empty the buffer before looping again
90 loop cfg h (line : buffer) -- append line to the head of the buffer and loop
93 log_in :: Configuration -> Handle -> IO ()
95 prompt1 <- recv_prompt h
97 if prompt1 /= username_prompt then
98 report_error "ERROR: didn't receive username prompt."
100 send_line h (username cfg)
101 prompt2 <- recv_prompt h
103 if prompt2 /= password_prompt then
104 report_error "ERROR: didn't receive password prompt."
106 send_line h (password cfg)
107 _ <- recv_line h -- "The Sports Network"
110 username_prompt = "Username: "
111 password_prompt = "Password: "
113 send_line :: Handle -> String -> IO ()
115 hPutStr h' (s ++ "\r\n")
118 recv_chars :: Int -> Handle -> IO String
120 s <- sequence [ hGetChar h' | _ <- [1..n] ]
124 recv_prompt :: Handle -> IO String
125 recv_prompt = recv_chars 10
127 connect_and_loop :: Configuration -> String -> IO ()
128 connect_and_loop cfg host = do
129 putStrLn $ "Connecting to " ++ host ++ "..."
130 bracket acquire_handle release_handle action
134 five_seconds = 5000000
136 acquire_handle = connectTo host (PortNumber 4500)
137 release_handle = hClose
139 -- No buffering anywhere.
140 hSetBuffering h NoBuffering
142 -- The feed is often unresponsive after we send out username. It
143 -- happens in a telnet session, too (albeit less frequently?),
144 -- so there might be a bug on their end.
146 -- If we dump the packets with tcpdump, it looks like their
147 -- software is getting confused: they send us some XML in
148 -- the middle of the log-in procedure. In any case, the easiest
149 -- fix is to disconnect and try again.
151 login_worked <- timeout five_seconds $ log_in cfg h
153 Nothing -> putStrLn "Login timed out (5s)."
154 Just _ -> loop cfg h []
157 -- | A wrapper around threadDelay which takes seconds instead of
158 -- microseconds as its argument.
159 thread_sleep :: Int -> IO ()
160 thread_sleep seconds = do
161 let microseconds = seconds * (10 ^ (6 :: Int))
162 threadDelay microseconds
170 -- Merge the config file options with the command-line ones,
171 -- prefering the command-line ones.
172 let opt_config = rc_cfg <> cmd_cfg
174 -- This is necessary because if the user specifies an empty list of
175 -- hostnames in e.g. the config file, we want to bail rather than
176 -- fall back on the default list (which gets merged from a
177 -- Configuration below).
178 when (null $ get_feed_hosts (OC.feed_hosts opt_config)) $ do
179 report_error "ERROR: no feed hosts supplied."
180 exitWith (ExitFailure exit_no_feed_hosts)
182 when (isNothing (OC.password opt_config)) $ do
183 report_error "ERROR: no password supplied."
184 exitWith (ExitFailure exit_no_password)
186 when (isNothing (OC.username opt_config)) $ do
187 report_error "ERROR: no username supplied."
188 exitWith (ExitFailure exit_no_username)
190 -- Finally, update a default config with any options that have been
191 -- set in either the config file or on the command-line.
192 let cfg = (def :: Configuration) `merge_optional` opt_config
194 hSetBuffering stderr NoBuffering
195 hSetBuffering stdout NoBuffering
200 round_robin :: Configuration -> Int -> IO ()
201 round_robin cfg feed_host_idx = do
202 let hosts = get_feed_hosts $ feed_hosts cfg
203 let host = hosts !! feed_host_idx
204 catchIOError (connect_and_loop cfg host) (report_error . show)
205 thread_sleep 10 -- Wait 10s before attempting to reconnect.
206 round_robin cfg $ (feed_host_idx + 1) `mod` (length hosts)