From ccc1bbe59b9a19b2a61e3f0944a793fc77a3afc3 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Sat, 6 Feb 2016 07:36:53 -0800 Subject: [PATCH] Add twtxt parsing library --- src/.gitignore | 1 + src/twtxt.nim | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/twtxt.nims | 1 + 3 files changed, 70 insertions(+) create mode 100644 src/.gitignore create mode 100644 src/twtxt.nim create mode 100644 src/twtxt.nims diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..8fa3a67 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1 @@ +twtxt diff --git a/src/twtxt.nim b/src/twtxt.nim new file mode 100644 index 0000000..433b953 --- /dev/null +++ b/src/twtxt.nim @@ -0,0 +1,68 @@ +import json, httpclient, strutils, times + +const + ISOTime*: string = "yyyy-MM-dd'T'HH:mm:ss'.000000'zzz" + +type + Tweet* = object of RootObj + date*: TimeInfo + message*: string + username*: string + +proc `$`*(t: Tweet): string = + t.date.format(ISOTime) & "\t" & t.message + +proc `%`*(t: Tweet): JsonNode = + %* + { + "date": t.date.format(ISOTime), + "message": t.message, + "username": t.username, + } + +proc `%`*(s: seq[Tweet]): JsonNode = + result = newJArray() + + for t in s.items(): + result.add %t + +proc parseTweet*(user, inp: string): Tweet = + let + splitTweet = inp.split '\t' + + if splitTweet.len != 2: + raise newException(ValueError, "Invalid tweet") + + let + tdate = splitTweet[0].parse(ISOTime) + message = splitTweet[1] + + Tweet(date: tdate, + message: message, + username: user) + +proc getTweetsFrom*(url: string, username: string): seq[Tweet] = + var res = newSeq[Tweet]() + + let body = url.getContent() + + for line in body.splitLines().items(): + if line.len > 0: + res.add(username.parseTweet(line)) + + return res + +when isMainModule: + let + now = getLocalTime(getTime()) + t: Tweet = Tweet(date: now, + message: "Test message", + username: "Xena") + + const testInp = "2016-02-05T19:30:46.964649+00:00 This is a tweet via twtxt!" + + echo "xena".parseTweet testInp + + echo pretty(%t, 4) + + echo pretty(%getTweetsFrom("https://xena.greedo.xeserv.us/files/xena.txt", "xena"), 4) diff --git a/src/twtxt.nims b/src/twtxt.nims new file mode 100644 index 0000000..fc86e83 --- /dev/null +++ b/src/twtxt.nims @@ -0,0 +1 @@ +--define:ssl