main.py 7.6 KB

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