Created
July 6, 2010 03:01
-
-
Save puffnfresh/464947 to your computer and use it in GitHub Desktop.
Haskell module to convert a Twitter message (tweet) to HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {- | | |
| Module : TweetHTML | |
| Description : Convert a Twitter message (tweet) to HTML | |
| Copyright : (c) Brian McKenna | |
| License : MIT | |
| -} | |
| module TweetHTML (tweetHTML) where | |
| import Data.Char | |
| import Text.Printf | |
| import Text.ParserCombinators.Parsec | |
| data Markers = Plain | Mention | Hashtag | Link | |
| -- Convert a parsed tweet into HTML | |
| homeURL = "http://twitter.com/" | |
| searchURL = homeURL ++ "?search?q=%23" | |
| toHTML (Hashtag, a) = printf "<a href=\"%s\">#%s</a>" (searchURL ++ a) a | |
| toHTML (Mention, a) = printf "@<a href=\"%s\">%s</a>" (homeURL ++ a) a | |
| toHTML (Link, a) = printf "<a href=\"%s\">%s</a>" a a | |
| toHTML (_, a) = a | |
| tweetHTML tweet = case (parse message "" tweet) of | |
| Right xs -> concatMap toHTML xs | |
| -- Parse a Twitter message (tweet) | |
| identifier = many1 (alphaNum <|> char '_') | |
| notSpace = satisfy (not . isSpace) | |
| link = do | |
| protocol <- string "http://" | |
| location <- many1 notSpace | |
| return (Link, protocol ++ location) | |
| hashtag = do | |
| char '#' | |
| ident <- identifier | |
| return (Hashtag, ident) | |
| mention = do | |
| char '@' | |
| ident <- identifier | |
| return (Mention, ident) | |
| word = do | |
| word <- many1 notSpace | |
| return (Plain, word) | |
| whitespace = do | |
| ws <- many1 space | |
| return (Plain, ws) | |
| message = manyTill (choice [whitespace, link, mention, hashtag, word]) eof | |
| -- Show an example | |
| main = putStrLn $ tweetHTML | |
| "This is a test #tweet from @puffnfresh http://brianmckenna.org/" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment