multiFeedParsing.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #!/usr/bin/env python3
  2. # vim: tabstop=4 shiftwidth=4 expandtab
  3. import urllib.parse
  4. import re
  5. import feedparser
  6. import time
  7. from datetime import datetime
  8. urllib.parse.uses_relative.append("gemini")
  9. urllib.parse.uses_netloc.append("gemini")
  10. # collapse whitespace
  11. def _cw(text):
  12. return re.sub(r'\s', ' ', text)
  13. def parsegemsub(feed, baseurl):
  14. entries = []
  15. authorpattern = r'^#\s*([^#\r\n]+)'
  16. entriespattern = r'^=>\s*(\S+)\s+(\d{4}-\d{2}-\d{2})[^\r\n\S]*([^\r\n]*)'
  17. entriespatternmatches = re.findall(entriespattern, feed, re.MULTILINE)
  18. authorpatternmatch = re.findall(authorpattern, feed, re.MULTILINE)
  19. if authorpatternmatch:
  20. author = authorpatternmatch[0]
  21. else:
  22. return None
  23. for entrypatternmatch in entriespatternmatches:
  24. # Get our YYYY-MM-DD string, add time of day, parse to datetime.datetime, convert to unix timestamp and cast to int
  25. try:
  26. updated = int(datetime.timestamp(datetime.strptime(entrypatternmatch[1] + " 12:00:00", "%Y-%m-%d %H:%M:%S")))
  27. except:
  28. continue
  29. # A gemsub feed can often have relative links, we'll have to absolutize them
  30. link = urllib.parse.urljoin(baseurl, entrypatternmatch[0]).replace('/..','').replace('/.','')
  31. title = entrypatternmatch[2] if entrypatternmatch[2] else entrypatternmatch[1]
  32. entries.append(FeedEntry(baseurl, author, updated, title, link))
  33. return entries
  34. def parsetwtxt(feed, baseurl):
  35. entries = []
  36. authorpattern = r'^#\s*nick\s*=\s*(\S+)'
  37. # This is a naive match, but we'll only keep those that validate eventually
  38. entriespattern = r'^(\S+)\t([^\r\n]+)'
  39. entriespatternmatches = re.findall(entriespattern, feed, re.MULTILINE)
  40. authorpatternmatch = re.findall(authorpattern, feed, re.MULTILINE)
  41. if authorpatternmatch:
  42. author = authorpatternmatch[0]
  43. else:
  44. author = baseurl
  45. for entrypatternmatch in entriespatternmatches:
  46. # Get our datetime string, parse to datetime.datetime, convert to unix timestamp and cast to int
  47. try:
  48. posted = int(datetime.timestamp(datetime.strptime(entrypatternmatch[0], "%Y-%m-%dT%H:%M:%S%z")))
  49. except:
  50. continue
  51. entries.append(TwtxtEntry(feedurl = baseurl, author = author, posted = posted, twt = entrypatternmatch[1]))
  52. return entries
  53. def parsexml(feed, baseurl):
  54. scheme = baseurl.split("://")[0]
  55. entries = []
  56. parsedfeed = feedparser.parse(feed)
  57. # Let's set author name, or lacking that use the feed title.
  58. feedauthor = _cw(parsedfeed['feed']['author_detail']['name']) if parsedfeed['feed'].has_key('author_detail') and parsedfeed['feed']['author_detail'].has_key('name') else None
  59. feedtitle = _cw(parsedfeed['feed']['title']) if parsedfeed['feed'].has_key('title') else None
  60. if not feedauthor and feedtitle:
  61. feedauthor = feedtitle
  62. if not parsedfeed.has_key('entries'):
  63. return None
  64. for entry in parsedfeed['entries']:
  65. try: # The feed could miss all sorts of fields...
  66. if entry.has_key('author_detail') and entry['author_detail'].has_key('name'):
  67. author = _cw(entry['author_detail']['name'])
  68. elif feedauthor:
  69. author = feedauthor
  70. else:
  71. continue
  72. updated = int(time.mktime(entry['updated_parsed'])) # Seconds since epoch
  73. title = _cw(entry['title'])
  74. if len(entry['links']) >= 1:
  75. link = [l for l in entry['links'] if l['href'].startswith(scheme)][0]['href']
  76. else:
  77. link = _cw(entry['link'])
  78. if not link:
  79. continue
  80. link = urllib.parse.urljoin(baseurl, link).replace('/..','').replace('/.','')
  81. except:
  82. continue
  83. entries.append(FeedEntry(baseurl, author, updated, title, link))
  84. return entries
  85. class FeedEntry():
  86. def __init__(self, feedurl, author, updated, title, link):
  87. self.feedurl = feedurl
  88. self.author = author
  89. self.updated = updated
  90. self.title = title
  91. self.link = link
  92. class TwtxtEntry():
  93. def __init__(self, feedurl, author, posted, twt):
  94. self.feedurl = feedurl
  95. self.author = author
  96. self.posted = posted
  97. self.twt = twt