import hashlib
import re
import os
import sys
import xml.etree.ElementTree
import requests
_HTML_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('\n')
f.write(_HTML_HEAD)
f.write('')
f.write('')
for post in posts:
f.write('')
f.write(' | %s | \n' % post['date'].split(' ')[0])
f.write(' %s | \n' % (post['id'], post['title']))
f.write('
\n')
f.write('
')
f.write('')
for post in posts:
with open(os.path.join(dest_path, 'posts', '%s.html' % post['id']), 'w') as f:
f.write('\n')
f.write(_HTML_HEAD)
f.write('')
f.write('<--- tillbaka
')
f.write('')
f.write('
%s: %s
\n' % (post['date'], post['title']))
f.write(post['content_html'] or '')
if post['comments']:
f.write('
')
f.write('Kommentarer
')
for comment in post['comments']:
f.write('%s: %s
' % (comment['date'], comment['author']))
f.write(comment['content'].replace('\n', '\n
'))
f.write('')
f.write('')
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.*?\])?
]*? src="(http[^>]*?)"[^>]*?>([^<]*?\[/caption\])?')
p3 = re.compile(r'(\[caption.*?\])?
]*? 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 = '
%s ' % (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 = '
%s ' % (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('' % (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