main.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import hashlib
  2. import re
  3. import os
  4. import sys
  5. import xml.etree.ElementTree
  6. import requests
  7. _HTML_HEAD = '''
  8. <head>
  9. <style>
  10. .img-container {
  11. width: 400px;
  12. padding: 5px;
  13. margin: auto;
  14. }
  15. .wrapper {
  16. width: 800px;
  17. margin: auto;
  18. font-size: larger;
  19. padding-bottom: 100px;
  20. }
  21. img {
  22. display: block;
  23. max-width: 100%;
  24. height: auto;
  25. }
  26. table {
  27. font-size: large;
  28. }
  29. td {
  30. padding-left: 20px;
  31. padding-top: 3px;
  32. }
  33. </style>
  34. </head>
  35. '''
  36. def mkdir(dest_path):
  37. if os.path.exists(dest_path):
  38. print('Error: output destination already exists.')
  39. return
  40. else:
  41. os.makedirs(dest_path)
  42. os.makedirs(os.path.join(dest_path, 'posts'))
  43. os.makedirs(os.path.join(dest_path, 'posts', 'files'))
  44. def _comment(node):
  45. approved = node.find(r'{http://wordpress.org/export/1.2/}comment_approved').text
  46. if approved != '1':
  47. return
  48. return {
  49. 'author': '%s (%s)' % (
  50. node.find(r'{http://wordpress.org/export/1.2/}comment_author').text,
  51. node.find(r'{http://wordpress.org/export/1.2/}comment_author_email').text
  52. ),
  53. 'date': node.find(r'{http://wordpress.org/export/1.2/}comment_date').text or '',
  54. 'content': node.find(r'{http://wordpress.org/export/1.2/}comment_content').text or ''
  55. }
  56. def _item(node):
  57. data = {
  58. 'type': node.find(r'{http://wordpress.org/export/1.2/}post_type').text,
  59. 'date': node.find(r'{http://wordpress.org/export/1.2/}post_date').text,
  60. 'status': node.find(r'{http://wordpress.org/export/1.2/}status').text,
  61. 'link': node.find(r'link').text,
  62. 'title': node.find(r'title').text,
  63. 'content_html': node.find(r'{http://purl.org/rss/1.0/modules/content/}encoded').text,
  64. 'post_id': node.find(r'{http://wordpress.org/export/1.2/}post_id').text,
  65. }
  66. data['id'] = hashlib.md5(data['link'].encode('utf-8')).hexdigest()
  67. if data['type'] == 'post':
  68. data['comments'] = [_comment(node) for node in node.findall(r'{http://wordpress.org/export/1.2/}comment')]
  69. data['comments'] = [comment for comment in data['comments'] if comment]
  70. elif data['type'] == 'attachment':
  71. data['attachment'] = node.find(r'{http://wordpress.org/export/1.2/}attachment_url').text
  72. return data
  73. def _download(dest_path, url):
  74. extension = url.split('.')[-1]
  75. url_hash = hashlib.md5(url.encode('utf-8')).hexdigest()
  76. dest_fname = '%s.%s' % (url_hash, extension)
  77. dest = os.path.join(dest_path, 'posts', 'files', dest_fname)
  78. if os.path.exists(dest):
  79. # print('already exists.')
  80. return dest_fname
  81. print('Downloading %s...' % url)
  82. resp = requests.get(url)
  83. with open(dest, 'wb') as f:
  84. f.write(resp.content)
  85. return dest_fname
  86. def _write_files(dest_path, posts):
  87. with open(os.path.join(dest_path, 'index.html'), 'w') as f:
  88. f.write('<html>\n')
  89. f.write(_HTML_HEAD)
  90. f.write('<body>')
  91. f.write('<div class="wrapper">')
  92. f.write('<table>')
  93. for post in posts:
  94. f.write('<tr>')
  95. f.write(' <td>%s</td>\n' % post['date'].split(' ')[0])
  96. f.write(' <td><a href="posts/%s.html">%s</a></td>\n' % (post['id'], post['title']))
  97. f.write('</tr>\n')
  98. f.write('</table>')
  99. f.write('</div>')
  100. f.write('</body></html>')
  101. for post in posts:
  102. with open(os.path.join(dest_path, 'posts', '%s.html' % post['id']), 'w') as f:
  103. f.write('<html>\n')
  104. f.write(_HTML_HEAD)
  105. f.write('<body>')
  106. f.write('<div class="wrapper">')
  107. f.write('<a href="../index.html">&lt;&lt;&lt; Tillbaka</a>')
  108. if post['comments']:
  109. f.write(' | <a href="#comments">Kommentarer</a>')
  110. f.write('<hr>')
  111. f.write('<h1>%s: %s</h1>\n' % (post['date'], post['title']))
  112. f.write(post['content_html'] or '')
  113. if post['comments']:
  114. f.write('<hr>')
  115. f.write('<div id="comments">')
  116. f.write('<h1>Kommentarer</h1>')
  117. for comment in post['comments']:
  118. f.write('<h2>%s: %s</h2>' % (comment['date'], comment['author']))
  119. f.write('<p>' + comment['content'].replace('\n', '</p><p>') + '</p>')
  120. f.write('</div>')
  121. f.write('</div>')
  122. f.write('</body></html>')
  123. def main(dest_path, xml_files):
  124. posts = []
  125. attachments = {}
  126. for xml_file in xml_files:
  127. # print('parsing %s...' % xml_file)
  128. # https://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree
  129. tree = xml.etree.ElementTree.parse(xml_file).getroot()
  130. for channel in tree:
  131. for item in channel:
  132. if item.tag != 'item':
  133. continue
  134. data = _item(item)
  135. if data['status'] not in ['publish', 'inherit']:
  136. continue
  137. if data['type'] == 'post':
  138. posts.append(data)
  139. elif data['type'] == 'attachment':
  140. attachments[data['post_id']] = data
  141. posts.sort(key=lambda x: x['date'])
  142. p1 = re.compile(r'(\[caption.*?\])?<a href="(http[^>]*?)"><img[^>]*? src="(http[^>]*?)"[^>]*?></a>([^<]*?\[/caption\])?')
  143. p3 = re.compile(r'(\[caption.*?\])?<img[^>]*? src="(http[^>]*?)"[^>]*?>([^<]*?\[/caption\])?')
  144. p4 = re.compile(r'\[gallery.*?ids="([^"]*?)".*?\]')
  145. drop_patterns = {
  146. re.compile(r'<span .*?>'),
  147. }
  148. for post in posts:
  149. if '<p' not in post['content_html']:
  150. post['content_html'] = '<p>' + post['content_html'].replace('\n', '</p><p>') + '</p>'
  151. for p in drop_patterns:
  152. for match in re.finditer(p, post['content_html']):
  153. post['content_html'] = post['content_html'].replace(match.group(0), '')
  154. if re.match(r'^20\d\d - ', str(post['title'])):
  155. post['date'] = post['title'][:4]
  156. post['title'] = post['title'][7:]
  157. for match in re.finditer(p1, post['content_html']):
  158. caption = match.group(4).replace('[/caption]','').strip() if match.group(4) else ''
  159. img_url = match.group(3).split('?')[0]
  160. target_url = match.group(2)
  161. img_fname = _download(dest_path, img_url)
  162. target_fname = _download(dest_path, target_url)
  163. img_tag = '<div class="img-container"><a href="files/%s"><img src="files/%s"></a><i>%s</i></div>' % (target_fname, img_fname, caption)
  164. post['content_html'] = post['content_html'].replace(match.group(0), img_tag)
  165. for match in re.finditer(p3, post['content_html']):
  166. img_url = match.group(2).split('?')[0]
  167. caption = match.group(3).replace('[/caption]','').strip() if match.group(3) else ''
  168. img_fname = _download(dest_path, img_url)
  169. img_tag = '<div class="img-container"><a href="files/%s"><img src="files/%s"></a><i>%s</i></div>' % (img_fname, img_fname, caption)
  170. post['content_html'] = post['content_html'].replace(match.group(0), img_tag)
  171. for match in re.finditer(p4, post['content_html']):
  172. ids = match.group(1).split(',')
  173. body = []
  174. for attachment_id in ids:
  175. attachment = attachments.get(attachment_id)
  176. if not attachment:
  177. print('could not find attachment %s' % attachment_id)
  178. continue
  179. img_url = attachment['attachment']
  180. img_fname = _download(dest_path, img_url)
  181. body.append('<div class="img-container"><a href="files/%s"><img src="files/%s"></a></div>' % (img_fname, img_fname))
  182. post['content_html'] = post['content_html'].replace(match.group(0), '\n'.join(body))
  183. _write_files(dest_path, posts)
  184. if __name__ == '__main__':
  185. if len(sys.argv) > 2:
  186. # mkdir(sys.argv[1])
  187. main(sys.argv[1], sys.argv[2:])
  188. else:
  189. print('Usage: python3 main.py <output destination> <xml files...>')