Files
momentry_core/docs/API_WORDPRESS_GUIDE.md

7.5 KiB
Raw Blame History

WordPress 呼叫 Momentry API 指南

項目 內容
版本 V1.1
日期 2026-03-25
用途 在 WordPress 中呼叫 Momentry API

版本歷史

版本 日期 目的 操作人 工具/模型
V1.1 2026-03-25 更新: n8n 搜尋回傳 file_path 取代 media_url,新增 API Key 驗證說明 OpenCode deepseek-reasoner
V1.0 2026-03-23 創建 WordPress API 指南 Warren OpenCode / MiniMax M2.5

API URL

在 WordPress 中呼叫 API請使用外部 URL

https://api.momentry.ddns.net

⚠️ WordPress 運行於瀏覽器端,無法直接訪問 localhost


API 認證

所有 /api/v1/* 端點(除了健康檢查)都需要 API Key 認證。請在請求標頭中加入:

'headers' => ['Content-Type' => 'application/json', 'X-API-Key' => 'YOUR_API_KEY']

目前示範使用的 API Key: demo_api_key_12345

注意: 正式環境請使用安全的 API Key 管理機制,避免在客戶端 JavaScript 中暴露 API Key。


常用端點

方法 端點 說明
GET /health 健康檢查
POST /api/v1/search 語意搜尋(標準格式)
GET /api/v1/videos 列出所有影片
GET /api/v1/lookup 查詢影片

PHP 範例

基本搜尋

<?php
$api_url = 'https://api.momentry.ddns.net/api/v1/n8n/search';

$data = [
    'query' => 'charade',
    'limit' => 10
];

$response = wp_remote_post($api_url, [
    'headers' => ['Content-Type' => 'application/json', 'X-API-Key' => 'YOUR_API_KEY'],
    'body'    => json_encode($data),
    'timeout' => 30
]);

if (is_wp_error($response)) {
    echo '錯誤: ' . $response->get_error_message();
} else {
    $body = json_decode(wp_remote_retrieve_body($response), true);
    print_r($body['hits']);
}
?>

列出所有影片

<?php
$api_url = 'https://api.momentry.ddns.net/api/v1/videos';

$response = wp_remote_get($api_url, [
    'headers' => ['X-API-Key' => 'YOUR_API_KEY'],
    'timeout' => 30
]);

if (!is_wp_error($response)) {
    $body = json_decode(wp_remote_retrieve_body($response), true);
    foreach ($body['videos'] as $video) {
        echo $video['file_name'] . "\n";
    }
}
?>

查詢特定影片

<?php
$uuid = '5dea6618a606e7c7';
$api_url = 'https://api.momentry.ddns.net/api/v1/lookup?uuid=' . $uuid;

$response = wp_remote_get($api_url, [
    'headers' => ['X-API-Key' => 'YOUR_API_KEY'],
    'timeout' => 30
]);

if (!is_wp_error($response)) {
    $video = json_decode(wp_remote_retrieve_body($response), true);
    echo '檔案: ' . $video['file_name'] . "\n";
    echo '時長: ' . $video['duration'] . ' 秒';
}
?>

JavaScript 範例

使用 fetch

// 搜尋影片
async function searchVideos(query, limit = 10) {
    const response = await fetch('https://api.momentry.ddns.net/api/v1/n8n/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-API-Key': 'YOUR_API_KEY' },
        body: JSON.stringify({ query, limit })
    });
    
    if (!response.ok) {
        throw new Error('API 請求失敗');
    }
    
    return await response.json();
}

// 使用範例
searchVideos('charade', 5)
    .then(data => {
        data.hits.forEach(hit => {
            console.log(`${hit.text} (score: ${hit.score})`);
        });
    });

WordPress Shortcode 範例

functions.php 中註冊短碼:

<?php
// 將文件路徑轉換為可訪問的 URL
function convert_file_path_to_url($file_path) {
    // 範例: 將 SFTPGo 文件路徑轉換為 web URL
    // /Users/accusys/momentry/var/sftpgo/data/demo/video.mp4
    // → https://sftpgo.example.com/demo/video.mp4
    
    // 移除基本路徑
    $base_path = '/Users/accusys/momentry/var/sftpgo/data/';
    if (strpos($file_path, $base_path) === 0) {
        $relative_path = substr($file_path, strlen($base_path));
        // 替換為實際的 SFTPGo web URL
        return 'https://sftpgo.example.com/' . $relative_path;
    }
    
    // 如果無法轉換,返回原始路徑
    return $file_path;
}

// 註冊短碼
add_shortcode('momentry_search', function($atts) {
    $atts = shortcode_atts([
        'query' => '',
        'limit' => '10'
    ], $atts);
    
    if (empty($atts['query'])) {
        return '<p>請提供搜尋關鍵字</p>';
    }
    
    $response = wp_remote_post('https://api.momentry.ddns.net/api/v1/n8n/search', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-API-Key' => 'YOUR_API_KEY'  // 替換為實際的 API Key
        ],
        'body'    => json_encode([
            'query' => $atts['query'],
            'limit' => (int)$atts['limit']
        ]),
        'timeout' => 30
    ]);
    
    if (is_wp_error($response)) {
        return '<p>搜尋服務暫時無法使用</p>';
    }
    
    $data = json_decode(wp_remote_retrieve_body($response), true);
    
    if (empty($data['hits'])) {
        return '<p>找不到相關結果</p>';
    }
    
    $output = '<ul class="momentry-results">';
    foreach ($data['hits'] as $hit) {
        // 注意: API 現在返回 file_path 而非 media_url
        // 需要將文件路徑轉換為可訪問的 URL
        $file_path = $hit['file_path'];
        $video_url = convert_file_path_to_url($file_path); // 需要實作此函數
        
        $output .= sprintf(
            '<li>%s <a href="%s?start=%s">播放</a></li>',
            esc_html($hit['text']),
            $video_url,
            $hit['start']
        );
    }
    $output .= '</ul>';
    
    return $output;
});
?>

使用方式:

[momentry_search query="charade" limit="5"]

REST API Endpoint (WP >= 5.0)

在 WordPress REST API 中註冊自定義端點:

<?php
// 註冊 REST API 端點
add_action('rest_api_init', function() {
    register_rest_route('momentry/v1', '/search', [
        'methods'  => 'POST',
        'callback' => function($request) {
            $response = wp_remote_post(
                'https://api.momentry.ddns.net/api/v1/n8n/search',
                [
                    'headers' => ['Content-Type' => 'application/json', 'X-API-Key' => 'YOUR_API_KEY'],
                    'body'    => json_encode([
                        'query' => $request->get_param('query'),
                        'limit' => $request->get_param('limit', 10)
                    ])
                ]
            );
            
            if (is_wp_error($response)) {
                return new WP_Error('api_error', 'API 請求失敗');
            }
            
            return json_decode(wp_remote_retrieve_body($response));
        }
    ]);
});
?>

呼叫方式:

POST /wp-json/momentry/v1/search
Body: {"query": "charade", "limit": 5}

常見錯誤

錯誤: cURL error 7

原因: 無法連接到 API

檢查:

  1. API 服務是否啟動
  2. 網路是否可達

錯誤: 502 Bad Gateway

原因: API 服務未啟動

解決:

sudo launchctl load /Library/LaunchDaemons/com.momentry.api.plist

curl 測試

在終端機中測試:

# 健康檢查
curl https://api.momentry.ddns.net/health

# 搜尋測試
curl -X POST https://api.momentry.ddns.net/api/v1/n8n/search \
  -H "Content-Type: application/json" \
  -d '{"query":"charade","limit":5}'

相關文件