parse.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. # coding: utf-8
  2. """
  3. Everything related to parsing links from bookmark services.
  4. For a list of supported services, see the README.md.
  5. For examples of supported files see examples/.
  6. Parsed link schema: {
  7. 'url': 'https://example.com/example/?abc=123&xyc=345#lmnop',
  8. 'domain': 'example.com',
  9. 'base_url': 'example.com/example/',
  10. 'timestamp': '15442123124234',
  11. 'tags': 'abc,def',
  12. 'title': 'Example.com Page Title',
  13. 'sources': ['ril_export.html', 'downloads/getpocket.com.txt'],
  14. }
  15. """
  16. import re
  17. import json
  18. import urllib
  19. from collections import OrderedDict
  20. import xml.etree.ElementTree as etree
  21. from datetime import datetime
  22. from util import (
  23. domain,
  24. base_url,
  25. str_between,
  26. get_link_type,
  27. fetch_page_title,
  28. URL_REGEX,
  29. )
  30. def get_parsers(file):
  31. """return all parsers that work on a given file, defaults to all of them"""
  32. return OrderedDict([
  33. ('pocket', parse_pocket_export),
  34. ('pinboard', parse_json_export),
  35. ('bookmarks', parse_bookmarks_export),
  36. ('rss', parse_rss_export),
  37. ('pinboard_rss', parse_pinboard_rss_feed),
  38. ('shaarli_rss', parse_shaarli_rss_export),
  39. ('medium_rss', parse_medium_rss_feed),
  40. ('plain_text', parse_plain_text),
  41. ])
  42. def parse_links(path):
  43. """parse a list of links dictionaries from a bookmark export file"""
  44. links = []
  45. with open(path, 'r', encoding='utf-8') as file:
  46. for parser_name, parser_func in get_parsers(file).items():
  47. # otherwise try all parsers until one works
  48. try:
  49. links += list(parser_func(file))
  50. if links:
  51. break
  52. except (ValueError, TypeError, IndexError, AttributeError, etree.ParseError):
  53. # parser not supported on this file
  54. pass
  55. return links, parser_name
  56. def parse_pocket_export(html_file):
  57. """Parse Pocket-format bookmarks export files (produced by getpocket.com/export/)"""
  58. html_file.seek(0)
  59. pattern = re.compile("^\\s*<li><a href=\"(.+)\" time_added=\"(\\d+)\" tags=\"(.*)\">(.+)</a></li>", re.UNICODE)
  60. for line in html_file:
  61. # example line
  62. # <li><a href="http://example.com/ time_added="1478739709" tags="tag1,tag2">example title</a></li>
  63. match = pattern.search(line)
  64. if match:
  65. fixed_url = match.group(1).replace('http://www.readability.com/read?url=', '') # remove old readability prefixes to get original url
  66. time = datetime.fromtimestamp(float(match.group(2)))
  67. info = {
  68. 'url': fixed_url,
  69. 'domain': domain(fixed_url),
  70. 'base_url': base_url(fixed_url),
  71. 'timestamp': str(time.timestamp()),
  72. 'tags': match.group(3),
  73. 'title': match.group(4).replace(' — Readability', '').replace('http://www.readability.com/read?url=', '') or fetch_page_title(fixed_url),
  74. 'sources': [html_file.name],
  75. }
  76. info['type'] = get_link_type(info)
  77. yield info
  78. def parse_json_export(json_file):
  79. """Parse JSON-format bookmarks export files (produced by pinboard.in/export/, or wallabag)"""
  80. json_file.seek(0)
  81. json_content = json.load(json_file)
  82. for line in json_content:
  83. # example line
  84. # {"href":"http:\/\/www.reddit.com\/r\/example","description":"title here","extended":"","meta":"18a973f09c9cc0608c116967b64e0419","hash":"910293f019c2f4bb1a749fb937ba58e3","time":"2014-06-14T15:51:42Z","shared":"no","toread":"no","tags":"reddit android"}]
  85. if line:
  86. erg = line
  87. if erg.get('timestamp'):
  88. timestamp = str(erg['timestamp']/10000000) # chrome/ff histories use a very precise timestamp
  89. elif erg.get('time'):
  90. timestamp = str(datetime.strptime(erg['time'].split(',', 1)[0], '%Y-%m-%dT%H:%M:%SZ').timestamp())
  91. elif erg.get('created_at'):
  92. timestamp = str(datetime.strptime(erg['created_at'], '%Y-%m-%dT%H:%M:%S%z').timestamp())
  93. else:
  94. timestamp = str(datetime.now().timestamp())
  95. if erg.get('href'):
  96. url = erg['href']
  97. else:
  98. url = erg['url']
  99. if erg.get('description'):
  100. title = (erg.get('description') or '').replace(' — Readability', '')
  101. else:
  102. title = erg['title'].strip()
  103. info = {
  104. 'url': url,
  105. 'domain': domain(url),
  106. 'base_url': base_url(url),
  107. 'timestamp': timestamp,
  108. 'tags': erg.get('tags') or '',
  109. 'title': title or fetch_page_title(url),
  110. 'sources': [json_file.name],
  111. }
  112. info['type'] = get_link_type(info)
  113. yield info
  114. def parse_rss_export(rss_file):
  115. """Parse RSS XML-format files into links"""
  116. rss_file.seek(0)
  117. items = rss_file.read().split('</item>\n<item>')
  118. for item in items:
  119. # example item:
  120. # <item>
  121. # <title><![CDATA[How JavaScript works: inside the V8 engine]]></title>
  122. # <category>Unread</category>
  123. # <link>https://blog.sessionstack.com/how-javascript-works-inside</link>
  124. # <guid>https://blog.sessionstack.com/how-javascript-works-inside</guid>
  125. # <pubDate>Mon, 21 Aug 2017 14:21:58 -0500</pubDate>
  126. # </item>
  127. trailing_removed = item.split('</item>', 1)[0]
  128. leading_removed = trailing_removed.split('<item>', 1)[-1]
  129. rows = leading_removed.split('\n')
  130. def get_row(key):
  131. return [r for r in rows if r.startswith('<{}>'.format(key))][0]
  132. title = str_between(get_row('title'), '<![CDATA[', ']]').strip()
  133. url = str_between(get_row('link'), '<link>', '</link>')
  134. ts_str = str_between(get_row('pubDate'), '<pubDate>', '</pubDate>')
  135. time = datetime.strptime(ts_str, "%a, %d %b %Y %H:%M:%S %z")
  136. info = {
  137. 'url': url,
  138. 'domain': domain(url),
  139. 'base_url': base_url(url),
  140. 'timestamp': str(datetime.now().timestamp()),
  141. 'tags': '',
  142. 'title': title or fetch_page_title(url),
  143. 'sources': [rss_file.name],
  144. }
  145. info['type'] = get_link_type(info)
  146. yield info
  147. def parse_shaarli_rss_export(rss_file):
  148. """Parse Shaarli-specific RSS XML-format files into links"""
  149. rss_file.seek(0)
  150. entries = rss_file.read().split('<entry>')[1:]
  151. for entry in entries:
  152. # example entry:
  153. # <entry>
  154. # <title>Aktuelle Trojaner-Welle: Emotet lauert in gefälschten Rechnungsmails | heise online</title>
  155. # <link href="https://www.heise.de/security/meldung/Aktuelle-Trojaner-Welle-Emotet-lauert-in-gefaelschten-Rechnungsmails-4291268.html" />
  156. # <id>https://demo.shaarli.org/?cEV4vw</id>
  157. # <published>2019-01-30T06:06:01+00:00</published>
  158. # <updated>2019-01-30T06:06:01+00:00</updated>
  159. # <content type="html" xml:lang="en"><![CDATA[<div class="markdown"><p>&#8212; <a href="https://demo.shaarli.org/?cEV4vw">Permalink</a></p></div>]]></content>
  160. # </entry>
  161. trailing_removed = entry.split('</entry>', 1)[0]
  162. leading_removed = trailing_removed.strip()
  163. rows = leading_removed.split('\n')
  164. def get_row(key):
  165. return [r.strip() for r in rows if r.strip().startswith('<{}'.format(key))][0]
  166. title = str_between(get_row('title'), '<title>', '</title>').strip()
  167. url = str_between(get_row('link'), '<link href="', '" />')
  168. ts_str = str_between(get_row('published'), '<published>', '</published>')
  169. time = datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%S%z")
  170. info = {
  171. 'url': url,
  172. 'domain': domain(url),
  173. 'base_url': base_url(url),
  174. 'timestamp': str(time.timestamp()),
  175. 'tags': '',
  176. 'title': title or fetch_page_title(url),
  177. 'sources': [rss_file.name],
  178. }
  179. info['type'] = get_link_type(info)
  180. yield info
  181. def parse_bookmarks_export(html_file):
  182. """Parse netscape-format bookmarks export files (produced by all browsers)"""
  183. html_file.seek(0)
  184. pattern = re.compile("<a href=\"(.+?)\" add_date=\"(\\d+)\"[^>]*>(.+)</a>", re.UNICODE | re.IGNORECASE)
  185. for line in html_file:
  186. # example line
  187. # <DT><A HREF="https://example.com/?q=1+2" ADD_DATE="1497562974" LAST_MODIFIED="1497562974" ICON_URI="https://example.com/favicon.ico" ICON="data:image/png;base64,...">example bookmark title</A>
  188. match = pattern.search(line)
  189. if match:
  190. url = match.group(1)
  191. time = datetime.fromtimestamp(float(match.group(2)))
  192. info = {
  193. 'url': url,
  194. 'domain': domain(url),
  195. 'base_url': base_url(url),
  196. 'timestamp': str(time.timestamp()),
  197. 'tags': "",
  198. 'title': match.group(3).strip() or fetch_page_title(url),
  199. 'sources': [html_file.name],
  200. }
  201. info['type'] = get_link_type(info)
  202. yield info
  203. def parse_pinboard_rss_feed(rss_file):
  204. """Parse Pinboard RSS feed files into links"""
  205. rss_file.seek(0)
  206. root = etree.parse(rss_file).getroot()
  207. items = root.findall("{http://purl.org/rss/1.0/}item")
  208. for item in items:
  209. url = item.find("{http://purl.org/rss/1.0/}link").text
  210. tags = item.find("{http://purl.org/dc/elements/1.1/}subject").text
  211. title = item.find("{http://purl.org/rss/1.0/}title").text.strip()
  212. ts_str = item.find("{http://purl.org/dc/elements/1.1/}date").text
  213. # = 🌈🌈🌈🌈
  214. # = 🌈🌈🌈🌈
  215. # = 🏆🏆🏆🏆
  216. # Pinboard includes a colon in its date stamp timezone offsets, which
  217. # Python can't parse. Remove it:
  218. if ":" == ts_str[-3:-2]:
  219. ts_str = ts_str[:-3]+ts_str[-2:]
  220. time = datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%S%z")
  221. info = {
  222. 'url': url,
  223. 'domain': domain(url),
  224. 'base_url': base_url(url),
  225. 'timestamp': str(time.timestamp()),
  226. 'tags': tags,
  227. 'title': title or fetch_page_title(url),
  228. 'sources': [rss_file.name],
  229. }
  230. info['type'] = get_link_type(info)
  231. yield info
  232. def parse_medium_rss_feed(rss_file):
  233. """Parse Medium RSS feed files into links"""
  234. rss_file.seek(0)
  235. root = etree.parse(rss_file).getroot()
  236. items = root.find("channel").findall("item")
  237. for item in items:
  238. # for child in item:
  239. # print(child.tag, child.text)
  240. url = item.find("link").text
  241. title = item.find("title").text.strip()
  242. ts_str = item.find("pubDate").text
  243. time = datetime.strptime(ts_str, "%a, %d %b %Y %H:%M:%S %Z")
  244. info = {
  245. 'url': url,
  246. 'domain': domain(url),
  247. 'base_url': base_url(url),
  248. 'timestamp': str(time.timestamp()),
  249. 'tags': '',
  250. 'title': title or fetch_page_title(url),
  251. 'sources': [rss_file.name],
  252. }
  253. info['type'] = get_link_type(info)
  254. yield info
  255. def parse_plain_text(text_file):
  256. """Parse raw links from each line in a text file"""
  257. text_file.seek(0)
  258. text_content = text_file.readlines()
  259. for line in text_content:
  260. if line:
  261. urls = re.findall(URL_REGEX, line)
  262. for url in urls:
  263. url = url.strip()
  264. info = {
  265. 'url': url,
  266. 'domain': domain(url),
  267. 'base_url': base_url(url),
  268. 'timestamp': str(datetime.now().timestamp()),
  269. 'tags': '',
  270. 'title': fetch_page_title(url),
  271. 'sources': [text_file.name],
  272. }
  273. info['type'] = get_link_type(info)
  274. yield info