feat: Alexa TTS API サーバーを追加
- alexa-api/: Echo デバイスに TTS を送る Node.js API サーバー
- server.js: alexa-remote2 を使わない直接 Alexa API 実装
- GET /api/language で CSRF トークン取得
- GET /api/bootstrap でカスタマー ID 取得
- POST /api/behaviors/preview で TTS 実行
- Dockerfile + docker-compose.yml: windmill_windmill-internal ネットワーク接続
- auth4.js: Amazon Japan OpenID フローで Cookie 取得(WORKING)
- scripts/alexa_speak.ts: Windmill から alexa-api を呼び出すスクリプト
Windmill (u/admin/alexa_speak) → alexa_api:3500/speak → Echo デバイス の
パスで日本語 TTS が動作することを確認済み。
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
6
alexa-api/.env.example
Normal file
6
alexa-api/.env.example
Normal file
@@ -0,0 +1,6 @@
|
||||
# alexa-api/.env
|
||||
# このファイルをコピーして .env を作成し、ALEXA_COOKIE に値を設定する
|
||||
# .env は Git にコミットしない(.gitignore 参照)
|
||||
|
||||
# Amazon Cookie(auth.js を実行して取得)
|
||||
ALEXA_COOKIE=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
2
alexa-api/.gitignore
vendored
Normal file
2
alexa-api/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
.env
|
||||
14
alexa-api/Dockerfile
Normal file
14
alexa-api/Dockerfile
Normal file
@@ -0,0 +1,14 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 依存パッケージのみ先にコピー(キャッシュ活用)
|
||||
COPY package*.json ./
|
||||
RUN npm install --omit=dev
|
||||
|
||||
# ソースをコピー
|
||||
COPY server.js .
|
||||
|
||||
EXPOSE 3500
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
70
alexa-api/auth.js
Normal file
70
alexa-api/auth.js
Normal file
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* alexa-api/auth.js
|
||||
* ローカル PC で実行して Amazon Cookie を取得するスクリプト。
|
||||
*
|
||||
* 使い方:
|
||||
* cd alexa-api
|
||||
* npm install alexa-cookie2
|
||||
* node auth.js
|
||||
*
|
||||
* → ブラウザで http://localhost:3456 を開く
|
||||
* → Amazon にログイン
|
||||
* → コンソールに Cookie が表示される
|
||||
* → その値を Windmill Variable "u/admin/ALEXA_COOKIE" に登録
|
||||
*/
|
||||
|
||||
const AlexaCookie = require('alexa-cookie2');
|
||||
|
||||
const PROXY_PORT = 3456;
|
||||
|
||||
console.log('==============================================');
|
||||
console.log(' Alexa Cookie 取得ツール');
|
||||
console.log('==============================================');
|
||||
console.log(`\n認証プロキシを起動中... (port ${PROXY_PORT})`);
|
||||
console.log('\n【手順】');
|
||||
console.log(` 1. ブラウザで http://localhost:${PROXY_PORT} を開く`);
|
||||
console.log(' 2. Amazon アカウントにログイン(amazon.co.jp)');
|
||||
console.log(' 3. ログイン完了後、このコンソールに Cookie が表示される\n');
|
||||
|
||||
AlexaCookie.generateAlexaCookie(
|
||||
'',
|
||||
{
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
setupProxy: true,
|
||||
proxyPort: PROXY_PORT,
|
||||
proxyOwnIp: '127.0.0.1',
|
||||
proxyListenBind: '0.0.0.0',
|
||||
logger: (msg) => {
|
||||
if (!msg.includes('verbose') && !msg.includes('DEBUG')) {
|
||||
console.log('[auth]', msg);
|
||||
}
|
||||
},
|
||||
},
|
||||
(err, cookie) => {
|
||||
// alexa-cookie2 はブラウザを開くよう促すメッセージも err として渡してくる
|
||||
if (err) {
|
||||
const msg = err.message || String(err);
|
||||
if (msg.includes('Please open')) {
|
||||
// これは実際のエラーではなく「ブラウザで開いて」という指示
|
||||
console.log('\n>>> ブラウザで http://localhost:3456/ を開いて Amazon にログインしてください <<<\n');
|
||||
// プロキシを生かしたまま待機(process.exit しない)
|
||||
return;
|
||||
}
|
||||
console.error('\n[ERROR] 認証失敗:', msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' Cookie 取得成功!');
|
||||
console.log('==============================================');
|
||||
console.log('\n以下の値を Windmill Variable に登録してください:');
|
||||
console.log(' パス: u/admin/ALEXA_COOKIE');
|
||||
console.log(' Secret: ON(チェックを入れる)');
|
||||
console.log('\n--- Cookie ---');
|
||||
console.log(cookie);
|
||||
console.log('--- ここまで ---\n');
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
76
alexa-api/auth2.js
Normal file
76
alexa-api/auth2.js
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* auth2.js - alexa-remote2 自身の認証フローを使う
|
||||
* alexa-cookie2 より確実(ライブラリ内蔵の OAuth プロキシを使用)
|
||||
*
|
||||
* 使い方:
|
||||
* node auth2.js
|
||||
* → ブラウザで http://localhost:3001/ を開いて Amazon にログイン
|
||||
* → 成功するとコンソールに Cookie が出力される → .env に保存
|
||||
*/
|
||||
|
||||
const AlexaRemote = require('alexa-remote2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PORT = 3001;
|
||||
|
||||
console.log('==============================================');
|
||||
console.log(' Alexa 認証ツール (alexa-remote2 内蔵プロキシ)');
|
||||
console.log('==============================================');
|
||||
console.log(`\nプロキシ起動中... (port ${PORT})`);
|
||||
console.log(`\n【手順】ブラウザで http://localhost:${PORT}/ を開いて Amazon にログイン\n`);
|
||||
|
||||
const alexa = new AlexaRemote();
|
||||
|
||||
alexa.init(
|
||||
{
|
||||
cookie: null,
|
||||
alexaServiceHost: 'alexa.amazon.co.jp',
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
useWsMqtt: false,
|
||||
setupProxy: true,
|
||||
proxyOwnIp: '127.0.0.1',
|
||||
proxyPort: PORT,
|
||||
proxyListenBind: '0.0.0.0',
|
||||
logger: console.log,
|
||||
onSucess: (refreshedCookie) => {
|
||||
// 認証成功時にリフレッシュされた Cookie を受け取る
|
||||
console.log('\n[onSucess] Cookie refreshed');
|
||||
},
|
||||
},
|
||||
(err, result) => {
|
||||
if (err) {
|
||||
const msg = err.message || String(err);
|
||||
if (msg.includes('open') && (msg.includes('http://') || msg.includes('localhost'))) {
|
||||
console.log(`\n>>> ブラウザで http://localhost:${PORT}/ を開いてください <<<\n`);
|
||||
// プロキシを生かしたまま待機
|
||||
return;
|
||||
}
|
||||
console.error('\n[ERROR]', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
// 認証成功
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
|
||||
// alexa-remote2 内部の Cookie を取得
|
||||
const cookie = alexa.cookie || alexa._options?.cookie;
|
||||
if (cookie) {
|
||||
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
|
||||
console.log('\n以下を alexa-api/.env の ALEXA_COOKIE に設定してください:\n');
|
||||
console.log('ALEXA_COOKIE=' + cookieStr);
|
||||
|
||||
// .env に自動保存
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
|
||||
console.log(`\n.env に自動保存しました: ${envPath}`);
|
||||
} else {
|
||||
console.log('Cookie を取得できませんでした。alexa オブジェクト:', Object.keys(alexa));
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
76
alexa-api/auth3.js
Normal file
76
alexa-api/auth3.js
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* auth3.js - メール/パスワードで直接認証(2FA なしのアカウント向け)
|
||||
*
|
||||
* 使い方:
|
||||
* AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="yourpass" node auth3.js
|
||||
*
|
||||
* 成功すると .env を更新して終了します。
|
||||
*/
|
||||
|
||||
const AlexaRemote = require('alexa-remote2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const email = process.env.AMAZON_EMAIL;
|
||||
const password = process.env.AMAZON_PASSWORD;
|
||||
|
||||
if (!email || !password) {
|
||||
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
|
||||
console.error(' 例: AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="pass" node auth3.js');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[INFO] ${email} でログイン試行中...`);
|
||||
|
||||
const alexa = new AlexaRemote();
|
||||
|
||||
alexa.init(
|
||||
{
|
||||
email,
|
||||
password,
|
||||
alexaServiceHost: 'alexa.amazon.co.jp',
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
useWsMqtt: false,
|
||||
setupProxy: false,
|
||||
logger: (msg) => {
|
||||
if (!msg.includes('verbose') && !msg.includes('Bearer')) {
|
||||
console.log('[alexa]', msg);
|
||||
}
|
||||
},
|
||||
onSucess: (refreshedCookie) => {
|
||||
saveCookie(refreshedCookie, 'onSucess refresh');
|
||||
},
|
||||
},
|
||||
(err) => {
|
||||
if (err) {
|
||||
console.error('[ERROR] 認証失敗(詳細):', err);
|
||||
console.error('\n考えられる原因:');
|
||||
console.error(' - パスワードが違う');
|
||||
console.error(' - Amazon が CAPTCHA を要求している(後で再試行)');
|
||||
console.error(' - 2FA が実際は有効になっている');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 認証成功
|
||||
const cookie = alexa.cookie;
|
||||
saveCookie(cookie, 'init success');
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
|
||||
function saveCookie(cookie, source) {
|
||||
if (!cookie) {
|
||||
console.error(`[${source}] Cookie が空です`);
|
||||
return;
|
||||
}
|
||||
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
console.log('.env を更新しました:', envPath);
|
||||
console.log('Cookie length:', cookieStr.length);
|
||||
}
|
||||
190
alexa-api/auth4.js
Normal file
190
alexa-api/auth4.js
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* auth4.js - Amazon Japan OpenID フローを正しく再現するカスタム認証スクリプト
|
||||
* alexa-cookie2 の古いエンドポイント問題を回避して直接フォームを処理する
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const EMAIL = process.env.AMAZON_EMAIL;
|
||||
const PASSWORD = process.env.AMAZON_PASSWORD;
|
||||
|
||||
if (!EMAIL || !PASSWORD) {
|
||||
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const ALEXA_LOGIN_URL =
|
||||
'https://www.amazon.co.jp/ap/signin?' +
|
||||
new URLSearchParams({
|
||||
'openid.assoc_handle': 'amzn_dp_project_dee_jp',
|
||||
'openid.mode': 'checkid_setup',
|
||||
'openid.ns': 'http://specs.openid.net/auth/2.0',
|
||||
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.return_to': 'https://alexa.amazon.co.jp/api/apps/v1/token',
|
||||
'pageId': 'amzn_dp_project_dee_jp',
|
||||
}).toString();
|
||||
|
||||
const USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
|
||||
|
||||
let cookieJar = {};
|
||||
|
||||
function setCookies(setCookieHeaders) {
|
||||
if (!setCookieHeaders) return;
|
||||
const headers = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders];
|
||||
for (const h of headers) {
|
||||
const [kv] = h.split(';');
|
||||
const [k, v] = kv.trim().split('=');
|
||||
if (k && v !== undefined) cookieJar[k.trim()] = v.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function getCookieHeader() {
|
||||
return Object.entries(cookieJar)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
function request(url, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const reqOpts = {
|
||||
hostname: parsed.hostname,
|
||||
path: parsed.pathname + parsed.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT,
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Accept': 'text/html,application/xhtml+xml,*/*;q=0.8',
|
||||
'Cookie': getCookieHeader(),
|
||||
...(options.headers || {}),
|
||||
},
|
||||
};
|
||||
|
||||
const req = https.request(reqOpts, (res) => {
|
||||
setCookies(res.headers['set-cookie']);
|
||||
let body = '';
|
||||
res.on('data', (d) => (body += d));
|
||||
res.on('end', () => {
|
||||
resolve({ status: res.statusCode, headers: res.headers, body });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// HTML の hidden フィールドを抽出
|
||||
function extractHiddenFields(html) {
|
||||
const fields = {};
|
||||
const re = /<input[^>]+type=["']?hidden["']?[^>]*>/gi;
|
||||
let match;
|
||||
while ((match = re.exec(html)) !== null) {
|
||||
const tag = match[0];
|
||||
const name = (tag.match(/name=["']([^"']+)["']/) || [])[1];
|
||||
const value = (tag.match(/value=["']([^"']*)["']/) || ['', ''])[1];
|
||||
if (name) fields[name] = value;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
// フォームの action URL を抽出
|
||||
function extractFormAction(html) {
|
||||
const m = html.match(/id="ap_login_form"[^>]+action="([^"]+)"/);
|
||||
if (m) return m[1].replace(/&/g, '&');
|
||||
const m2 = html.match(/name="signIn"[^>]+action="([^"]+)"/);
|
||||
if (m2) return m2[1].replace(/&/g, '&');
|
||||
return null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[1] ログインページ取得中...');
|
||||
const page1 = await request(ALEXA_LOGIN_URL);
|
||||
console.log(` Status: ${page1.status}, Cookies: ${Object.keys(cookieJar).join(', ')}`);
|
||||
|
||||
if (page1.status !== 200) {
|
||||
console.error(`[ERROR] ログインページ取得失敗: ${page1.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// フォーム情報を抽出
|
||||
const action = extractFormAction(page1.body);
|
||||
const hidden = extractHiddenFields(page1.body);
|
||||
|
||||
if (!action) {
|
||||
console.error('[ERROR] ログインフォームが見つかりません。HTMLを確認します:');
|
||||
console.error(page1.body.substring(0, 500));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[2] フォーム送信先: ${action}`);
|
||||
console.log(` Hidden fields: ${Object.keys(hidden).join(', ')}`);
|
||||
|
||||
// フォームデータ構築
|
||||
const formData = new URLSearchParams({
|
||||
...hidden,
|
||||
email: EMAIL,
|
||||
password: PASSWORD,
|
||||
rememberMe: 'true',
|
||||
}).toString();
|
||||
|
||||
console.log('[3] 認証送信中...');
|
||||
const page2 = await request(action, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': ALEXA_LOGIN_URL,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
console.log(` Status: ${page2.status}`);
|
||||
console.log(` Location: ${page2.headers.location || '(none)'}`);
|
||||
console.log(` Cookies after login: ${Object.keys(cookieJar).join(', ')}`);
|
||||
|
||||
// リダイレクトをたどる
|
||||
let current = page2;
|
||||
let redirectCount = 0;
|
||||
while (current.status >= 300 && current.status < 400 && current.headers.location && redirectCount < 10) {
|
||||
const loc = current.headers.location;
|
||||
const nextUrl = loc.startsWith('http') ? loc : `https://www.amazon.co.jp${loc}`;
|
||||
console.log(`[${4 + redirectCount}] Redirect → ${nextUrl.substring(0, 80)}...`);
|
||||
current = await request(nextUrl);
|
||||
console.log(` Status: ${current.status}, New Cookies: ${Object.keys(cookieJar).join(', ')}`);
|
||||
redirectCount++;
|
||||
}
|
||||
|
||||
// 成功判定: at-acbjp または session-token が含まれているか
|
||||
const cookie = getCookieHeader();
|
||||
const hasAlexaToken = cookie.includes('at-acbjp') || cookie.includes('session-token');
|
||||
|
||||
if (!hasAlexaToken) {
|
||||
console.error('[ERROR] 認証に失敗しました。取得できたCookieに認証トークンが含まれていません。');
|
||||
console.error('取得済みCookieキー:', Object.keys(cookieJar).join(', '));
|
||||
if (current.body.includes('captcha') || current.body.includes('CAPTCHA')) {
|
||||
console.error('※ CAPTCHA が要求されています。しばらく待ってから再試行してください。');
|
||||
}
|
||||
if (current.body.includes('password') && current.body.includes('error')) {
|
||||
console.error('※ パスワードが間違っている可能性があります。');
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// .env に保存
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, `ALEXA_COOKIE=${cookie}\n`);
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
console.log(`.env を保存しました: ${envPath}`);
|
||||
console.log(`Cookie 長さ: ${cookie.length} 文字`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[FATAL]', err);
|
||||
process.exit(1);
|
||||
});
|
||||
19
alexa-api/docker-compose.yml
Normal file
19
alexa-api/docker-compose.yml
Normal file
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
alexa-api:
|
||||
build: .
|
||||
container_name: alexa_api
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- PORT=3500
|
||||
networks:
|
||||
- windmill_windmill-internal
|
||||
# 外部には公開しない(Windmill ワーカーから内部ネットワーク経由でのみアクセス)
|
||||
# デバッグ時は以下のコメントを外す:
|
||||
# ports:
|
||||
# - "127.0.0.1:3500:3500"
|
||||
|
||||
networks:
|
||||
windmill_windmill-internal:
|
||||
external: true
|
||||
1257
alexa-api/package-lock.json
generated
Normal file
1257
alexa-api/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
16
alexa-api/package.json
Normal file
16
alexa-api/package.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "alexa-api",
|
||||
"version": "1.0.0",
|
||||
"description": "Alexa TTS API server for Windmill integration",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"alexa-cookie2": "^5.0.3",
|
||||
"alexa-remote2": "^5.0.0"
|
||||
}
|
||||
}
|
||||
208
alexa-api/server.js
Normal file
208
alexa-api/server.js
Normal file
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* alexa-api/server.js
|
||||
* Windmill から Echo デバイスに TTS を送る API サーバー
|
||||
* 直接 Alexa API を叩く実装(alexa-remote2 不使用)
|
||||
*
|
||||
* Endpoints:
|
||||
* POST /speak { device: "デバイス名 or serial", text: "しゃべる内容" }
|
||||
* GET /devices デバイス一覧取得
|
||||
* GET /health ヘルスチェック
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const express = require('express');
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
const PORT = process.env.PORT || 3500;
|
||||
const ALEXA_HOST = 'alexa.amazon.co.jp';
|
||||
const ALEXA_COOKIE = process.env.ALEXA_COOKIE;
|
||||
|
||||
if (!ALEXA_COOKIE) {
|
||||
console.error('[ERROR] ALEXA_COOKIE 環境変数が設定されていません。');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ---- キャッシュ ----
|
||||
|
||||
let cachedDevices = null;
|
||||
let cachedCustomerId = null;
|
||||
let deviceCacheExpires = 0;
|
||||
|
||||
// ---- HTTP ヘルパー ----
|
||||
|
||||
function httpsRequest(path, options, extraCookies) {
|
||||
options = options || {};
|
||||
extraCookies = extraCookies || '';
|
||||
return new Promise(function(resolve, reject) {
|
||||
var allCookies = ALEXA_COOKIE + (extraCookies ? '; ' + extraCookies : '');
|
||||
var reqOpts = {
|
||||
hostname: ALEXA_HOST,
|
||||
path: path,
|
||||
method: options.method || 'GET',
|
||||
headers: Object.assign({
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Accept': 'application/json, text/plain, */*',
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Cookie': allCookies,
|
||||
}, options.headers || {}),
|
||||
};
|
||||
var req = https.request(reqOpts, function(res) {
|
||||
var body = '';
|
||||
res.on('data', function(d) { body += d; });
|
||||
res.on('end', function() { resolve({ status: res.statusCode, headers: res.headers, body: body }); });
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Alexa API ヘルパー ----
|
||||
|
||||
async function getCsrfToken() {
|
||||
var res = await httpsRequest('/api/language');
|
||||
var setCookies = res.headers['set-cookie'] || [];
|
||||
var csrfCookieStr = setCookies.find(function(c) { return c.startsWith('csrf='); });
|
||||
if (!csrfCookieStr) throw new Error('CSRF token not found');
|
||||
return csrfCookieStr.split('=')[1].split(';')[0];
|
||||
}
|
||||
|
||||
async function getCustomerId() {
|
||||
if (cachedCustomerId) return cachedCustomerId;
|
||||
var res = await httpsRequest('/api/bootstrap');
|
||||
if (res.status !== 200) throw new Error('Bootstrap API failed: ' + res.status);
|
||||
var data = JSON.parse(res.body);
|
||||
cachedCustomerId = data.authentication && data.authentication.customerId;
|
||||
if (!cachedCustomerId) throw new Error('customerId not found');
|
||||
return cachedCustomerId;
|
||||
}
|
||||
|
||||
async function getDevices(force) {
|
||||
var now = Date.now();
|
||||
if (!force && cachedDevices && now < deviceCacheExpires) return cachedDevices;
|
||||
var res = await httpsRequest('/api/devices-v2/device?cached=false');
|
||||
if (res.status !== 200) throw new Error('Devices API failed: ' + res.status);
|
||||
var data = JSON.parse(res.body);
|
||||
cachedDevices = data.devices || [];
|
||||
deviceCacheExpires = now + 5 * 60 * 1000;
|
||||
return cachedDevices;
|
||||
}
|
||||
|
||||
function findDevice(devices, nameOrSerial) {
|
||||
var bySerial = devices.find(function(d) { return d.serialNumber === nameOrSerial; });
|
||||
if (bySerial) return bySerial;
|
||||
var lower = nameOrSerial.toLowerCase();
|
||||
var byName = devices.find(function(d) { return d.accountName && d.accountName.toLowerCase() === lower; });
|
||||
if (byName) return byName;
|
||||
return devices.find(function(d) { return d.accountName && d.accountName.toLowerCase().includes(lower); });
|
||||
}
|
||||
|
||||
// ---- API エンドポイント ----
|
||||
|
||||
// POST /speak
|
||||
app.post('/speak', async function(req, res) {
|
||||
var body = req.body || {};
|
||||
var device = body.device;
|
||||
var text = body.text;
|
||||
|
||||
if (!device || !text) {
|
||||
return res.status(400).json({ error: 'device と text は必須です' });
|
||||
}
|
||||
|
||||
console.log('[SPEAK] device="' + device + '" text="' + text + '"');
|
||||
|
||||
try {
|
||||
var results = await Promise.all([getCsrfToken(), getCustomerId(), getDevices()]);
|
||||
var csrfToken = results[0];
|
||||
var customerId = results[1];
|
||||
var devices = results[2];
|
||||
|
||||
var target = findDevice(devices, device);
|
||||
if (!target) {
|
||||
var names = devices.map(function(d) { return d.accountName; }).join(', ');
|
||||
return res.status(404).json({ error: 'デバイス "' + device + '" が見つかりません', available: names });
|
||||
}
|
||||
|
||||
console.log(' -> ' + target.accountName + ' (type=' + target.deviceType + ', serial=' + target.serialNumber + ')');
|
||||
|
||||
var sequenceObj = {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.Sequence',
|
||||
startNode: {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode',
|
||||
type: 'Alexa.Speak',
|
||||
operationPayload: {
|
||||
deviceType: target.deviceType,
|
||||
deviceSerialNumber: target.serialNumber,
|
||||
customerId: customerId,
|
||||
locale: 'ja-JP',
|
||||
textToSpeak: text,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
var bodyStr = JSON.stringify({
|
||||
behaviorId: 'PREVIEW',
|
||||
sequenceJson: JSON.stringify(sequenceObj),
|
||||
status: 'ENABLED',
|
||||
});
|
||||
|
||||
var ttsRes = await httpsRequest('/api/behaviors/preview', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'csrf': csrfToken,
|
||||
'Referer': 'https://alexa.amazon.co.jp/spa/index.html',
|
||||
'Origin': 'https://alexa.amazon.co.jp',
|
||||
},
|
||||
body: bodyStr,
|
||||
}, 'csrf=' + csrfToken);
|
||||
|
||||
if (ttsRes.status === 200 || ttsRes.status === 202) {
|
||||
console.log(' [OK] TTS sent to ' + target.accountName);
|
||||
res.json({ ok: true, device: target.accountName, text: text });
|
||||
} else {
|
||||
console.error(' [ERROR] TTS failed: ' + ttsRes.status + ' ' + ttsRes.body);
|
||||
res.status(502).json({ error: 'Alexa API error: ' + ttsRes.status, body: ttsRes.body });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[ERROR] /speak:', err.message);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /devices
|
||||
app.get('/devices', async function(req, res) {
|
||||
try {
|
||||
var devices = await getDevices(true);
|
||||
res.json(devices.map(function(d) {
|
||||
return { name: d.accountName, type: d.deviceType, serial: d.serialNumber, online: d.online, family: d.deviceFamily };
|
||||
}));
|
||||
} catch (err) {
|
||||
console.error('[ERROR] /devices:', err.message);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /health
|
||||
app.get('/health', function(req, res) {
|
||||
res.json({ ok: true, cookieLength: ALEXA_COOKIE.length });
|
||||
});
|
||||
|
||||
// ---- 起動 ----
|
||||
|
||||
app.listen(PORT, '0.0.0.0', async function() {
|
||||
console.log('[INFO] alexa-api server listening on port ' + PORT);
|
||||
try {
|
||||
var customerId = await getCustomerId();
|
||||
console.log('[INFO] Customer ID: ' + customerId);
|
||||
var devices = await getDevices();
|
||||
var echoDevices = devices.filter(function(d) {
|
||||
return (d.deviceType && (d.deviceType.startsWith('A4ZXE') || d.deviceType.startsWith('ASQZWP')));
|
||||
});
|
||||
console.log('[INFO] Echo devices: ' + echoDevices.map(function(d) { return d.accountName; }).join(', '));
|
||||
} catch (err) {
|
||||
console.error('[WARN] Startup init failed:', err.message);
|
||||
}
|
||||
});
|
||||
119
alexa-api/test_tts.js
Normal file
119
alexa-api/test_tts.js
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* test_tts.js - TTS API テスト
|
||||
* node test_tts.js
|
||||
*/
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const envContent = fs.readFileSync(path.join(__dirname, '.env'), 'utf8');
|
||||
const COOKIE_STR = envContent.match(/ALEXA_COOKIE=(.+)/)[1].trim();
|
||||
|
||||
function makeRequest(url, options = {}, extraCookies = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const allCookies = COOKIE_STR + (extraCookies ? '; ' + extraCookies : '');
|
||||
const reqOpts = {
|
||||
hostname: parsed.hostname,
|
||||
path: parsed.pathname + parsed.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Accept': 'application/json, text/plain, */*',
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Cookie': allCookies,
|
||||
...(options.headers || {}),
|
||||
},
|
||||
};
|
||||
const req = https.request(reqOpts, (res) => {
|
||||
let body = '';
|
||||
res.on('data', d => body += d);
|
||||
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body }));
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// 1. CSRFトークン取得
|
||||
console.log('[1] CSRF token取得...');
|
||||
const langRes = await makeRequest('https://alexa.amazon.co.jp/api/language');
|
||||
const setCookies = langRes.headers['set-cookie'] || [];
|
||||
const csrfCookieStr = setCookies.find(c => c.startsWith('csrf='));
|
||||
const csrfToken = csrfCookieStr ? csrfCookieStr.split('=')[1].split(';')[0] : null;
|
||||
console.log(' CSRF token:', csrfToken);
|
||||
console.log(' Status:', langRes.status);
|
||||
|
||||
if (!csrfToken) { console.error('CSRF token not found!'); process.exit(1); }
|
||||
|
||||
// 2. デバイス一覧取得
|
||||
console.log('[2] デバイス一覧取得...');
|
||||
const devRes = await makeRequest('https://alexa.amazon.co.jp/api/devices-v2/device?cached=false');
|
||||
console.log(' Status:', devRes.status);
|
||||
const devices = JSON.parse(devRes.body).devices || [];
|
||||
console.log(' Device count:', devices.length);
|
||||
|
||||
// デバイス一覧表示
|
||||
devices.filter(d => d.deviceFamily !== 'TABLET').forEach(d => {
|
||||
console.log(` - ${d.accountName} (type=${d.deviceType}, serial=${d.serialNumber})`);
|
||||
});
|
||||
|
||||
// プレハブを探す
|
||||
const target = devices.find(d => d.serialNumber === 'G0922H085165007R');
|
||||
console.log('\nTarget device:', target ? `${target.accountName}` : 'NOT FOUND');
|
||||
|
||||
if (!target) { process.exit(1); }
|
||||
|
||||
// 2.5. カスタマーIDを取得
|
||||
const bootstrapRes = await makeRequest('https://alexa.amazon.co.jp/api/bootstrap');
|
||||
const bootstrap = JSON.parse(bootstrapRes.body);
|
||||
const customerId = bootstrap.authentication?.customerId;
|
||||
console.log(' Customer ID:', customerId);
|
||||
|
||||
// 3. TTSリクエスト
|
||||
const sequenceObj = {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.Sequence',
|
||||
startNode: {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode',
|
||||
type: 'Alexa.Speak',
|
||||
operationPayload: {
|
||||
deviceType: target.deviceType,
|
||||
deviceSerialNumber: target.serialNumber,
|
||||
customerId: customerId,
|
||||
locale: 'ja-JP',
|
||||
textToSpeak: 'テストです。聞こえますか',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const bodyObj = {
|
||||
behaviorId: 'PREVIEW',
|
||||
sequenceJson: JSON.stringify(sequenceObj),
|
||||
status: 'ENABLED',
|
||||
};
|
||||
const body = JSON.stringify(bodyObj);
|
||||
|
||||
console.log('\n[3] TTS送信...');
|
||||
|
||||
const ttsRes = await makeRequest('https://alexa.amazon.co.jp/api/behaviors/preview', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'csrf': csrfToken,
|
||||
'Referer': 'https://alexa.amazon.co.jp/spa/index.html',
|
||||
'Origin': 'https://alexa.amazon.co.jp',
|
||||
},
|
||||
body,
|
||||
}, `csrf=${csrfToken}`);
|
||||
|
||||
console.log('TTS status:', ttsRes.status);
|
||||
console.log('TTS response:', ttsRes.body.substring(0, 500));
|
||||
|
||||
if (ttsRes.status === 200 || ttsRes.status === 202) {
|
||||
console.log('\n成功!エコーがしゃべるはずです。');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
30
scripts/alexa_speak.ts
Normal file
30
scripts/alexa_speak.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* alexa_speak.ts
|
||||
* 指定した Echo デバイスにテキストを読み上げさせる Windmill スクリプト
|
||||
*
|
||||
* パラメータ:
|
||||
* device - デバイス名またはシリアル番号(例: "リビングエコー1", "プレハブ")
|
||||
* text - 読み上げるテキスト
|
||||
*/
|
||||
|
||||
export async function main(
|
||||
device: string,
|
||||
text: string,
|
||||
): Promise<{ ok: boolean; device: string; text: string }> {
|
||||
const ALEXA_API_URL = "http://alexa_api:3500";
|
||||
|
||||
const res = await fetch(`${ALEXA_API_URL}/speak`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ device, text }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
`alexa-api error ${res.status}: ${JSON.stringify(body)}`
|
||||
);
|
||||
}
|
||||
|
||||
return await res.json();
|
||||
}
|
||||
Reference in New Issue
Block a user