194 lines
7.4 KiB
Python
194 lines
7.4 KiB
Python
"""Parse a WXR (WordPress export) feed and load it into this blog.
|
|
|
|
Reads posts (<item>), categories/tags (<category domain="…">), and comments
|
|
(<wfw:comment>) from a WXR 1.2 document and writes them into the same tables
|
|
this blog already uses. Pure logic, stdlib only, so it can be unit-tested
|
|
without an HTTP server or database.
|
|
|
|
Mapping decisions (option a):
|
|
- Posts only are imported (no Pages).
|
|
- WordPress post_status -> our status: "publish" -> published, everything else -> draft.
|
|
- Categories are matched by name against existing rows; unknown names are created.
|
|
The slug is stored in posts.category (comma-joined for multiple categories).
|
|
- Tags are stored comma-joined in posts.tags.
|
|
- Comments are attached to their post by object_id; only approved ones are kept,
|
|
mapped to our status="approved" (the value the public view shows).
|
|
|
|
On import we never overwrite existing rows: a post with a slug that already
|
|
exists is skipped (reported in the result) so re-importing is safe.
|
|
"""
|
|
|
|
from email.utils import parsedate_to_datetime
|
|
from datetime import datetime, timezone
|
|
|
|
import xml.etree.ElementTree as ET
|
|
|
|
from .db import _slugify, get_db
|
|
|
|
|
|
# Qualified names of the elements we read. WordPress stores them with these URI
|
|
# prefixes; matching on the URI (not the prefix) means a different prefix in the
|
|
# file still resolves correctly.
|
|
_N = {
|
|
"post_name": "{http://wordpress.com/export/1.2/}post_name",
|
|
"encoded": "{http://purl.org/rss/1.0/modules/content/}encoded",
|
|
"excerpt": "{http://wordpress.org/export/1.2/excerpt/}excerpt",
|
|
"creator": "{http://purl.org/dc/elements/1.1/}creator",
|
|
"date": "{http://purl.org/dc/elements/1.1/}date",
|
|
"status": "{http://wordpress.com/export/1.2/}status",
|
|
"comment": "{http://wellformedweb.org/CommentAPI/}comment",
|
|
}
|
|
|
|
|
|
def _text(el):
|
|
return (el.text or "").strip() if el is not None else ""
|
|
|
|
|
|
def _attr(el, name):
|
|
if el is None:
|
|
return ""
|
|
val = el.get(name)
|
|
return val if val is not None else ""
|
|
|
|
|
|
def _to_db_date(value):
|
|
"""Parse an RFC 822 date (WXR pubDate/dc:date) into our DB timestamp format."""
|
|
if not value.strip():
|
|
return ""
|
|
try:
|
|
dt = parsedate_to_datetime(value.strip())
|
|
except (TypeError, ValueError):
|
|
return ""
|
|
if dt.tzinfo is not None:
|
|
dt = dt.astimezone(timezone.utc).replace(tzinfo=None)
|
|
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
def _comment_datetime(el):
|
|
"""A comment's own timestamp (WXR stores it per comment, not per post)."""
|
|
if el is None:
|
|
return ""
|
|
raw = (el.get("date_time_gmt") or el.get("comment_date_gmt") or "").strip()
|
|
if not raw:
|
|
return ""
|
|
if len(raw) >= 19 and raw[4] == "-" and raw[7] == "-":
|
|
return raw[:19] # already "YYYY-MM-DD HH:MM:SS"
|
|
return _to_db_date(raw)
|
|
|
|
|
|
def import_wxr(path, db=None):
|
|
"""Parse the WXR file at `path` and insert rows into the DB.
|
|
|
|
Returns a result dict: posts_imported, posts_skipped (duplicate slug),
|
|
categories_added, comments_imported, errors (list of strings).
|
|
|
|
`db` defaults to the app's live database; tests may pass their own sqlite3
|
|
connection so an import can be exercised against throwaway data.
|
|
"""
|
|
if db is None:
|
|
db = get_db()
|
|
|
|
try:
|
|
tree = ET.parse(path)
|
|
except ET.ParseError as exc:
|
|
return {"posts_imported": 0, "posts_skipped": 0, "categories_added": 0,
|
|
"comments_imported": 0, "errors": [f"Could not parse the WXR file: {exc}"]}
|
|
|
|
root = tree.getroot()
|
|
channel = root.find("channel")
|
|
if channel is None:
|
|
return {"posts_imported": 0, "posts_skipped": 0, "categories_added": 0,
|
|
"comments_imported": 0, "errors": ["No <channel> found in the WXR file."] }
|
|
|
|
# name -> slug for categories that already exist.
|
|
cat_by_name = {}
|
|
for slug_, name_ in db.execute("SELECT slug, name FROM categories").fetchall():
|
|
cat_by_name.setdefault(name_, slug_)
|
|
|
|
# First pass: collect every category name referenced by any post, then make
|
|
# sure each one exists so we can resolve its slug.
|
|
referenced = set()
|
|
items = channel.findall("item")
|
|
for item in items:
|
|
for cat in item.findall("category"):
|
|
# Only real categories (domain="category") need ensuring to exist;
|
|
# tags are stored on the post, never as their own category row.
|
|
if cat.get("domain") == "post_tag":
|
|
continue
|
|
name = _text(cat)
|
|
if name:
|
|
referenced.add(name)
|
|
|
|
counts = {"posts_imported": 0, "posts_skipped": 0, "categories_added": 0,
|
|
"comments_imported": 0, "errors": []}
|
|
|
|
for name in sorted(referenced):
|
|
if name not in cat_by_name:
|
|
slug_ = _slugify(name)
|
|
if not db.execute("SELECT 1 FROM categories WHERE slug = ?", (slug_,)).fetchone():
|
|
db.execute("INSERT INTO categories (slug, name) VALUES (?, ?)", (slug_, name))
|
|
counts["categories_added"] += 1
|
|
cat_by_name[name] = slug_
|
|
|
|
for item in items:
|
|
title = _text(item.find("title"))
|
|
if not title:
|
|
continue
|
|
|
|
slug = _text(item.find(_N["post_name"])) or _slugify(title)
|
|
|
|
status_raw = _text(item.find(_N["status"])).lower()
|
|
status = "published" if status_raw == "publish" else "draft"
|
|
|
|
body = _text(item.find(_N["encoded"]))
|
|
excerpt = _text(item.find(_N["excerpt"]))
|
|
author = _text(item.find(_N["creator"])) or "editor"
|
|
created_at = _to_db_date(_text(item.find(_N["date"]))) or _to_db_date(_text(item.find("pubDate")))
|
|
|
|
categories, tags = [], []
|
|
for cat in item.findall("category"):
|
|
domain = cat.get("domain", "category")
|
|
name = _text(cat)
|
|
if not name:
|
|
continue
|
|
if domain == "post_tag":
|
|
tags.append(name)
|
|
else:
|
|
categories.append(cat_by_name.get(name, name))
|
|
|
|
# A <wfw:comment> is nested inside this post's <item>, so it belongs to
|
|
# this post. Insert the post first, then attach each comment to its id.
|
|
if db.execute("SELECT 1 FROM posts WHERE slug = ?", (slug,)).fetchone():
|
|
counts["posts_skipped"] += 1
|
|
continue
|
|
|
|
db.execute(
|
|
"INSERT INTO posts (title, slug, body, excerpt, author, category, tags, status, "
|
|
"created_at, updated_at, published_at) "
|
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
(title, slug, body, excerpt, author, ",".join(categories), ",".join(tags),
|
|
status, created_at, created_at, created_at),
|
|
)
|
|
post_id = db.execute("SELECT id FROM posts WHERE slug = ?", (slug,)).fetchone()[0]
|
|
|
|
for c in item.findall(_N["comment"]):
|
|
body_c = _text(c)
|
|
if not body_c:
|
|
continue
|
|
email = _attr(c, "author_email") or ""
|
|
# Imported comments start as 'pending': auto-approving arbitrary
|
|
# text from an uploaded file published whatever it contained.
|
|
comment_at = _comment_datetime(c) or created_at
|
|
db.execute(
|
|
"INSERT INTO comments (object_type, object_id, author, email, body, status, created_at, updated_at) "
|
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
("post", post_id, _attr(c, "author") or author, email, body_c,
|
|
"pending", comment_at, comment_at),
|
|
)
|
|
counts["comments_imported"] += 1
|
|
|
|
counts["posts_imported"] += 1
|
|
|
|
db.commit()
|
|
return counts
|