{
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "trendingphotos",
        "responseMode": "responseNode",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -368,
        160
      ],
      "id": "a485121e-8345-4ef9-97fd-eb2c43e12ac9",
      "name": "Webhook1",
      "webhookId": "0ee8e406-5890-4ec0-afe8-d29aec6d4a0d"
    },
    {
      "parameters": {
        "operation": "binaryToPropery",
        "binaryPropertyName": "image1",
        "destinationKey": "image1",
        "options": {}
      },
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        0,
        -80
      ],
      "id": "189ff969-4b14-4f7d-b01b-245e4e63fdee",
      "name": "Extract from File2"
    },
    {
      "parameters": {
        "operation": "binaryToPropery",
        "binaryPropertyName": "image2",
        "destinationKey": "image2",
        "options": {}
      },
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        0,
        112
      ],
      "id": "df0317e3-6af2-494d-9e7c-303c9147dced",
      "name": "Extract from File3"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        304,
        128
      ],
      "id": "c5e0d697-b2bc-4d2f-9cbf-1cb02487d3f0",
      "name": "Merge1"
    },
    {
      "parameters": {
        "jsCode": "const items = $input.all();\n\nconst toBase64 = (val) => {\n  if (!val) return '';\n  if (typeof val === 'string') return val;\n  if (Buffer.isBuffer(val)) return val.toString('base64');\n  if (val.type === 'Buffer' && Array.isArray(val.data)) {\n    return Buffer.from(val.data).toString('base64');\n  }\n  return '';\n};\n\nconsole.log('=== DEBUG: Number of items after Merge:', items.length);\n\nconst getImage = (item, jsonKey, binaryKey) => {\n  // Try binary first\n  if (item?.binary?.[binaryKey]?.data) {\n    const mime = item.binary[binaryKey].mimeType ?? 'image/png';\n    const b64 = toBase64(item.binary[binaryKey].data);\n    if (b64.length > 0) {\n      return `data:${mime};base64,${b64}`;\n    }\n  }\n\n  // Fallback to json\n  const val = item?.json?.[jsonKey];\n  if (val) {\n    const b64 = toBase64(val);\n    if (b64.length > 0) {\n      const mime = 'image/png';\n      return `data:${mime};base64,${b64}`;\n    }\n  }\n\n  return null;\n};\n\nconst img1 = getImage(items[0], 'image1', 'image1');\nlet img2 = getImage(items[1], 'image2', 'image2');\n\nif (!img2) {\n  img2 = getImage(items[0], 'image2', 'image2');\n}\n\nconsole.log('img1 resolved:', img1 ? `YES (${img1.length} chars)` : 'NO');\nconsole.log('img2 resolved:', img2 ? `YES (${img2.length} chars)` : 'NO');\n\nif (!img1) throw new Error('Could not resolve image1 — check logs above');\nif (!img2) throw new Error('Could not resolve image2 — check logs above');\n\nconsole.log('img1 starts with:', img1.substring(0, 80));\nconsole.log('img2 starts with:', img2.substring(0, 80));\n\nconst firstJson = items[0]?.json || {};\nconst secondJson = items[1]?.json || {};\nconst body = firstJson.body || secondJson.body || {};\n\nconst imagePrompt =\n  body.prompt ||\n  firstJson.prompt ||\n  secondJson.prompt ||\n  \"Create a realistic World Cup 2026 supporter portrait. Use reference image 1 as the exact main subject. Preserve the person's face, identity, skin tone, hairstyle, age, expression, body shape, head angle, and natural proportions exactly. Do not change the person's facial features. Use reference image 2 as the national team reference. Detect the team or country from the jersey, flag, colors, badge style, or visible symbols. Dress the person from image 1 in a realistic football supporter jersey inspired by that team, matching the correct color palette, flag atmosphere, and supporter identity. If a third reference image is provided, use it only as the stadium, crowd, lighting, or celebration atmosphere reference. Otherwise, place the subject in a cinematic World Cup 2026 stadium environment. Create bright stadium lights, a packed cheering crowd, waving national flags, confetti, celebration banners, and strong emotional football energy. Include a realistic golden World Cup-style trophy or cup as a visible celebration element, either held naturally by the subject or placed beside them in the foreground, without covering the face. Make the final image feel like a premium sports fan poster with strong national pride. The result should be realistic, vibrant, sharp, and polished, with detailed jersey fabric, natural lighting, accurate flag colors, and a powerful World Cup celebration atmosphere. Negative instructions: do not create a different person, do not change the face, do not use wrong national colors, do not distort hands, do not add extra limbs, do not create fake text, do not use cartoon style, and do not let the trophy cover the face.\";\n\nconst videoPrompt =\n  body.video_prompt ||\n  firstJson.video_prompt ||\n  secondJson.video_prompt ||\n  \"Create a cinematic 5-second World Cup 2026 supporter video from this generated portrait. Keep the same person, face identity, jersey, national team colors, trophy, stadium background, lighting, and composition consistent with the source image. Do not change the person's face, age, hairstyle, outfit, team colors, or trophy placement. Add subtle realistic motion: slow camera push-in or pull-back, gentle stadium light movement, waving flags in the background, falling confetti, slight jersey fabric movement, natural hair movement, and crowd celebration energy. Make the person look proud and heroic, like a premium football fan poster coming to life. Keep the motion smooth, cinematic, realistic, and stable. Add ambient stadium sound, soft crowd cheering, light wind, and celebration atmosphere. Avoid face morphing, identity changes, distorted hands, unstable trophy movement, flickering jersey colors, fake text, warped flags, excessive camera shake, or cartoon-like motion.\";\n\nreturn [{\n  json: {\n    image_urls: [img1, img2],\n    prompt: imagePrompt,\n    video_prompt: videoPrompt,\n    video_duration: Number(body.video_duration || firstJson.video_duration || secondJson.video_duration || 5),\n    video_ratio: body.video_ratio || firstJson.video_ratio || secondJson.video_ratio || 'adaptive',\n    generate_audio: body.generate_audio === undefined ? true : Boolean(body.generate_audio)\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        528,
        128
      ],
      "id": "9e309f2d-063e-4f21-83dd-0a62586772f1",
      "name": "Build Payload1"
    },
    {
      "parameters": {
        "jsCode": "const r = $json;\n\nconst imageUrl =\n  r?.data?.[0]?.url ||\n  r?.data?.[0]?.image_url ||\n  r?.data?.[0]?.image?.url ||\n  r?.result?.data?.[0]?.url ||\n  r?.result?.url ||\n  r?.url ||\n  r?.image_url;\n\nif (!imageUrl) {\n  throw new Error(\n    'Cannot find generated image URL from image generation response: ' +\n    JSON.stringify(r).slice(0, 2000)\n  );\n}\n\nconst payload = $('Build Payload1').first().json;\n\nreturn [\n  {\n    json: {\n      generated_image_url: imageUrl,\n      video_prompt: payload.video_prompt,\n      video_duration: payload.video_duration || 5,\n      video_ratio: payload.video_ratio || 'adaptive',\n      generate_audio: payload.generate_audio === undefined ? true : payload.generate_audio\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -176,
        416
      ],
      "id": "00a7cfce-f1de-47d4-a9f9-db035c92b48d",
      "name": "Extract Generated Image URL"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://ark.ap-southeast.bytepluses.com/api/v3/contents/generations/tasks",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer apikey"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"model\": \"seedance-1-5-pro-251215\",\n  \"content\": [\n    {\n      \"type\": \"text\",\n      \"text\": \"{{ $json.video_prompt }}\"\n    },\n    {\n      \"type\": \"image_url\",\n      \"image_url\": {\n        \"url\": \"{{ $json.generated_image_url }}\"\n      }\n    }\n  ],\n  \"generate_audio\": {{ $json.generate_audio === false ? 'false' : 'true' }},\n  \"ratio\": \"{{ $json.video_ratio || 'adaptive' }}\",\n  \"duration\": {{ Number($json.video_duration || 5) }},\n  \"watermark\": false\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        0,
        416
      ],
      "id": "5d2342b6-89f1-4caf-a630-977121427137",
      "name": "Create Video Task"
    },
    {
      "parameters": {
        "jsCode": "const r = $json;\n\nconst taskId =\n  r?.id ||\n  r?.data?.id ||\n  r?.task_id ||\n  r?.data?.task_id;\n\nif (!taskId) {\n  throw new Error(\n    'Video task id not found in response: ' +\n    JSON.stringify(r).slice(0, 2000)\n  );\n}\n\nreturn [\n  {\n    json: {\n      task_id: taskId\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        192,
        416
      ],
      "id": "e8975c34-cd1b-40be-b0d7-e1b530f622d7",
      "name": "Save Video Task ID"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        416,
        416
      ],
      "id": "28ca201c-b7a3-4f1e-ac14-86d199c5f2b2",
      "name": "Wait 5 Seconds",
      "webhookId": "edcde8fb-1133-46fd-9135-638f4068db41"
    },
    {
      "parameters": {
        "url": "={{ 'https://ark.ap-southeast.bytepluses.com/api/v3/contents/generations/tasks/' + $json.task_id }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer apikey"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        624,
        416
      ],
      "id": "111904fc-dd4f-45b8-ab6d-90b152c1d886",
      "name": "Check Video Task"
    },
    {
      "parameters": {
        "jsCode": "const r = $json;\n\nconst taskId =\n  r?.id ||\n  r?.data?.id ||\n  r?.task_id ||\n  r?.data?.task_id ||\n  $('Save Video Task ID').first().json.task_id;\n\nconst status =\n  r?.status ||\n  r?.data?.status ||\n  r?.task_status ||\n  r?.data?.task_status ||\n  '';\n\nconst statusLower = String(status).toLowerCase();\n\nif (\n  statusLower.includes('failed') ||\n  statusLower.includes('error') ||\n  statusLower.includes('cancel')\n) {\n  throw new Error(\n    'Video generation failed: ' +\n    JSON.stringify(r).slice(0, 2000)\n  );\n}\n\nconst urls = new Set();\n\nfunction collectVideoUrls(value, parentKey = '') {\n  if (!value) return;\n\n  if (typeof value === 'string') {\n    const lower = value.toLowerCase();\n\n    if (\n      value.startsWith('http') &&\n      (\n        parentKey.toLowerCase().includes('video') ||\n        lower.includes('.mp4') ||\n        lower.includes('.mov') ||\n        lower.includes('/video')\n      )\n    ) {\n      urls.add(value);\n    }\n\n    return;\n  }\n\n  if (Array.isArray(value)) {\n    for (const item of value) {\n      collectVideoUrls(item, parentKey);\n    }\n    return;\n  }\n\n  if (typeof value === 'object') {\n    for (const [key, val] of Object.entries(value)) {\n      const keyLower = key.toLowerCase();\n\n      if (\n        keyLower.includes('video') &&\n        typeof val === 'string' &&\n        val.startsWith('http')\n      ) {\n        urls.add(val);\n      }\n\n      if (\n        keyLower.includes('video') &&\n        val &&\n        typeof val === 'object' &&\n        typeof val.url === 'string'\n      ) {\n        urls.add(val.url);\n      }\n\n      collectVideoUrls(val, key);\n    }\n  }\n}\n\ncollectVideoUrls(r);\n\nconst videoUrls = [...urls];\n\nreturn [\n  {\n    json: {\n      task_id: taskId,\n      status,\n      is_done: videoUrls.length > 0,\n      video_urls: videoUrls,\n      raw: r\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        800,
        432
      ],
      "id": "2c8f14cf-4759-45e5-b3c5-da566703ee43",
      "name": "Check Video Result"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "158d7220-4e4a-4f62-8e9a-c6fc79df2a4b",
              "leftValue": "={{ $json.is_done }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        992,
        432
      ],
      "id": "8ad9787a-10f0-462b-920b-57f461211e52",
      "name": "Video Ready?"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ {\n  task_id: $json.task_id,\n  status: $json.status,\n  video_urls: $json.video_urls,\n  raw: $json.raw\n} }}",
        "options": {}
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        1264,
        416
      ],
      "id": "03de1dae-898b-4e70-b939-0c1ef8a79a45",
      "name": "Respond to Webhook"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://ark.ap-southeast.bytepluses.com/api/v3/images/generations",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer apikey"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"model\": \"seedream-5-0-260128\",\n  \"prompt\": \"{{ $json.prompt }}\",\n  \"size\": \"2K\",\n  \"output_format\": \"png\",\n  \"watermark\": false,\n  \"image\": {{ JSON.stringify($json.image_urls) }}\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -352,
        416
      ],
      "id": "f7274e5e-99d7-4b76-864f-a70b6d907c53",
      "name": "HTTP Request"
    }
  ],
  "connections": {
    "Webhook1": {
      "main": [
        [
          {
            "node": "Extract from File2",
            "type": "main",
            "index": 0
          },
          {
            "node": "Extract from File3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract from File2": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract from File3": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge1": {
      "main": [
        [
          {
            "node": "Build Payload1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Payload1": {
      "main": [
        [
          {
            "node": "HTTP Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Generated Image URL": {
      "main": [
        [
          {
            "node": "Create Video Task",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Video Task": {
      "main": [
        [
          {
            "node": "Save Video Task ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Video Task ID": {
      "main": [
        [
          {
            "node": "Wait 5 Seconds",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait 5 Seconds": {
      "main": [
        [
          {
            "node": "Check Video Task",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Video Task": {
      "main": [
        [
          {
            "node": "Check Video Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Video Result": {
      "main": [
        [
          {
            "node": "Video Ready?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Video Ready?": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait 5 Seconds",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request": {
      "main": [
        [
          {
            "node": "Extract Generated Image URL",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "meta": {
    "instanceId": "9a562c06a632241f66aadd52a495ad98e76b760ef5cfce9c319a4759c47cd94e"
  }
}