| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215 |
- import hashlib
- import re
- import os
- import sys
- import xml.etree.ElementTree
- import requests
- _HTML_HEAD = '''
- <head>
- <style>
- .img-container {
- width: 400px;
- padding: 5px;
- margin: auto;
- }
- .wrapper {
- width: 800px;
- margin: auto;
- }
- img {
- display: block;
- max-width: 100%;
- height: auto;
- }
- </style>
- </head>
- '''
- def mkdir(dest_path):
- if os.path.exists(dest_path):
- print('Error: output destination already exists.')
- return
- else:
- os.makedirs(dest_path)
- os.makedirs(os.path.join(dest_path, 'posts'))
- os.makedirs(os.path.join(dest_path, 'posts', 'files'))
- def _comment(node):
- approved = node.find(r'{http://wordpress.org/export/1.2/}comment_approved').text
- if approved != '1':
- return
- return {
- 'author': '%s (%s)' % (
- node.find(r'{http://wordpress.org/export/1.2/}comment_author').text,
- node.find(r'{http://wordpress.org/export/1.2/}comment_author_email').text
- ),
- 'date': node.find(r'{http://wordpress.org/export/1.2/}comment_date').text or '',
- 'content': node.find(r'{http://wordpress.org/export/1.2/}comment_content').text or ''
- }
- def _item(node):
- data = {
- 'type': node.find(r'{http://wordpress.org/export/1.2/}post_type').text,
- 'date': node.find(r'{http://wordpress.org/export/1.2/}post_date').text,
- 'status': node.find(r'{http://wordpress.org/export/1.2/}status').text,
- 'link': node.find(r'link').text,
- 'title': node.find(r'title').text,
- 'content_html': node.find(r'{http://purl.org/rss/1.0/modules/content/}encoded').text,
- 'post_id': node.find(r'{http://wordpress.org/export/1.2/}post_id').text,
- }
- data['id'] = hashlib.md5(data['link'].encode('utf-8')).hexdigest()
- if data['type'] == 'post':
- data['comments'] = [_comment(node) for node in node.findall(r'{http://wordpress.org/export/1.2/}comment')]
- data['comments'] = [comment for comment in data['comments'] if comment]
- elif data['type'] == 'attachment':
- data['attachment'] = node.find(r'{http://wordpress.org/export/1.2/}attachment_url').text
- return data
- def _download(dest_path, url):
- print('Downloading %s...' % url)
- extension = url.split('.')[-1]
- url_hash = hashlib.md5(url.encode('utf-8')).hexdigest()
- dest_fname = '%s.%s' % (url_hash, extension)
- dest = os.path.join(dest_path, 'posts', 'files', dest_fname)
- if os.path.exists(dest):
- print('already exists.')
- return dest_fname
- # return dest_fname
- resp = requests.get(url)
- with open(dest, 'wb') as f:
- f.write(resp.content)
- return dest_fname
- def _write_files(dest_path, posts):
- with open(os.path.join(dest_path, 'index.html'), 'w') as f:
- f.write('<html>\n')
- f.write(_HTML_HEAD)
- f.write('<body>')
- f.write('<table>')
- for post in posts:
- f.write('<tr>')
- f.write(' <td>%s</td>\n' % post['date'].split(' ')[0])
- f.write(' <td><a href="posts/%s.html">%s</a></td>\n' % (post['id'], post['title']))
- f.write('</tr>\n')
- f.write('</table>')
- f.write('</body></html>')
- for post in posts:
- with open(os.path.join(dest_path, 'posts', '%s.html' % post['id']), 'w') as f:
- f.write('<html>\n')
- f.write(_HTML_HEAD)
- f.write('<body>')
- f.write('<a href="../index.html"><--- tillbaka</a><hr>')
- f.write('<div class="wrapper">')
- f.write('<h1>%s: %s</h1>\n' % (post['date'], post['title']))
- f.write(post['content_html'] or '')
- if post['comments']:
- f.write('<hr>')
- f.write('<h1>Kommentarer</h1>')
- for comment in post['comments']:
- f.write('<h2>%s: %s</h2>' % (comment['date'], comment['author']))
- f.write(comment['content'].replace('\n', '\n<br>'))
- f.write('</div>')
- f.write('</body></html>')
- def main(dest_path, xml_files):
- posts = []
- attachments = {}
- for xml_file in xml_files:
- # print('parsing %s...' % xml_file)
- # https://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree
- tree = xml.etree.ElementTree.parse(xml_file).getroot()
- for channel in tree:
- for item in channel:
- if item.tag != 'item':
- continue
- data = _item(item)
- if data['status'] not in ['publish', 'inherit']:
- continue
- if data['type'] == 'post':
- posts.append(data)
- elif data['type'] == 'attachment':
- attachments[data['post_id']] = data
- posts.sort(key=lambda x: x['date'])
- posts = [p for p in posts if p['id'] == '2481127cff605a6239722c80efd67f3c']
- p1 = re.compile(r'(\[caption.*?\])?<a href="(http[^>]*?)"><img[^>]*? src="(http[^>]*?)"[^>]*?></a>([^<]*?\[/caption\])?')
- p3 = re.compile(r'(\[caption.*?\])?<img[^>]*? src="(http[^>]*?)"[^>]*?>([^<]*?\[/caption\])?')
- p4 = re.compile(r'\[gallery ids="(.*)"\]')
- drop_patterns = {
- # re.compile(r'\[gallery ids.*?\]'),
- }
- for post in posts:
- for p in drop_patterns:
- for match in re.finditer(p, post['content_html']):
- post['content_html'] = post['content_html'].replace(match.group(0), '')
- if re.match(r'^20\d\d - ', str(post['title'])):
- post['date'] = post['title'][:4]
- post['title'] = post['title'][7:]
- for match in re.finditer(p1, post['content_html']):
- caption = match.group(4).replace('[/caption]','').strip() if match.group(4) else ''
- img_url = match.group(3).split('?')[0]
- target_url = match.group(2)
- img_fname = _download(dest_path, img_url)
- target_fname = _download(dest_path, target_url)
- img_tag = '<div class="img-container"><a href="files/%s"><img src="files/%s"></a><i>%s</i></div>' % (target_fname, img_fname, caption)
- post['content_html'] = post['content_html'].replace(match.group(0), img_tag)
- for match in re.finditer(p3, post['content_html']):
- img_url = match.group(2).split('?')[0]
- caption = match.group(3).replace('[/caption]','').strip() if match.group(3) else ''
- img_fname = _download(dest_path, img_url)
- img_tag = '<div class="img-container"><a href="files/%s"><img src="files/%s"></a><i>%s</i></div>' % (img_fname, img_fname, caption)
- post['content_html'] = post['content_html'].replace(match.group(0), img_tag)
- for match in re.finditer(p4, post['content_html']):
- ids = match.group(1).split(',')
- body = []
- for attachment_id in ids:
- attachment = attachments.get(attachment_id)
- if not attachment:
- print('could not find attachment %s' % attachment_id)
- continue
- img_url = attachment['attachment']
- img_fname = _download(dest_path, img_url)
- body.append('<div class="img-container"><a href="files/%s"><img src="files/%s"></a></div>' % (img_fname, img_fname))
- post['content_html'] = post['content_html'].replace(match.group(0), '\n'.join(body))
- print(ids)
- _write_files(dest_path, posts)
- if __name__ == '__main__':
- if len(sys.argv) > 2:
- # mkdir(sys.argv[1])
- main(sys.argv[1], sys.argv[2:])
- else:
- print('Usage: python3 main.py <output destination> <xml files...>')
-
|