-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpost
More file actions
executable file
·252 lines (199 loc) · 6.54 KB
/
post
File metadata and controls
executable file
·252 lines (199 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env python3
"""
Simple script to create new blog and daily posts.
Usage:
./post blog [title]
./post daily [title]
"""
import json
import random
import re
import subprocess
import sys
import os
from datetime import date
from pathlib import Path
from urllib.parse import urlparse, urlunparse, quote, unquote
from urllib.request import urlopen, Request
from html.parser import HTMLParser
REPO = Path(__file__).parent
READINGS_JSON = REPO / "readings.json"
def get_date_slug():
"""Return today's date in YYYY-MM-DD format."""
return date.today().isoformat()
def slugify(title):
"""Convert title to URL-friendly slug."""
return title.lower().replace(' ', '-').replace("'", '')
def create_blog_post(title=None):
"""Create a new blog post."""
today = get_date_slug()
if title:
slug = slugify(title)
filename = f"{slug}.md"
else:
title = input("Enter blog post title: ").strip()
if not title:
print("Error: Title is required")
sys.exit(1)
slug = slugify(title)
filename = f"{slug}.md"
filepath = Path("content/blog") / filename
if filepath.exists():
print(f"Error: {filepath} already exists")
sys.exit(1)
content = f"""+++
title = "{title}"
date = {today}
draft = true
[extra]
artbit = ""
+++
"""
filepath.write_text(content)
print(f"Created: {filepath}")
def pick_reading():
"""Pick a random unused reading, mark as used, return HTML block."""
if not READINGS_JSON.exists():
print("readings.json not found.", file=sys.stderr)
return None
entries = json.loads(READINGS_JSON.read_text())
unused = [(i, e) for i, e in enumerate(entries) if not e["used"]]
if not unused:
print("No unused readings left!", file=sys.stderr)
return None
idx, entry = random.choice(unused)
parts = ['<div class=boxed>', '']
parts.append(f'**Daily reading: [{entry["title"]}]({entry["url"]})**')
if entry["note"]:
parts.append("")
parts.append(entry["note"])
parts.append('')
parts.append('</div>')
# Mark as used
entries[idx]["used"] = True
READINGS_JSON.write_text(json.dumps(entries, indent=2, ensure_ascii=False) + "\n")
return "\n".join(parts)
class TitleParser(HTMLParser):
def __init__(self):
super().__init__()
self._in_title = False
self.title = ""
def handle_starttag(self, tag, attrs):
if tag == "title":
self._in_title = True
def handle_endtag(self, tag):
if tag == "title":
self._in_title = False
def handle_data(self, data):
if self._in_title:
self.title += data
def fetch_title(url):
"""Fetch the <title> from a URL."""
req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
try:
with urlopen(req, timeout=10) as resp:
html = resp.read(100_000).decode("utf-8", errors="replace")
except Exception as e:
print(f"Warning: could not fetch title: {e}")
return None
parser = TitleParser()
parser.feed(html)
return parser.title.strip() or None
def normalize_url(url):
"""Normalize a URL for deduplication."""
parsed = urlparse(url)
scheme = parsed.scheme.lower()
host = parsed.hostname.lower() if parsed.hostname else ""
# Remove default ports
port = parsed.port
if (scheme == "http" and port == 80) or (scheme == "https" and port == 443):
port = None
netloc = host + (f":{port}" if port else "")
# Normalize path: decode then re-encode, remove trailing slash (keep root /)
path = quote(unquote(parsed.path), safe="/:@!$&'()*+,;=-._~")
if path != "/" and path.endswith("/"):
path = path.rstrip("/")
# Remove fragment, keep query
return urlunparse((scheme, netloc, path, parsed.params, parsed.query, ""))
def add_reading(url, note=""):
"""Fetch title from URL and add a new reading entry."""
if not READINGS_JSON.exists():
print("readings.json not found.", file=sys.stderr)
sys.exit(1)
url = normalize_url(url)
entries = json.loads(READINGS_JSON.read_text())
existing = {normalize_url(e["url"]) for e in entries}
if url in existing:
print(f"Already exists: {url}")
sys.exit(1)
fetched = (fetch_title(url) or "").replace('"', '\\"')
result = subprocess.run(
["bash", "-c", f'read -e -i "{fetched}" -p "Title: " val && echo "$val"'],
text=True, stdout=subprocess.PIPE,
)
title = result.stdout.strip()
if not title:
print("Error: Title is required")
sys.exit(1)
entries.append({
"date": get_date_slug(),
"title": title,
"url": url,
"note": note,
"used": False,
})
READINGS_JSON.write_text(json.dumps(entries, indent=2, ensure_ascii=False) + "\n")
unused = sum(1 for e in entries if not e["used"])
print(f"Added: {title}")
print(f"{unused}/{len(entries)} readings remaining.")
def create_daily_post(title=None):
"""Create a new daily post with a random reading."""
today = get_date_slug()
if not title:
title = f"Daily: {today}"
filename = f"{today}.md"
filepath = Path("content/daily") / filename
if filepath.exists():
print(f"Error: {filepath} already exists")
sys.exit(1)
reading = pick_reading()
content = f"""+++
title = "{title}"
date = {today}
+++
"""
if reading:
content += reading + "\n\n"
filepath.write_text(content)
print(f"Created: {filepath}")
if reading and READINGS_JSON.exists():
entries = json.loads(READINGS_JSON.read_text())
unused = sum(1 for e in entries if not e["used"])
print(f"Included a random reading. {unused}/{len(entries)} remaining.")
def main():
if len(sys.argv) < 2:
print("Usage: ./post {blog|daily} [title]")
sys.exit(1)
command = sys.argv[1]
title = " ".join(sys.argv[2:]) if len(sys.argv) > 2 else None
if command == "blog":
create_blog_post(title)
elif command == "daily":
create_daily_post(title)
elif command == "add":
args = sys.argv[2:]
if not args:
print("Usage: ./post add <url> [-m message]")
sys.exit(1)
url = args[0]
note = ""
if "-m" in args:
mi = args.index("-m")
note = " ".join(args[mi + 1:])
add_reading(url, note)
else:
print(f"Error: Unknown command '{command}'")
print("Usage: ./post {blog|daily|add} [title|url]")
sys.exit(1)
if __name__ == "__main__":
main()