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
253
254
255
256
257
|
#!/usr/bin/env node
/**
* Daily live event recap mailer.
* Queries today's events (JST) from SQLite and sends an HTML digest via the
* mail container (Postfix + OpenDKIM) which delivers directly to recipient MX.
*
* Env vars:
* DB_PATH path to SQLite database (default: /app/data/events.db)
* MAIL_HOST SMTP host (default: mail — the Postfix container)
* MAIL_PORT SMTP port (default: 25)
* RECAP_TO recipient address (default: mazideyabai@gmail.com)
*/
import Database from "better-sqlite3";
import { createConnection } from "net";
const DB_PATH = process.env.DB_PATH ?? "/app/data/events.db";
const MAIL_HOST = process.env.MAIL_HOST ?? "mail";
const MAIL_PORT = parseInt(process.env.MAIL_PORT ?? "25", 10);
const FROM = "noreply@golive.yyamashita.com";
const EHLO_DOMAIN = "golive.yyamashita.com";
const TO = process.env.RECAP_TO ?? "mazideyabai@gmail.com";
const APP_URL = "https://golive.yyamashita.com";
// ---- date helpers (JST = UTC+9) ----------------------------------------
const JST_MS = 9 * 60 * 60 * 1000;
function nowJST(): Date {
return new Date(Date.now() + JST_MS);
}
function isoDate(d: Date): string {
// Returns YYYY-MM-DD in JST
return new Date(d.getTime() + JST_MS).toISOString().slice(0, 10);
}
function fmtJST(dateStr: string): string {
const DOW = ["日", "月", "火", "水", "木", "金", "土"];
const d = new Date(`${dateStr}T12:00:00Z`);
const [y, m, day] = dateStr.split("-");
return `${y}/${m}/${day}(${DOW[d.getUTCDay()]})`;
}
// ---- database ----------------------------------------------------------
interface EventRow {
id: number;
venue_name: string;
title: string;
artist: string | null;
date: string;
start_time: string | null;
price: string | null;
ticket_url: string | null;
source_url: string | null;
}
function fetchEvents(from: string, to: string): EventRow[] {
const db = new Database(DB_PATH, { readonly: true });
try {
return db
.prepare(
`SELECT e.id, v.name AS venue_name, e.title, e.artist,
e.date, e.start_time, e.price, e.ticket_url, e.source_url
FROM events e JOIN venues v ON e.venue_id = v.id
WHERE e.date >= ? AND e.date <= ?
ORDER BY e.date ASC, e.start_time ASC`
)
.all(from, to) as EventRow[];
} finally {
db.close();
}
}
// ---- HTML builder -------------------------------------------------------
function esc(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function buildHtml(events: EventRow[], date: string): string {
const pageUrl = `${APP_URL}/events/by-date?date=${date}`;
const head = `<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
body{font-family:sans-serif;font-size:14px;color:#333;max-width:800px;margin:0 auto;padding:16px}
h1{font-size:20px;border-bottom:3px solid #c00;padding-bottom:6px;color:#c00}
table{border-collapse:collapse;width:100%;margin-bottom:4px}
th,td{border:1px solid #ddd;padding:6px 10px;text-align:left;vertical-align:top}
th{background:#fafafa;font-weight:bold;font-size:12px;color:#666}
.artist{font-weight:bold}
.sub{color:#777;font-size:12px}
a{color:#1a7a3c;text-decoration:none}
a:hover{text-decoration:underline}
.none{color:#aaa;font-style:italic;font-size:12px}
.footer{margin-top:16px;font-size:12px;color:#999;border-top:1px solid #eee;padding-top:8px}
</style>
</head>
<body>
<h1>東京ライブハウス ${esc(fmtJST(date))} のライブ</h1>
<p><a href="${esc(pageUrl)}">${esc(pageUrl)}</a></p>
`;
if (events.length === 0) {
return head + `<p>本日のイベントはまだ登録されていません。</p></body></html>`;
}
let body = `<table>\n<tr><th>会場</th><th>アーティスト / タイトル</th><th>開演</th></tr>\n`;
for (const e of events) {
const url = e.ticket_url ?? e.source_url;
const inner = e.artist
? `<span class="artist">${esc(e.artist)}</span><br><span class="sub">${esc(e.title)}</span>`
: `<span class="sub">${esc(e.title)}</span>`;
const nameCell = url ? `<a href="${esc(url)}">${inner}</a>` : inner;
const time = e.start_time ? esc(e.start_time) : `<span class="none">-</span>`;
body += `<tr><td>${esc(e.venue_name)}</td><td>${nameCell}</td><td>${time}</td></tr>\n`;
}
body += `</table>\n`;
body += `<p class="footer">${events.length} 件 ・ <a href="${esc(pageUrl)}">一覧ページで開く</a></p>\n`;
return head + body + `</body></html>`;
}
// ---- RFC 2047 subject / MIME helpers ------------------------------------
function encodeSubject(str: string): string {
return `=?UTF-8?B?${Buffer.from(str).toString("base64")}?=`;
}
function foldBase64(b64: string): string {
// Chunk base64 into 76-char lines per MIME spec
return b64.match(/.{1,76}/g)?.join("\r\n") ?? b64;
}
function buildMessage(subject: string, html: string): string {
const date = new Date().toUTCString();
const msgId = `<${Date.now()}.recap@${EHLO_DOMAIN}>`;
const b64body = foldBase64(Buffer.from(html).toString("base64"));
return [
`Date: ${date}`,
`Message-ID: ${msgId}`,
`From: Tokyo Livehouse Events <${FROM}>`,
`To: ${TO}`,
`Subject: ${encodeSubject(subject)}`,
"MIME-Version: 1.0",
"Content-Type: text/html; charset=UTF-8",
"Content-Transfer-Encoding: base64",
"",
b64body,
].join("\r\n");
}
// ---- raw SMTP client ----------------------------------------------------
function smtpSend(
host: string,
port: number,
from: string,
to: string,
message: string
): Promise<void> {
return new Promise((resolve, reject) => {
const socket = createConnection(port, host);
let buf = "";
// Phases: 0=greeting 1=ehlo 2=mail-from 3=rcpt-to 4=data 5=body+dot 6=quit 7=done
let phase = 0;
function advance() {
phase++;
switch (phase) {
case 1:
socket.write(`EHLO ${EHLO_DOMAIN}\r\n`);
break;
case 2:
socket.write(`MAIL FROM:<${from}>\r\n`);
break;
case 3:
socket.write(`RCPT TO:<${to}>\r\n`);
break;
case 4:
socket.write("DATA\r\n");
break;
case 5:
// Dot-stuffing: lines beginning with "." get an extra "."
const stuffed = message
.split("\r\n")
.map((l) => (l.startsWith(".") ? "." + l : l))
.join("\r\n");
socket.write(stuffed + "\r\n.\r\n");
break;
case 6:
socket.write("QUIT\r\n");
break;
case 7:
socket.end();
resolve();
break;
}
}
socket.on("data", (chunk) => {
buf += chunk.toString();
let idx: number;
while ((idx = buf.indexOf("\r\n")) !== -1) {
const line = buf.slice(0, idx);
buf = buf.slice(idx + 2);
if (!line) continue;
const code = parseInt(line.slice(0, 3), 10);
const isFinal = line[3] !== "-"; // "-" = continuation line
if (isFinal) {
if (code >= 400) {
const err = new Error(`SMTP ${code}: ${line}`);
socket.destroy();
reject(err);
return;
}
advance();
}
}
});
socket.on("error", reject);
});
}
// ---- main ---------------------------------------------------------------
async function main() {
const date = isoDate(new Date());
console.log(`[recap] querying events for ${date}`);
const events = fetchEvents(date, date);
console.log(`[recap] ${events.length} events found`);
const subject = `東京ライブハウス ${fmtJST(date)} のライブ(${events.length} 件)`;
const html = buildHtml(events, date);
const message = buildMessage(subject, html);
console.log(`[recap] sending to ${TO} via ${MAIL_HOST}:${MAIL_PORT}`);
await smtpSend(MAIL_HOST, MAIL_PORT, FROM, TO, message);
console.log("[recap] sent successfully");
}
main().catch((err) => {
console.error("[recap] error:", err);
process.exit(1);
});
|