"""拾编写作台的通用工具:slug、front matter、摘要。""" import re from datetime import datetime, time from pathlib import Path from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime from django.utils.html import strip_tags from django.utils.text import slugify from blog.models import Category, Post, Tag def unique_slug(model, base, exclude_id=None, max_length=200): base = (base or "item").strip()[:max_length] or "item" slug = base index = 2 queryset = model.objects.all() if exclude_id: queryset = queryset.exclude(pk=exclude_id) while queryset.filter(slug=slug).exists(): suffix = "-{}".format(index) slug = base[: max_length - len(suffix)] + suffix index += 1 return slug def make_post_slug(raw="", title="", filename="", exclude_id=None): candidates = [raw, title, Path(filename).stem if filename else ""] for candidate in candidates: value = slugify(candidate or "") if value: return unique_slug(Post, value[:200], exclude_id, 200) fallback = "post-" + timezone.localtime().strftime("%Y%m%d-%H%M") return unique_slug(Post, fallback, exclude_id, 200) def make_category_slug(raw="", name="", exclude_id=None): candidate = (raw or "").strip() if candidate: candidate = candidate.replace("/", "-") candidate = re.sub(r"\s+", "-", candidate) if not candidate: candidate = slugify(name or "", allow_unicode=True) if not candidate: candidate = "cat" return unique_slug(Category, candidate[:100], exclude_id, 100) def make_tag_slug(name, exclude_id=None): candidate = slugify(name or "", allow_unicode=True) or "tag" return unique_slug(Tag, candidate[:100], exclude_id, 100) def get_or_create_category(name): name = (name or "").strip()[:100] if not name: return None category = Category.objects.filter(name=name).first() if category: return category return Category.objects.create(name=name, slug=make_category_slug(name=name)) def get_or_create_tag(name): name = (name or "").strip()[:100] if not name: return None tag = Tag.objects.filter(name=name).first() if tag: return tag return Tag.objects.create(name=name, slug=make_tag_slug(name)) def descendant_ids(category): """分类的所有后代 id(不含自身)。""" found = set() stack = [category.pk] while stack: parent_id = stack.pop() children = list( Category.objects.filter(parent_id=parent_id).values_list("pk", flat=True) ) for child_id in children: if child_id not in found: found.add(child_id) stack.append(child_id) return found def parse_front_matter(text): """解析一个极简 YAML front matter;不引入 PyYAML。""" text = (text or "").lstrip("\ufeff") lines = text.splitlines() if not lines or lines[0].strip() != "---": return {}, text end = None for index in range(1, len(lines)): if lines[index].strip() in ("---", "..."): end = index break if end is None: return {}, text meta = {} for line in lines[1:end]: if ":" not in line: continue key, value = line.split(":", 1) key = key.strip().lower() if not key: continue meta[key] = value.strip().strip("\"'") body = "\n".join(lines[end + 1:]).lstrip("\n") return meta, body def split_names(value): value = (value or "").strip().strip("[]") if not value: return [] return [ item.strip().strip("\"'") for item in re.split(r"[,,、]", value) if item.strip() ] def first_heading(body): match = re.search(r"^#\s+(.+?)\s*$", body or "", re.MULTILINE) if not match: return "" return re.sub(r"[*_`]+", "", match.group(1)).strip() def remove_first_heading(body): match = re.search(r"^#\s+(.+?)\s*$", body or "", re.MULTILINE) if not match: return body return (body[: match.start()] + body[match.end():]).lstrip("\n") def plain_excerpt(content, content_format="markdown", length=180): if content_format == "markdown": try: import markdown html = markdown.markdown( content or "", extensions=["extra", "sane_lists"] ) except Exception: html = content or "" else: html = content or "" text = strip_tags(html) text = re.sub(r"\s+", " ", text).strip() return text[:length] def parse_date_value(value): value = (value or "").strip() if not value: return None moment = parse_datetime(value) if moment is None: day = parse_date(value) if day is None: return None moment = datetime.combine(day, time.min) if timezone.is_naive(moment): moment = timezone.make_aware(moment) return moment