~reesmichael1/roman

ref: 7a95a17d006e08e02f638b15caba2a56ce590741 roman/src/romanpkg/feeds.nim -rw-r--r-- 6.3 KiB
7a95a17dMichael Rees Allow toggling read status from post selection 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
when defined(internalRenderer):
  {.experimental: "parallel".}
  import threadpool

import asyncdispatch
import httpclient
import options
import sequtils
import streams
import strutils
import tables
import terminal
import uri
import xmlparser
import xmltree

import fab
import FeedNim / [atom, rss]

import errors
import posts
import termask
import types

from config import conf


const atomNames = ["index.atom", "feed.atom", "atom.xml"]
const rssNames = ["index.rss", "feed.rss", "rss.xml"]


proc updateUnread*(feed: var Feed) {.raises: [].} =
  feed.unreadPosts = feed.posts.filterIt(not it.read).len


proc detectFeedKind(content: string): FeedKind {.raises: [RomanError].} =
  var xml: XmlNode
  try:
    xml = parseXml(newStringStream(content))
  except:
    let msg = getCurrentExceptionMsg()
    raise newException(RomanError, "could not parse feed: " & msg)

  # A well-formed RSS feed has an <rss> tag,
  # while a well-formed Atom feed has a <feed> tag
  let feed = xml.findAll("feed")
  let rss = xml.findAll("rss")
  if feed.len > 0 and rss.len == 0:
    return FeedKind.Atom
  if feed.len == 0 and rss.len > 0:
    return FeedKind.RSS

  return FeedKind.Unknown


proc guessFeedKind(url: string): FeedKind {.raises: [].} =
  # If we can't uniquely identify one or the other, try some dirty tricks here.
  # If all else fails, return FeedKind.Unknown again, which will
  # ask the user to tell us which type of feed it is.
  let parsed = parseURI(url)

  if atomNames.anyIt(parsed.path.contains(it)):
    return FeedKind.Atom
  elif rssNames.anyIt(parsed.path.contains(it)):
    return FeedKind.RSS

  if parsed.path.len > 3 and parsed.path[
      parsed.path.len-3..parsed.path.high] == "rss":
    return FeedKind.RSS

  if parsed.path.len > 4 and parsed.path[
      parsed.path.len-4..parsed.path.high] == "atom":
    return FeedKind.Atom

  return FeedKind.Unknown


# Show the number of unread posts in the feed display
proc formatTitle*(feed: Feed): string {.raises: [].} =
  feed.title & " [" & $feed.unreadPosts & "/" & $feed.posts.len & "]"


proc displayFeed*(feed: var Feed) {.raises: [RomanError, InterruptError].} =
  try:
    under(feed.title & "\n", sty = {styleBright})

    var display = initTable[ref string, ref string]()
    var titles: seq[ref string]

    proc toggleRead(posts: seq[Post]): proc(index: int) {.closure, gcSafe.} =
      return proc(index: int) {.closure, gcSafe.} =
        var post = posts[index]
        post.toggleRead()
        titles[index][] = post.formatTitle()
        display[titles[index]] = titles[index]

    var callbacks = newTable[char, proc(index: int) {.closure, gcSafe.}]()
    callbacks[conf.toggleRead] = toggleRead(feed.posts)

    while true:
      display = initTable[ref string, ref string]()
      titles = @[]
      for p in feed.posts:
        var title = new string
        title[] = p.title
        var formatted = new string
        formatted[] = p.formatTitle()
        titles.add(title)
        display[title] = formatted
      let selectedTitle = promptList[ref string, ref string]("Select Post",
          titles, show = 10, displayNames = display, callbacks = callbacks)
      if selectedTitle.isNone():
        raise newException(InterruptError, "no post selected")
      let title = selectedTitle.unsafeGet()
      var post = feed.posts.filterIt(it.title == title[])[0]
      displayPost(post)
      post.markAsRead()

  except IOError as e:
    raise newException(RomanError, "could not write to the terminal: " & e.msg)
  except ValueError as e:
    raise newException(RomanError, "could not set terminal style: " & e.msg)
  except InterruptError as e:
    # Update the read/unread counts in the feed
    # before returning to feed selection
    feed.updateUnread()
    raise newException(InterruptError, e.msg)
  except Exception as e:
    raise newException(RomanError, "error loading callbacks table: " & e.msg)


proc buildFeedFromContentAndSub(content: string, sub: Subscription): Feed {.
    raises: [RomanError].} =
  result = new(Feed)
  try:
    var feedKind = sub.feedKind
    if feedKind == Unknown:
      feedKind = detectFeedKind(content)
    if feedKind == Unknown:
      feedKind = guessFeedKind(sub.url)
    case feedKind:
    of FeedKind.RSS:
      let rawFeed = parseRSS(content)
      if sub.name.len > 0:
        result.title = sub.name
      else:
        result.title = rawFeed.title
      result.posts = rawFeed.items.mapIt(postFromRSSItem(it))
    of FeedKind.Atom:
      let rawFeed = parseAtom(content)
      if sub.name.len > 0:
        result.title = sub.name
      else:
        result.title = rawFeed.title.text
      result.posts = rawFeed.entries.mapIt(postFromAtomEntry(it))
    of Unknown:
      raise newException(RomanError,
        "could not identify feed as RSS or Atom, please use --type option")
    result.kind = feedKind
    result.updateUnread()
  except ValueError:
    raise newException(RomanError, sub.url & " is not a valid URL")
  except:
    let msg = getCurrentExceptionMsg()
    raise newException(RomanError,
      "while accessing " & sub.url & ": " & msg)


proc getFeed*(sub: Subscription): Feed {.raises: [RomanError].} =
  try:
    var client = newHttpClient()
    let content = client.getContent(sub.url)
    result = buildFeedFromContentAndSub(content, sub)
  except Exception as e:
    raise newException(RomanError, e.msg)


proc asyncFeedsLoader(subs: seq[Subscription]): Future[seq[string]] {.async.} =
  var futures = newSeq[Future[string]](subs.len)
  result = newSeq[string](subs.len)
  for ix, sub in subs:
    var client = newAsyncHttpClient()
    futures[ix] = client.getContent(sub.url)

  result = await all(futures)


proc getFeeds*(subs: seq[Subscription]): seq[Feed] {.raises: [RomanError].} =
  result = newSeq[Feed](subs.len)
  var contents: seq[string]
  try:
    contents = waitFor asyncFeedsLoader(subs)
    when defined(internalRenderer):
      var responses = newSeq[FlowVar[ref Feed]](subs.len)
      parallel:
        for ix, content in contents:
          responses[ix] = spawn buildFeedFromContentAndSub(content, subs[ix])

      sync()
      for ix, response in responses:
        result[ix] = (^response)[]

    else:
      for ix, content in contents:
        result[ix] = buildFeedFromContentAndSub(content, subs[ix])

  except:
    raise newException(RomanError, "error in loading feeds: " &
        getCurrentExceptionMsg())