parse.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. 'timestamp': '15442123124234',
  9. 'title': 'Example.com Page Title',
  10. 'tags': 'abc,def',
  11. 'sources': ['ril_export.html', 'downloads/getpocket.com.txt'],
  12. }
  13. """
  14. import re
  15. import json
  16. from datetime import datetime
  17. from collections import OrderedDict
  18. import xml.etree.ElementTree as etree
  19. from config import ANSI
  20. from util import (
  21. str_between,
  22. get_link_type,
  23. URL_REGEX,
  24. )
  25. def get_parsers(file):
  26. """return all parsers that work on a given file, defaults to all of them"""
  27. return OrderedDict([
  28. ('Pocket HTML', parse_pocket_html_export),
  29. ('Pinboard JSON', parse_pinboard_json_export),
  30. ('Netscape HTML', parse_netscape_html_export),
  31. ('RSS', parse_rss_export),
  32. ('Pinboard RSS', parse_pinboard_rss_export),
  33. ('Shaarli RSS', parse_shaarli_rss_export),
  34. ('Medium RSS', parse_medium_rss_export),
  35. ('Plain Text', parse_plain_text_export),
  36. ])
  37. def parse_links(path):
  38. """parse a list of links dictionaries from a bookmark export file"""
  39. links = []
  40. with open(path, 'r', encoding='utf-8') as file:
  41. print('{green}[*] [{}] Parsing new links from output/sources/{}...{reset}'.format(
  42. datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  43. path.rsplit('/', 1)[-1],
  44. **ANSI,
  45. ))
  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 Exception as err:
  53. # we try each parser one by one, each parser will throw exeption an exception if unsupported
  54. # so we accept the first one that
  55. # uncomment the following line to see why the parser was unsupported for each attempted format
  56. # print('[!] Parser {} failed: {} {}'.format(parser_name, err.__class__.__name__, err))
  57. pass
  58. return links, parser_name
  59. def parse_pocket_html_export(html_file):
  60. """Parse Pocket-format bookmarks export files (produced by getpocket.com/export/)"""
  61. html_file.seek(0)
  62. pattern = re.compile("^\\s*<li><a href=\"(.+)\" time_added=\"(\\d+)\" tags=\"(.*)\">(.+)</a></li>", re.UNICODE)
  63. for line in html_file:
  64. # example line
  65. # <li><a href="http://example.com/ time_added="1478739709" tags="tag1,tag2">example title</a></li>
  66. match = pattern.search(line)
  67. if match:
  68. fixed_url = match.group(1).replace('http://www.readability.com/read?url=', '') # remove old readability prefixes to get original url
  69. time = datetime.fromtimestamp(float(match.group(2)))
  70. info = {
  71. 'url': fixed_url,
  72. 'timestamp': str(time.timestamp()),
  73. 'tags': match.group(3),
  74. 'title': match.group(4).replace(' — Readability', '').replace('http://www.readability.com/read?url=', '') or None,
  75. 'sources': [html_file.name],
  76. }
  77. info['type'] = get_link_type(info)
  78. yield info
  79. def parse_pinboard_json_export(json_file):
  80. """Parse JSON-format bookmarks export files (produced by pinboard.in/export/, or wallabag)"""
  81. json_file.seek(0)
  82. json_content = json.load(json_file)
  83. for line in json_content:
  84. # example line
  85. # {"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"}]
  86. if line:
  87. erg = line
  88. if erg.get('timestamp'):
  89. timestamp = str(erg['timestamp']/10000000) # chrome/ff histories use a very precise timestamp
  90. elif erg.get('time'):
  91. timestamp = str(datetime.strptime(erg['time'].split(',', 1)[0], '%Y-%m-%dT%H:%M:%SZ').timestamp())
  92. elif erg.get('created_at'):
  93. timestamp = str(datetime.strptime(erg['created_at'], '%Y-%m-%dT%H:%M:%S%z').timestamp())
  94. else:
  95. timestamp = str(datetime.now().timestamp())
  96. if erg.get('href'):
  97. url = erg['href']
  98. else:
  99. url = erg['url']
  100. if erg.get('description'):
  101. title = (erg.get('description') or '').replace(' — Readability', '')
  102. else:
  103. title = erg['title'].strip()
  104. info = {
  105. 'url': url,
  106. 'timestamp': timestamp,
  107. 'tags': erg.get('tags') or '',
  108. 'title': title or None,
  109. 'sources': [json_file.name],
  110. }
  111. info['type'] = get_link_type(info)
  112. yield info
  113. def parse_rss_export(rss_file):
  114. """Parse RSS XML-format files into links"""
  115. rss_file.seek(0)
  116. items = rss_file.read().split('</item>\n<item>')
  117. for item in items:
  118. # example item:
  119. # <item>
  120. # <title><![CDATA[How JavaScript works: inside the V8 engine]]></title>
  121. # <category>Unread</category>
  122. # <link>https://blog.sessionstack.com/how-javascript-works-inside</link>
  123. # <guid>https://blog.sessionstack.com/how-javascript-works-inside</guid>
  124. # <pubDate>Mon, 21 Aug 2017 14:21:58 -0500</pubDate>
  125. # </item>
  126. trailing_removed = item.split('</item>', 1)[0]
  127. leading_removed = trailing_removed.split('<item>', 1)[-1]
  128. rows = leading_removed.split('\n')
  129. def get_row(key):
  130. return [r for r in rows if r.strip().startswith('<{}>'.format(key))][0]
  131. title = str_between(get_row('title'), '<![CDATA[', ']]').strip()
  132. url = str_between(get_row('link'), '<link>', '</link>')
  133. ts_str = str_between(get_row('pubDate'), '<pubDate>', '</pubDate>')
  134. time = datetime.strptime(ts_str, "%a, %d %b %Y %H:%M:%S %z")
  135. info = {
  136. 'url': url,
  137. 'timestamp': str(time.timestamp()),
  138. 'tags': '',
  139. 'title': title or None,
  140. 'sources': [rss_file.name],
  141. }
  142. info['type'] = get_link_type(info)
  143. yield info
  144. def parse_shaarli_rss_export(rss_file):
  145. """Parse Shaarli-specific RSS XML-format files into links"""
  146. rss_file.seek(0)
  147. entries = rss_file.read().split('<entry>')[1:]
  148. for entry in entries:
  149. # example entry:
  150. # <entry>
  151. # <title>Aktuelle Trojaner-Welle: Emotet lauert in gefälschten Rechnungsmails | heise online</title>
  152. # <link href="https://www.heise.de/security/meldung/Aktuelle-Trojaner-Welle-Emotet-lauert-in-gefaelschten-Rechnungsmails-4291268.html" />
  153. # <id>https://demo.shaarli.org/?cEV4vw</id>
  154. # <published>2019-01-30T06:06:01+00:00</published>
  155. # <updated>2019-01-30T06:06:01+00:00</updated>
  156. # <content type="html" xml:lang="en"><![CDATA[<div class="markdown"><p>&#8212; <a href="https://demo.shaarli.org/?cEV4vw">Permalink</a></p></div>]]></content>
  157. # </entry>
  158. trailing_removed = entry.split('</entry>', 1)[0]
  159. leading_removed = trailing_removed.strip()
  160. rows = leading_removed.split('\n')
  161. def get_row(key):
  162. return [r.strip() for r in rows if r.strip().startswith('<{}'.format(key))][0]
  163. title = str_between(get_row('title'), '<title>', '</title>').strip()
  164. url = str_between(get_row('link'), '<link href="', '" />')
  165. ts_str = str_between(get_row('published'), '<published>', '</published>')
  166. time = datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%S%z")
  167. info = {
  168. 'url': url,
  169. 'timestamp': str(time.timestamp()),
  170. 'tags': '',
  171. 'title': title or None,
  172. 'sources': [rss_file.name],
  173. }
  174. info['type'] = get_link_type(info)
  175. yield info
  176. def parse_netscape_html_export(html_file):
  177. """Parse netscape-format bookmarks export files (produced by all browsers)"""
  178. html_file.seek(0)
  179. pattern = re.compile("<a href=\"(.+?)\" add_date=\"(\\d+)\"[^>]*>(.+)</a>", re.UNICODE | re.IGNORECASE)
  180. for line in html_file:
  181. # example line
  182. # <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>
  183. match = pattern.search(line)
  184. if match:
  185. url = match.group(1)
  186. time = datetime.fromtimestamp(float(match.group(2)))
  187. info = {
  188. 'url': url,
  189. 'timestamp': str(time.timestamp()),
  190. 'tags': "",
  191. 'title': match.group(3).strip() or None,
  192. 'sources': [html_file.name],
  193. }
  194. info['type'] = get_link_type(info)
  195. yield info
  196. def parse_pinboard_rss_export(rss_file):
  197. """Parse Pinboard RSS feed files into links"""
  198. rss_file.seek(0)
  199. root = etree.parse(rss_file).getroot()
  200. items = root.findall("{http://purl.org/rss/1.0/}item")
  201. for item in items:
  202. url = item.find("{http://purl.org/rss/1.0/}link").text
  203. tags = item.find("{http://purl.org/dc/elements/1.1/}subject").text
  204. title = item.find("{http://purl.org/rss/1.0/}title").text.strip()
  205. ts_str = item.find("{http://purl.org/dc/elements/1.1/}date").text
  206. # = 🌈🌈🌈🌈
  207. # = 🌈🌈🌈🌈
  208. # = 🏆🏆🏆🏆
  209. # Pinboard includes a colon in its date stamp timezone offsets, which
  210. # Python can't parse. Remove it:
  211. if ":" == ts_str[-3:-2]:
  212. ts_str = ts_str[:-3]+ts_str[-2:]
  213. time = datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%S%z")
  214. info = {
  215. 'url': url,
  216. 'timestamp': str(time.timestamp()),
  217. 'tags': tags,
  218. 'title': title or None,
  219. 'sources': [rss_file.name],
  220. }
  221. info['type'] = get_link_type(info)
  222. yield info
  223. def parse_medium_rss_export(rss_file):
  224. """Parse Medium RSS feed files into links"""
  225. rss_file.seek(0)
  226. root = etree.parse(rss_file).getroot()
  227. items = root.find("channel").findall("item")
  228. for item in items:
  229. # for child in item:
  230. # print(child.tag, child.text)
  231. url = item.find("link").text
  232. title = item.find("title").text.strip()
  233. ts_str = item.find("pubDate").text
  234. time = datetime.strptime(ts_str, "%a, %d %b %Y %H:%M:%S %Z")
  235. info = {
  236. 'url': url,
  237. 'timestamp': str(time.timestamp()),
  238. 'tags': '',
  239. 'title': title or None,
  240. 'sources': [rss_file.name],
  241. }
  242. info['type'] = get_link_type(info)
  243. yield info
  244. def parse_plain_text_export(text_file):
  245. """Parse raw links from each line in a text file"""
  246. text_file.seek(0)
  247. text_content = text_file.readlines()
  248. for line in text_content:
  249. if line:
  250. urls = re.findall(URL_REGEX, line)
  251. for url in urls:
  252. url = url.strip()
  253. info = {
  254. 'url': url,
  255. 'timestamp': str(datetime.now().timestamp()),
  256. 'tags': '',
  257. 'title': None,
  258. 'sources': [text_file.name],
  259. }
  260. info['type'] = get_link_type(info)
  261. yield info