-
-
Save benjacoblee/92ef72f515346348ec2f092e4cf9245f to your computer and use it in GitHub Desktop.
This file contains 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
import strutils | |
import system | |
import std/httpclient | |
import strformat | |
import std/xmltree | |
from htmlparser import parseHtml | |
import nimquery | |
import sugar | |
import sequtils | |
import unpack | |
import std/parseopt | |
import std/tables | |
const tbl = { | |
"latest": "https://www.channelnewsasia.com/api/v1/rss-outbound-feed?_format=xml", | |
"asia": "https://www.channelnewsasia.com/api/v1/rss-outbound-feed?_format=xml&category=6511", | |
"business": "https://www.channelnewsasia.com/api/v1/rss-outbound-feed?_format=xml&category=6936", | |
"singapore": "https://www.channelnewsasia.com/api/v1/rss-outbound-feed?_format=xml&category=10416", | |
"sport": "https://www.channelnewsasia.com/api/v1/rss-outbound-feed?_format=xml&category=10296", | |
"world": "https://www.channelnewsasia.com/api/v1/rss-outbound-feed?_format=xml&category=6311" | |
}.toOrderedTable | |
let keys: seq[string] = tbl.keys.toSeq.map((k) => fmt"<{k}>") | |
var | |
p = initOptParser() | |
proc getFeed(key: string): void | |
proc genUsageText(isErr: bool): string | |
while true: | |
p.next() | |
case p.kind | |
of cmdEnd: | |
quit(genUsageText(isErr = false), 0) | |
of cmdShortOption, cmdLongOption: break | |
of cmdArgument: | |
if tbl.hasKey(p.key): | |
getFeed(p.key) | |
quit(0) | |
else: | |
quit(genUsageText(isErr = true), 0) | |
proc getFeed(key: string): void = | |
let client = newHttpClient() | |
let response = client.request(tbl[key], httpMethod = HttpGet) | |
let xml = parseHtml(response.body) | |
echo fmt"## {key} News".toUpper() & "\n" | |
for item in xml.querySelectorAll("item"): | |
let item = item.innerText.strip().split("\n").map((s) => s.strip()) | |
item.unpackSeq(title, link) | |
echo &"{title}\n{link}\n" | |
proc genUsageText(isErr: bool): string = | |
let keysStr = keys.join(" ") | |
let usageStr = fmt"Usage: $ cna {keysStr}" | |
if isErr: | |
return fmt""" | |
Error: invalid category | |
{usageStr}""" | |
return fmt"""{usageStr}""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment