-
Notifications
You must be signed in to change notification settings - Fork 2
762 lines (642 loc) · 32.3 KB
/
note-post.yaml
File metadata and controls
762 lines (642 loc) · 32.3 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
name: Note Post via MCP
on:
workflow_dispatch:
inputs:
target_folder:
description: '投稿するnote配下のフォルダ名 (例: exsample)'
required: true
type: string
post_type:
description: '投稿タイプ'
required: true
type: choice
options:
- draft
- publish
default: draft
thumbnail_name:
description: 'サムネイル画像ファイル名(フォルダ内の画像、例: sample-thumbnail.png)'
required: false
type: string
jobs:
post-to-note:
runs-on: ubuntu-latest
container: mcr.microsoft.com/playwright:v1.56.1-jammy
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Validate target folder
run: |
TARGET_PATH="note/${{ github.event.inputs.target_folder }}"
if [ ! -d "$TARGET_PATH" ]; then
echo "❌ Error: Folder $TARGET_PATH does not exist"
exit 1
fi
# mdファイルを探す
MD_FILE=$(find "$TARGET_PATH" -maxdepth 1 -name "*.md" -type f | head -n 1)
if [ -z "$MD_FILE" ]; then
echo "❌ Error: No markdown file found in $TARGET_PATH"
exit 1
fi
echo "✅ Found markdown file: $MD_FILE"
echo "MD_FILE=$MD_FILE" >> $GITHUB_ENV
echo "TARGET_PATH=$TARGET_PATH" >> $GITHUB_ENV
- name: Setup authentication state
run: |
echo '${{ secrets.NOTE_STATE_JSON }}' > ~/.note-state.json
if [ ! -s ~/.note-state.json ]; then
echo "❌ Error: NOTE_STATE_JSON secret is empty"
echo "Please set NOTE_STATE_JSON secret in repository settings"
echo "Run 'npm run login' locally to generate the state file"
exit 1
fi
echo "✅ Authentication state file created"
- name: Determine thumbnail path
run: |
if [ -n "${{ github.event.inputs.thumbnail_name }}" ]; then
THUMBNAIL_PATH="${{ env.TARGET_PATH }}/${{ github.event.inputs.thumbnail_name }}"
if [ -f "$THUMBNAIL_PATH" ]; then
echo "THUMBNAIL_PATH=$THUMBNAIL_PATH" >> $GITHUB_ENV
echo "✅ Using thumbnail: $THUMBNAIL_PATH"
else
echo "⚠️ Warning: Specified thumbnail not found: $THUMBNAIL_PATH"
fi
fi
- name: Install minimal deps
run: |
npm i playwright@1.56.1
echo "✅ Playwright runtime ready (using preinstalled browsers in container)"
- name: Create posting script
run: |
cat > ./post-script.mjs << 'EOFSCRIPT'
import { chromium } from 'playwright';
import fs from 'fs';
import path from 'path';
// parseMarkdown関数
function parseMarkdown(content) {
const lines = content.split('\n');
let title = '';
let body = '';
const tags = [];
let inFrontMatter = false;
let frontMatterEnded = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.trim() === '---') {
if (!frontMatterEnded) {
inFrontMatter = !inFrontMatter;
if (!inFrontMatter) {
frontMatterEnded = true;
}
continue;
}
}
if (inFrontMatter) {
if (line.startsWith('title:')) {
title = line.substring(6).trim().replace(/^["']|["']$/g, '');
} else if (line.startsWith('tags:')) {
const tagsStr = line.substring(5).trim();
if (tagsStr.startsWith('[') && tagsStr.endsWith(']')) {
tags.push(...tagsStr.slice(1, -1).split(',').map(t => t.trim().replace(/^["']|["']$/g, '')));
}
} else if (line.trim().startsWith('-')) {
const tag = line.trim().substring(1).trim().replace(/^["']|["']$/g, '');
if (tag) tags.push(tag);
}
continue;
}
if (!title && line.startsWith('# ')) {
title = line.substring(2).trim();
continue;
}
if (frontMatterEnded || !line.trim().startsWith('---')) {
body += line + '\n';
}
}
return {
title: title || 'Untitled',
body: body.trim(),
tags: tags.filter(Boolean),
};
}
// 画像抽出関数
function extractImages(markdown, baseDir) {
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g;
const images = [];
let match;
while ((match = imageRegex.exec(markdown)) !== null) {
const alt = match[1] || 'image';
const imagePath = match[2];
if (!imagePath.startsWith('http://') && !imagePath.startsWith('https://')) {
const absolutePath = path.resolve(baseDir, imagePath);
if (fs.existsSync(absolutePath)) {
images.push({
alt,
localPath: imagePath,
absolutePath,
placeholder: match[0],
});
}
}
}
return images;
}
// メイン処理
async function main() {
const markdownPath = process.env.MD_FILE;
const thumbnailPath = process.env.THUMBNAIL_PATH || '';
const isPublic = process.env.POST_TYPE === 'publish';
const statePath = path.join(process.env.HOME, '.note-state.json');
console.log('📝 Starting note.com post...');
console.log(' Markdown:', markdownPath);
console.log(' Thumbnail:', thumbnailPath || 'None');
console.log(' Type:', isPublic ? 'Publish' : 'Draft');
const mdContent = fs.readFileSync(markdownPath, 'utf-8');
const { title, body, tags } = parseMarkdown(mdContent);
const baseDir = path.dirname(markdownPath);
const images = extractImages(body, baseDir);
console.log(' Title:', title);
console.log(' Tags:', tags.join(', '));
console.log(' Images:', images.length);
const browser = await chromium.launch({
headless: true,
args: [
'--lang=ja-JP',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-blink-features=AutomationControlled',
],
});
const context = await browser.newContext({
storageState: statePath,
locale: 'ja-JP',
permissions: ['clipboard-read', 'clipboard-write'],
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
viewport: { width: 1280, height: 720 },
deviceScaleFactor: 1,
isMobile: false,
hasTouch: false,
});
const page = await context.newPage();
page.setDefaultTimeout(180000);
// Headless検知を回避
await page.addInitScript(() => {
Object.defineProperty(navigator, 'webdriver', {
get: () => false,
});
// Chrome特有のプロパティを追加
window.chrome = {
runtime: {},
};
// Permissions APIのモック
const originalQuery = window.navigator.permissions.query;
window.navigator.permissions.query = (parameters) => (
parameters.name === 'notifications' ?
Promise.resolve({ state: Notification.permission }) :
originalQuery(parameters)
);
});
await context.grantPermissions(['clipboard-read', 'clipboard-write'], {
origin: 'https://editor.note.com'
});
// まずホームページにアクセスして認証状態を確認
console.log('🔐 Checking authentication status...');
await page.goto('https://note.com', { waitUntil: 'networkidle' });
await page.waitForTimeout(2000);
// ログイン状態の確認(より確実な方法)
const loginCheck = await page.evaluate(() => {
return {
hasNotificationIcon: !!document.querySelector('[aria-label*="通知"]'),
hasNoteCreateButton: Array.from(document.querySelectorAll('a')).some(a => a.textContent.includes('記事を書く')),
hasLoginLink: !!document.querySelector('a[href*="/login"]'),
};
});
// 通知アイコンがあるか、記事を書くボタンがあればログイン済み
const isLoggedIn = loginCheck.hasNotificationIcon || loginCheck.hasNoteCreateButton || !loginCheck.hasLoginLink;
console.log(`🔐 Login status: ${isLoggedIn ? 'Logged in' : 'Not logged in'}`);
if (!isLoggedIn) {
throw new Error('Authentication failed. Please check NOTE_STATE_JSON.');
}
try {
console.log('🌐 Navigating to editor...');
await page.goto('https://editor.note.com/new', {
waitUntil: 'networkidle',
timeout: 180000
});
console.log('⏳ Waiting for editor to load...');
// エディタの基本要素が読み込まれるまで待機
await page.waitForLoadState('networkidle');
await page.waitForSelector('textarea[placeholder*="タイトル"]', { timeout: 30000 });
console.log('✅ Editor loaded successfully');
} catch (error) {
console.error('❌ Failed to load editor page');
console.error('Error:', error.message);
// スクリーンショットを撮影
const screenshotPath = 'error-screenshot.png';
await page.screenshot({ path: screenshotPath, fullPage: true });
console.log(`📸 Screenshot saved: ${screenshotPath}`);
// 現在のURLを表示
console.log('Current URL:', page.url());
// ページのタイトルを表示
const pageTitle = await page.title();
console.log('Page Title:', pageTitle);
await browser.close();
throw error;
}
// サムネイル処理(参考コードの堅牢な方法を採用)
if (thumbnailPath && fs.existsSync(thumbnailPath)) {
console.log('🖼️ Uploading thumbnail...');
try {
// 複数の「画像を追加」ボタンがある場合、最も上のもの(Y座標が小さい)を選択
const candidates = page.locator('button[aria-label="画像を追加"]');
await candidates.first().waitFor({ state: 'visible', timeout: 15000 });
let target = candidates.first();
const cnt = await candidates.count();
if (cnt > 1) {
console.log(`🔍 Found ${cnt} "画像を追加" buttons, selecting the topmost one`);
let minY = Infinity;
let idx = 0;
for (let i = 0; i < cnt; i++) {
const box = await candidates.nth(i).boundingBox();
if (box && box.y < minY) {
minY = box.y;
idx = i;
}
}
target = candidates.nth(idx);
console.log(`✅ Selected button at index ${idx} (Y: ${minY})`);
}
await target.scrollIntoViewIfNeeded();
await target.click({ force: true });
const uploadBtn = page.locator('button:has-text("画像をアップロード")').first();
await uploadBtn.waitFor({ state: 'visible', timeout: 10000 });
// filechooserイベントを待つ(フォールバック付き)
let chooser = null;
try {
[chooser] = await Promise.all([
page.waitForEvent('filechooser', { timeout: 5000 }),
uploadBtn.click({ force: true }),
]);
} catch (e) {
console.log('ℹ️ filechooser event not captured, using fallback');
}
if (chooser) {
await chooser.setFiles(thumbnailPath);
} else {
await uploadBtn.click({ force: true }).catch(() => {});
const fileInput = page.locator('input[type="file"]').first();
await fileInput.waitFor({ state: 'attached', timeout: 10000 });
await fileInput.setInputFiles(thumbnailPath);
}
// トリミングダイアログの処理
const dialog = page.locator('div[role="dialog"]');
await dialog.waitFor({ state: 'visible', timeout: 10000 });
const saveThumbBtn = dialog.locator('button:has-text("保存")').first();
const cropper = dialog.locator('[data-testid="cropper"]').first();
// cropperとsaveボタンの状態を確認
const cropperEl = await cropper.elementHandle();
const saveEl = await saveThumbBtn.elementHandle();
if (cropperEl && saveEl) {
await Promise.race([
page.waitForFunction(
(el) => getComputedStyle(el).pointerEvents === 'none',
cropperEl,
{ timeout: 10000 }
),
page.waitForFunction(
(el) => !el.disabled,
saveEl,
{ timeout: 10000 }
),
]).catch(() => {});
}
await saveThumbBtn.click();
await dialog.waitFor({ state: 'hidden', timeout: 10000 }).catch(() => {});
await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
// 反映確認
const changedBtn = page.locator('button[aria-label="画像を変更"]');
const addBtn = page.locator('button[aria-label="画像を追加"]');
let applied = false;
try {
await changedBtn.waitFor({ state: 'visible', timeout: 5000 });
applied = true;
} catch {}
if (!applied) {
try {
await addBtn.waitFor({ state: 'hidden', timeout: 5000 });
applied = true;
} catch {}
}
console.log(applied ? '✅ Thumbnail uploaded and verified' : '⚠️ Thumbnail uploaded but verification uncertain');
} catch (err) {
console.log('⚠️ Thumbnail upload failed:', err.message);
}
}
// タイトル設定
console.log('📝 Setting title...');
console.log(` Target title: "${title}"`);
await page.waitForTimeout(500);
const titleField = page.locator('textarea[placeholder*="タイトル"]').first();
// タイトル入力前の値を確認
const beforeValue = await titleField.inputValue();
console.log(` Before fill: "${beforeValue}"`);
// 方法1: fillを試す
await titleField.fill(title);
await page.waitForTimeout(300);
// 入力後の値を確認
const afterFillValue = await titleField.inputValue();
console.log(` After fill: "${afterFillValue}"`);
// fillが失敗している場合、キーボード入力にフォールバック
if (afterFillValue !== title) {
console.log(' ℹ️ fill() did not work, trying keyboard input...');
await titleField.click();
await titleField.clear();
await page.keyboard.type(title);
await page.waitForTimeout(300);
const afterTypeValue = await titleField.inputValue();
console.log(` After keyboard type: "${afterTypeValue}"`);
}
console.log('✅ Title set');
// 本文設定
console.log('📝 Setting body...');
await page.waitForTimeout(500);
const bodyBox = page.locator('div[contenteditable="true"][role="textbox"]').first();
await bodyBox.waitFor({ state: 'visible', timeout: 10000 });
// Adobe Expressのヘルプが邪魔する場合に備えて、Escapeキーで全てのモーダルを閉じる
await page.keyboard.press('Escape');
await page.waitForTimeout(300);
// 要素にフォーカスを当てる(クリックの代わりに直接フォーカス)
await bodyBox.evaluate(el => {
el.focus();
// カーソルを末尾に移動
const range = document.createRange();
const sel = window.getSelection();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
});
// 画像を含まない場合は、Markdown全体を一括でクリップボード経由でペースト
if (images.length === 0) {
console.log('📋 Pasting entire content via clipboard...');
console.log(` Content length: ${body.length} characters`);
// クリップボードに書き込む
await page.evaluate(async (text) => {
await navigator.clipboard.writeText(text);
}, body);
// 本文エリアがフォーカスされているか確認
const isFocused = await bodyBox.evaluate(el => {
return document.activeElement === el;
});
console.log(` Body box focused: ${isFocused}`);
// ペースト
await page.keyboard.press('Control+V');
await page.waitForTimeout(1000);
// ペースト後の内容を確認
const afterContent = await bodyBox.textContent();
console.log(` After paste length: ${afterContent.length} characters`);
console.log('✅ Content pasted');
} else {
// 画像がある場合は、画像マーカーで分割して処理
console.log(`📋 Processing content with ${images.length} images...`);
// 画像の位置で本文を分割
const parts = [];
let lastIndex = 0;
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g;
let match;
while ((match = imageRegex.exec(body)) !== null) {
// 画像の前のテキスト
if (match.index > lastIndex) {
parts.push({ type: 'text', content: body.slice(lastIndex, match.index) });
}
// 画像
const imagePath = match[2];
const image = images.find(img => img.localPath === imagePath);
if (image) {
parts.push({ type: 'image', image: image });
}
lastIndex = match.index + match[0].length;
}
// 最後のテキスト
if (lastIndex < body.length) {
parts.push({ type: 'text', content: body.slice(lastIndex) });
}
// 各パートを順番に挿入
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
console.log(` Processing part ${i+1}/${parts.length}: type=${part.type}`);
if (part.type === 'text' && part.content.trim()) {
console.log(` Text part length: ${part.content.length} characters`);
// 参考コード(index.ts)と同じ処理を実装
const lines = part.content.split('\n');
let urlCount = 0;
let previousLineWasList = false;
let previousLineWasQuote = false;
let previousLineWasHorizontalRule = false;
for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
const line = lines[lineIdx];
const isLastLine = lineIdx === lines.length - 1;
// コードブロックの開始を検出
if (line.trim().startsWith('```')) {
// コードブロック全体(```から```まで)を収集
const codeBlockLines = [line];
let j = lineIdx + 1;
while (j < lines.length) {
codeBlockLines.push(lines[j]);
if (lines[j].trim().startsWith('```')) {
break;
}
j++;
}
// コードブロック全体をクリップボードで貼り付け
const codeBlockContent = codeBlockLines.join('\n');
await page.evaluate((text) => {
return navigator.clipboard.writeText(text);
}, codeBlockContent);
await page.keyboard.press('Control+V');
await page.waitForTimeout(300);
// コードブロックの後に改行(最終行でない場合)
if (j < lines.length - 1) {
await page.keyboard.press('Enter');
}
// インデックスを進める
lineIdx = j;
// フラグをリセット
previousLineWasList = false;
previousLineWasQuote = false;
previousLineWasHorizontalRule = false;
continue;
}
// 水平線かどうかをチェック
const isHorizontalRule = line.trim() === '---';
// 水平線の直後の空行をスキップ
if (previousLineWasHorizontalRule && line.trim() === '') {
previousLineWasHorizontalRule = false;
continue;
}
previousLineWasHorizontalRule = false;
// リスト項目かどうかをチェック
const isBulletList = /^(\s*)- /.test(line);
const isNumberedList = /^(\s*)\d+\.\s/.test(line);
const isCurrentLineList = isBulletList || isNumberedList;
// 引用かどうかをチェック
const isQuote = /^>/.test(line);
// 通常のテキスト行を処理
let processedLine = line;
// 前の行がリスト項目で、現在の行もリスト項目なら、マークダウン記号を削除
if (previousLineWasList && isCurrentLineList) {
if (isBulletList) {
processedLine = processedLine.replace(/^(\s*)- /, '$1');
}
if (isNumberedList) {
processedLine = processedLine.replace(/^(\s*)\d+\.\s/, '$1');
}
}
// 前の行が引用で、現在の行も引用なら、マークダウン記号を削除
if (previousLineWasQuote && isQuote) {
processedLine = processedLine.replace(/^>\s?/, '');
}
// 行をキーボード入力
await page.keyboard.type(processedLine);
// 次の行のために、現在の行の状態を記録
previousLineWasList = isCurrentLineList;
previousLineWasQuote = isQuote;
previousLineWasHorizontalRule = isHorizontalRule;
// URL単独行の場合、追加でEnterを押してリンクカード化
const isUrlLine = /^https?:\/\/[^\s]+$/.test(line.trim());
if (isUrlLine) {
await page.keyboard.press('Enter');
await page.waitForTimeout(1200); // リンクカード展開
urlCount++;
// 次の行がある場合、ArrowDownでカード外に移動
if (!isLastLine) {
await page.keyboard.press('ArrowDown');
await page.waitForTimeout(150);
}
} else {
// URL以外の行の場合のみ、最後の行でなければ改行
if (!isLastLine) {
await page.keyboard.press('Enter');
}
}
}
if (urlCount > 0) {
console.log(` ℹ️ Processed ${urlCount} URL line(s) with Enter for link cards`);
}
console.log(` ✅ Text typed`);
} else if (part.type === 'image' && fs.existsSync(part.image.absolutePath)) {
console.log(` 📸 Uploading image: ${part.image.localPath}`);
// 画像をクリップボードにコピーしてペースト
const imageBuffer = fs.readFileSync(part.image.absolutePath);
const base64Image = imageBuffer.toString('base64');
const mimeType = part.image.absolutePath.endsWith('.png') ? 'image/png' :
part.image.absolutePath.endsWith('.jpg') || part.image.absolutePath.endsWith('.jpeg') ? 'image/jpeg' :
'image/gif';
await page.evaluate(async ({ base64, mime }) => {
const blob = await fetch(`data:${mime};base64,${base64}`).then(r => r.blob());
await navigator.clipboard.write([
new ClipboardItem({ [mime]: blob })
]);
}, { base64: base64Image, mime: mimeType });
await page.keyboard.press('Control+V');
await page.waitForTimeout(1000);
// 画像貼り付け後、改行してテキスト入力モードに戻る
await page.keyboard.press('Enter');
await page.waitForTimeout(300);
console.log(` ✅ Image uploaded: ${part.image.localPath}`);
}
}
console.log('✅ Content with images inserted');
}
// コンテンツが反映されるまで待機
console.log('⏳ Waiting for content to be reflected...');
await page.waitForTimeout(2000);
// 入力内容の最終確認
const finalTitleValue = await page.locator('textarea[placeholder*="タイトル"]').first().inputValue();
const finalBodyContent = await page.locator('div[contenteditable="true"][role="textbox"]').first().textContent();
console.log(`📊 Final check - Title: ${finalTitleValue.length} chars, Body: ${finalBodyContent.length} chars`);
if (!isPublic) {
// 下書き保存
console.log('💾 Saving draft...');
const saveBtn = page.locator('button:has-text("下書き保存")').first();
await saveBtn.waitFor({ state: 'visible' });
// 保存前にもう一度待機
await page.waitForTimeout(1000);
await saveBtn.click();
// 保存完了メッセージを待つ
await page.locator('text=保存しました').waitFor({ timeout: 10000 }).catch(() => {
console.log('ℹ️ "保存しました" message not found, but continuing...');
});
await page.waitForTimeout(2000);
console.log('✅ Draft saved');
} else {
// 公開処理
const proceedBtn = page.locator('button:has-text("公開に進む")').first();
await proceedBtn.waitFor({ state: 'visible' });
await proceedBtn.click();
await page.waitForTimeout(2000);
// タグ追加
if (tags.length > 0) {
const tagInput = page.locator('input[placeholder*="ハッシュタグ"]').first();
await tagInput.waitFor({ state: 'visible' });
for (const tag of tags) {
await tagInput.fill(tag);
await page.keyboard.press('Enter');
await page.waitForTimeout(200);
}
console.log('✅ Tags added');
}
// 投稿
const publishBtn = page.locator('button:has-text("投稿する")').first();
await publishBtn.waitFor({ state: 'visible' });
await publishBtn.click();
await page.waitForTimeout(5000);
console.log('✅ Published');
}
const finalUrl = page.url();
console.log('🎉 Success!');
console.log(' URL:', finalUrl);
await browser.close();
}
main().catch(err => {
console.error('❌ Error:', err);
process.exit(1);
});
EOFSCRIPT
echo "✅ Posting script created"
- name: Execute post to note.com
run: |
export MD_FILE="${{ env.MD_FILE }}"
export THUMBNAIL_PATH="${{ env.THUMBNAIL_PATH }}"
export POST_TYPE="${{ github.event.inputs.post_type }}"
node ./post-script.mjs
- name: Upload error screenshot
if: failure()
uses: actions/upload-artifact@v4
with:
name: error-screenshot
path: error-screenshot.png
if-no-files-found: ignore
retention-days: 7
- name: Summary
if: always()
run: |
echo "## 📝 Note Post Result" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Item | Value |" >> $GITHUB_STEP_SUMMARY
echo "|------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| Target Folder | \`${{ github.event.inputs.target_folder }}\` |" >> $GITHUB_STEP_SUMMARY
echo "| Post Type | **${{ github.event.inputs.post_type }}** |" >> $GITHUB_STEP_SUMMARY
echo "| Markdown File | \`${{ env.MD_FILE }}\` |" >> $GITHUB_STEP_SUMMARY
if [ -n "${{ env.THUMBNAIL_PATH }}" ]; then
echo "| Thumbnail | \`${{ env.THUMBNAIL_PATH }}\` |" >> $GITHUB_STEP_SUMMARY
else
echo "| Thumbnail | None |" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "Completed at: \`$(date)\`" >> $GITHUB_STEP_SUMMARY