|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Generated by the github copilot agent, but heavily modified and corrected by me |
| 4 | +""" |
| 5 | + |
| 6 | +""" |
| 7 | +What this script does: |
| 8 | +Finds published posts in _posts/, post a toot for those missing comment_id, write the comment_id back and commit. |
| 9 | +
|
| 10 | +
|
| 11 | +This is compatible to jekyll, regarding publishing it considers the `publish` and `published` flag and checks the date whether it is already published |
| 12 | +(YAML has precedence over filename). |
| 13 | +NOTE: This will generate wrong links, if you wrote one of the predefined permalinks schemes into the frontmatter (or changed the default). Only the default scheme is currently supported. |
| 14 | +
|
| 15 | +
|
| 16 | +Environment variables: |
| 17 | + MASTODON_TOKEN - access token for Mastodon |
| 18 | + GITHUB_TOKEN - token with repo write permissions (provided by Actions) |
| 19 | +
|
| 20 | +Furthermore in _config.yml: |
| 21 | +url for generating links to the blog |
| 22 | +mastodon: |
| 23 | + - username: xyz |
| 24 | + instance: abc.com |
| 25 | +
|
| 26 | + The mastodon username and instance |
| 27 | +
|
| 28 | +
|
| 29 | +This script edits files in-place and commits changes using git. |
| 30 | +""" |
| 31 | +import os |
| 32 | +import re |
| 33 | +import sys |
| 34 | +import yaml |
| 35 | +import requests |
| 36 | +from datetime import datetime, timezone |
| 37 | +from dateutil import parser as date_parser |
| 38 | +from pathlib import Path |
| 39 | +import subprocess |
| 40 | +import logging |
| 41 | + |
| 42 | +# TODO change |
| 43 | +logging.basicConfig(level=logging.DEBUG) |
| 44 | + |
| 45 | + |
| 46 | +POSTS_DIR = Path("_posts") |
| 47 | + |
| 48 | + |
| 49 | +def parse_front_matter(text): |
| 50 | + m = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.S) |
| 51 | + if not m: |
| 52 | + logging.warning(f"Frontmatter regex failed on a post: {text}") |
| 53 | + return None, text |
| 54 | + fm_text, body = m.group(1), m.group(2) |
| 55 | + data = yaml.safe_load(fm_text) or {} |
| 56 | + logging.debug(data) |
| 57 | + return data, body |
| 58 | + |
| 59 | + |
| 60 | +def build_content(fm, body): |
| 61 | + fm_text = yaml.safe_dump(fm, sort_keys=False).rstrip() + "\n" |
| 62 | + return "---\n" + fm_text + "---\n" + (body.lstrip()) |
| 63 | + |
| 64 | + |
| 65 | +def get_date(fm, filename): |
| 66 | + date = fm.get("date") |
| 67 | + if date is None: |
| 68 | + date = "-".join(filename.split("-")[:3]) |
| 69 | + # Crashes if date does not exist or is invalid |
| 70 | + d = date_parser.parse(str(date)) |
| 71 | + if d.tzinfo is None: |
| 72 | + d = d.replace(tzinfo=timezone.utc) |
| 73 | + return d |
| 74 | + |
| 75 | + |
| 76 | +def is_published(fm, filename): |
| 77 | + pub = fm.get("publish") or fm.get("published") or fm.get("published", |
| 78 | + None) |
| 79 | + if isinstance(pub, bool) and not pub: |
| 80 | + return False |
| 81 | + # allow publish: true or published: true; if absent, consider published if date <= now |
| 82 | + d = get_date(fm, filename) |
| 83 | + if d: |
| 84 | + return d <= datetime.now(timezone.utc) |
| 85 | + |
| 86 | + return True |
| 87 | + |
| 88 | + |
| 89 | +def toot_post(instance, token, content, in_reply_to_id=None): |
| 90 | + url = instance.rstrip("/") + "/api/v1/statuses" |
| 91 | + data = {"status": content, "visibility": "public"} |
| 92 | + if in_reply_to_id: |
| 93 | + data["in_reply_to_id"] = in_reply_to_id |
| 94 | + headers = {"Authorization": f"Bearer {token}"} |
| 95 | + r = requests.post(url, data=data, headers=headers, timeout=30) |
| 96 | + logging.debug(data, headers) |
| 97 | + r.raise_for_status() # Throw exception if this did not work |
| 98 | + return r.json() |
| 99 | + |
| 100 | + |
| 101 | +def git_commit_and_push(files, message): |
| 102 | + if not files: |
| 103 | + return |
| 104 | + subprocess.check_call(["git", "config", "user.name", "github-actions[bot]"]) |
| 105 | + subprocess.check_call(["git", "config", "user.email", "invalid@example.com"]) |
| 106 | + subprocess.check_call(["git", "add"] + files) |
| 107 | + subprocess.check_call(["git", "commit", "-m", message]) |
| 108 | + # push using the repository origin; GITHUB_TOKEN is available in env for auth via checkout |
| 109 | + subprocess.check_call(["git", "push"]) |
| 110 | + |
| 111 | + |
| 112 | +def main(): |
| 113 | + token = os.getenv("MASTODON_TOKEN") |
| 114 | + |
| 115 | + with open("_config.yml") as file: |
| 116 | + config = yaml.safe_load(file.read()) |
| 117 | + instance = config.get("mastodon")[0]["instance"] |
| 118 | + if not instance or not token: |
| 119 | + logging.error("MASTODON_TOKEN must be set in github actions env and the mastodon block (see at the beginning of this file) configured in _config.yml") |
| 120 | + sys.exit(1) |
| 121 | + |
| 122 | + if not POSTS_DIR.exists(): |
| 123 | + logging.error(f"Posts dir {POSTS_DIR} not found") |
| 124 | + sys.exit(1) |
| 125 | + |
| 126 | + changed_files = [] |
| 127 | + |
| 128 | + for path in sorted(POSTS_DIR.iterdir()): |
| 129 | + if not path.is_file(): |
| 130 | + logging.debug("A") |
| 131 | + continue |
| 132 | + text = path.read_text(encoding="utf-8") |
| 133 | + fm, body = parse_front_matter(text) |
| 134 | + if fm is None: |
| 135 | + logging.debug("B") |
| 136 | + continue |
| 137 | + if not is_published(fm, path.name): |
| 138 | + logging.debug("C") |
| 139 | + continue |
| 140 | + if fm.get("comment_id"): |
| 141 | + logging.debug("D") |
| 142 | + continue |
| 143 | + # check file has correct naming scheme |
| 144 | + |
| 145 | + logging.debug(f"Current filename: {path.name}") |
| 146 | + |
| 147 | + # prepare toot content: use title and permalink if present |
| 148 | + title = fm.get("title") or path.stem |
| 149 | + # Link schemas are listed here: https://mademistakes.com/mastering-jekyll/how-to-link/ |
| 150 | + # /:categories/:year/:month/:day/:title:output_ext |
| 151 | + |
| 152 | + if type(fm.get("categories")) == list: |
| 153 | + categories = "/".join(fm.get("categories")) |
| 154 | + else: |
| 155 | + categories = fm.get("categories") |
| 156 | + date = get_date(fm, path.name) |
| 157 | + if date is False: |
| 158 | + raise Exception("Could not parse Date") |
| 159 | + |
| 160 | + blog_url = config.get("url") |
| 161 | + url = fm.get("permalink") or f"{blog_url}/{categories}/{str(date.year)}/{str(date.day)}/{path.name.split(".")[-2]}.html" |
| 162 | + toot = f"""Read my new post {title}: |
| 163 | +{url} |
| 164 | +
|
| 165 | +To comment on it, please just answer to this toot. The toots will be loaded underneath the article. |
| 166 | +
|
| 167 | +Lies meinen neuen Blogpost (link oberhalb) |
| 168 | +Zum kommentieren, einfach unter diesem Toot kommentieren, die toots landen dann unter dem Artikel. |
| 169 | +""" |
| 170 | + |
| 171 | + logging.info(f"Tooting for {path.name}: {toot}") |
| 172 | + try: |
| 173 | + res = toot_post(instance, token, toot) |
| 174 | + except Exception as e: |
| 175 | + logging.error(f"Failed to toot {path}: {e}") |
| 176 | + continue |
| 177 | + |
| 178 | + comment_id = res.get("id") |
| 179 | + if not comment_id: |
| 180 | + logging.error(f"No id returned for {path}") |
| 181 | + break |
| 182 | + |
| 183 | + fm["comment_id"] = str(comment_id) |
| 184 | + new_content = build_content(fm, body) |
| 185 | + path.write_text(new_content, encoding="utf-8") |
| 186 | + changed_files.append(str(path)) |
| 187 | + |
| 188 | + if changed_files: |
| 189 | + git_commit_and_push(changed_files, "Add comment_id for tooted posts") |
| 190 | + |
| 191 | + |
| 192 | +if __name__ == "__main__": |
| 193 | + main() |
0 commit comments