69 lines
1.4 KiB
Nim
69 lines
1.4 KiB
Nim
|
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)
|