{"id":"gI3QGKTf52zwyh6O","meta":{"instanceId":"workflow-159f09cb","versionId":"1.0.0","createdAt":"2025-09-29T07:07:43.803393","updatedAt":"2025-09-29T07:07:43.803408","owner":"n8n-user","license":"MIT","category":"automation","status":"active","priority":"high","environment":"production"},"name":"AutoClip – Automatically Generate Video Clips and Upload to YouTube","nodes":[{"id":"99e8f5d2-247a-44c7-85db-4bdd63c2a4f6","name":"Start AutoClip Workflow","type":"n8n-nodes-base.manualTrigger","position":[40,0],"parameters":{},"typeVersion":1,"notes":"This manualTrigger node performs automated tasks as part of the workflow."},{"id":"221b0fa1-7e71-43e1-88a6-7070c6c10ed8","name":"Retrieve Video Background Data","type":"n8n-nodes-base.googleSheets","position":[500,180],"parameters":{"columns":{"value":{"BackgroundURL":"{{ $env.BASE_URL }}"},"schema":[{"id":"BackgroundURL","type":"string","display":true,"required":false,"displayName":"BackgroundURL","defaultMatch":false,"canBeUsedToMatch":true},{"id":"BackgroudStatus","type":"string","display":true,"required":false,"displayName":"BackgroudStatus","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":90817124,"cachedResultUrl":"{{ $env.WEBHOOK_URL }}","cachedResultName":"video_backgroud_list"},"documentId":{"__rl":true,"mode":"id","value":"184-zcrfWSzQpDa-t57Oo_8DLyAF-2B_6yvGrybrcd5I"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Ra2f1dlqOJ13jTtb","name":"Google Sheets account"}},"typeVersion":4.5,"notes":"This googleSheets node performs automated tasks as part of the workflow."},{"id":"120db4aa-5a1a-4685-9d1d-6d7814b20458","name":"Retrieve Quote Data","type":"n8n-nodes-base.googleSheets","position":[500,0],"parameters":{"options":{},"filtersUI":{"values":[{"lookupColumn":"CreateStatus"}]},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"{{ $env.WEBHOOK_URL }}","cachedResultName":"Quotes_status"},"documentId":{"__rl":true,"mode":"id","value":"184-zcrfWSzQpDa-t57Oo_8DLyAF-2B_6yvGrybrcd5I"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Ra2f1dlqOJ13jTtb","name":"Google Sheets account"}},"typeVersion":4.5,"notes":"This googleSheets node performs automated tasks as part of the workflow."},{"id":"17e6585a-0e48-40e7-86ec-4fb53f45bd07","name":"List Video Background Files","type":"n8n-nodes-base.googleDrive","position":[260,180],"parameters":{"filter":{"folderId":{"__rl":true,"mode":"id","value":"1mLOqFJZvUm563mJ7LvTsIcKrAoakX-h2"}},"options":{"fields":["webViewLink","id","name"]},"resource":"fileFolder"},"credentials":{"googleDriveOAuth2Api":{"id":"nd1GyFEAYkpaT3xt","name":"Google Drive account"}},"typeVersion":3,"notes":"This googleDrive node performs automated tasks as part of the workflow."},{"id":"34d51d42-2562-4437-8cbc-e0158badb134","name":"Configure Music Background Folder ID","type":"n8n-nodes-base.set","position":[40,360],"parameters":{"options":{},"assignments":{"assignments":[{"id":"19727718-f70d-4333-93dd-1ade2b1a66bf","name":"MusicBackgroundFolderID","type":"string","value":"12T6ABEuR7WlZ2i88GqcB3U4DmuKVM4iR"}]}},"typeVersion":3.4,"notes":"This set node performs automated tasks as part of the workflow."},{"id":"0d819b1f-923d-4500-858a-166d65864872","name":"List Music Background Files","type":"n8n-nodes-base.googleDrive","position":[260,360],"parameters":{"filter":{"folderId":{"__rl":true,"mode":"id","value":"=12T6ABEuR7WlZ2i88GqcB3U4DmuKVM4iR"}},"options":{"fields":["webViewLink","name","id"]},"resource":"fileFolder"},"credentials":{"googleDriveOAuth2Api":{"id":"OEWvSsY5xiUhqOnx","name":"Google Drive account - PeakWave"}},"typeVersion":3,"notes":"This googleDrive node performs automated tasks as part of the workflow."},{"id":"3041385c-52d9-4d95-a454-de2064164717","name":"Retrieve Music Background Data","type":"n8n-nodes-base.googleSheets","position":[500,360],"parameters":{"columns":{"value":{"MusicURL":"{{ $env.BASE_URL }}"},"schema":[{"id":"MusicURL","type":"string","display":true,"required":false,"displayName":"MusicURL","defaultMatch":false,"canBeUsedToMatch":true},{"id":"MusicStatus","type":"string","display":true,"required":false,"displayName":"MusicStatus","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":1264732774,"cachedResultUrl":"{{ $env.WEBHOOK_URL }}","cachedResultName":"music_backgroud_list"},"documentId":{"__rl":true,"mode":"id","value":"184-zcrfWSzQpDa-t57Oo_8DLyAF-2B_6yvGrybrcd5I"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Ra2f1dlqOJ13jTtb","name":"Google Sheets account"}},"typeVersion":4.5,"notes":"This googleSheets node performs automated tasks as part of the workflow."},{"id":"ab86cac3-e44e-4e87-a467-a1c26e1f9752","name":"Merge File Selection Data","type":"n8n-nodes-base.merge","position":[740,200],"parameters":{"numberInputs":3},"typeVersion":3,"notes":"This merge node performs automated tasks as part of the workflow."},{"id":"28c79ad7-cb34-424a-97ed-fcec5471e179","name":"Select Random Video, Music & Quote","type":"n8n-nodes-base.code","position":[940,200],"parameters":{"jsCode":"function getRandomItem(arr) {\n  return arr[Math.floor(Math.random() * arr.length)];\n}\n\n// Filter items based on unique keys from the merged inputs\nconst videoItems = items.filter(item => item.json.BackgroundURL !== undefined);\nconst musicItems = items.filter(item => item.json.MusicURL !== undefined);\nconst quoteItems = items.filter(item => item.json.Qoute !== undefined);\n\n// Debug logs to check counts in the execution log\nconsole.log(\"Video Items count: \" + videoItems.length);\nconsole.log(\"Music Items count: \" + musicItems.length);\nconsole.log(\"Quote Items count: \" + quoteItems.length);\n\nif (videoItems.length === 0 || musicItems.length === 0 || quoteItems.length === 0) {\n  throw new Error(\"One or more input arrays are empty. Check your previous nodes.\");\n}\n\nconst selectedVideo = getRandomItem(videoItems);\nconst selectedMusic = getRandomItem(musicItems);\nconst selectedQuote = getRandomItem(quoteItems);\n\n// Return the combined selected items\nreturn [{\n  video: selectedVideo.json,\n  music: selectedMusic.json,\n  quote: selectedQuote.json\n}];\n"},"typeVersion":2,"notes":"This code node performs automated tasks as part of the workflow."},{"id":"bd3fa420-555d-46a2-b48c-15a916f62b44","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-20,-120],"parameters":{"width":1100,"height":660,"content":"## Data Preparation & File Selection\nRetrieve and merge source data for quotes, video backgrounds, and music from Google Sheets and Google Drive; then randomly select one quote, one background video, and one music file."},"typeVersion":1,"notes":"This stickyNote node performs automated tasks as part of the workflow."},{"id":"7da639cb-6576-4ab5-891a-308ce35aecaf","name":"Download Selected Video Background","type":"n8n-nodes-base.googleDrive","position":[1180,0],"parameters":{"fileId":{"__rl":true,"mode":"url","value":"={{ $json.video.BackgroundURL }}"},"options":{"binaryPropertyName":"data"},"operation":"download"},"credentials":{"googleDriveOAuth2Api":{"id":"OEWvSsY5xiUhqOnx","name":"Google Drive account - PeakWave"}},"typeVersion":3,"notes":"This googleDrive node performs automated tasks as part of the workflow."},{"id":"5ee8befc-979d-4a47-8eba-b31d6de8ea1f","name":"Download Selected Music Background","type":"n8n-nodes-base.googleDrive","position":[1180,340],"parameters":{"fileId":{"__rl":true,"mode":"url","value":"={{ $json.music.MusicURL }}"},"options":{"binaryPropertyName":"data"},"operation":"download"},"credentials":{"googleDriveOAuth2Api":{"id":"OEWvSsY5xiUhqOnx","name":"Google Drive account - PeakWave"}},"typeVersion":3,"notes":"This googleDrive node performs automated tasks as part of the workflow."},{"id":"fd8fd1f8-64a6-4bf0-8586-8f5be506c8a1","name":"Save Video Background Locally","type":"n8n-nodes-base.readWriteFile","position":[1420,0],"parameters":{"options":{},"fileName":"video1.mp4","operation":"write"},"typeVersion":1,"notes":"This readWriteFile node performs automated tasks as part of the workflow."},{"id":"9a8e1891-16c2-490c-ae91-4773f90e67d3","name":"Save Music Background Locally","type":"n8n-nodes-base.readWriteFile","position":[1420,340],"parameters":{"options":{"append":false},"fileName":"music1.mp3","operation":"write"},"typeVersion":1,"notes":"This readWriteFile node performs automated tasks as part of the workflow."},{"id":"9fdca64e-79d7-4a58-91dc-4aa9f9b3c4cc","name":"Prepare Overlay Text (Quote & Author)","type":"n8n-nodes-base.code","position":[1620,20],"parameters":{"jsCode":"// Define separate configuration for the quote and the author\nconst quoteFont = \"Kanit-Italic.ttf\";      // Font for the quote\nconst quoteFontSize = 70;\nconst authorFont = \"Kanit-Italic.ttf\";         // Font for the author (ensure this supports Thai)\nconst authorFontSize = 50;\nconst fontColor = \"white\";\nconst lineHeightMultiplier = 1.1;\nconst videoWidth = 1080;\nconst margin = 40;  // Gap from left and right edges\n\n// Effective width for the quote text (accounting for left/right margins)\nconst effectiveVideoWidth = videoWidth - 2 * margin;\n\n// Estimate average character width based on quoteFontSize (this is a rough estimate)\nconst avgCharWidth = quoteFontSize * 0.6;\nconst maxCharsPerLine = Math.floor(effectiveVideoWidth / avgCharWidth);\n\n// Retrieve the quote transcript and author from the \"Merge\" node\nconst transcript = $node[\"Merge File Selection Data\"].json[\"Qoute\"];\nif (!transcript) {\n  throw new Error(\"Quote not found\");\n}\nconst author = $node[\"Merge File Selection Data\"].json[\"Author\"];\nif (!author) {\n  throw new Error(\"Author not found\");\n}\n\n// Split the transcript into words and group them into lines based on maxCharsPerLine\nconst words = transcript.split(' ');\nconst lines = [];\nlet currentLine = \"\";\nlet currentCharCount = 0;\n\nwords.forEach(word => {\n  const wordLength = word.length;\n  const additionalSpace = currentLine ? 1 : 0;\n  const potentialLength = currentCharCount + additionalSpace + wordLength;\n  if (potentialLength <= maxCharsPerLine) {\n    currentLine += (currentLine ? \" \" : \"\") + word;\n    currentCharCount = potentialLength;\n  } else {\n    lines.push(currentLine);\n    currentLine = word;\n    currentCharCount = wordLength;\n  }\n});\nif (currentLine) {\n  lines.push(currentLine);\n}\n\n// Calculate layout for the quote block\nconst lineHeight = quoteFontSize * lineHeightMultiplier;\nconst totalHeight = lines.length * lineHeight;\n\n// Build drawtext commands for each quote line (centered horizontally)\n// Each line is positioned so that the entire quote block is vertically centered.\nconst quoteCommands = lines.map((line, index) => {\n  // Escape any single quotes in the line\n  const escapedLine = line.replace(/'/g, \"\\\\'\");\n  return `drawtext=fontfile=${quoteFont}:text='${escapedLine}':fontsize=${quoteFontSize}:fontcolor=${fontColor}:x=(w-text_w)/2:y=((h-${totalHeight})/2)+(${index}*${lineHeight})`;\n});\n\n// Build the drawtext command for the author\n// Place the author text below the quote block with a small gap (e.g. 20 pixels)\n// Align it to the right by setting x = w - text_w - margin.\nconst authorY = `((h-${totalHeight})/2)+(${lines.length}*${lineHeight})+20`;\nconst escapedAuthor = author.replace(/'/g, \"\\\\'\");\nconst authorCommand = `drawtext=fontfile=${authorFont}:text='${escapedAuthor}':fontsize=${authorFontSize}:fontcolor=${fontColor}:x=w-text_w-${margin}:y=${authorY}`;\n\n// Combine all commands (separated by commas) into one drawtext filter string.\nconst fullDrawTextFilter = quoteCommands.concat(authorCommand).join(\", \");\n\n// Return the prepared filter string for insertion into your FFmpeg command.\nreturn {\n  json: {\n    drawText: fullDrawTextFilter\n  }\n};\n"},"typeVersion":2,"notes":"This code node performs automated tasks as part of the workflow."},{"id":"082cf794-89a9-42cc-b9ee-96792a17893f","name":"Generate Final Video Clip","type":"n8n-nodes-base.executeCommand","position":[1640,340],"parameters":{"command":"=ffmpeg -i {{ $('Save Video Background Locally').item.json.fileName }} -i {{ $('Save Music Background Locally').item.json.fileName }} -filter_complex \"[0:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920[vid]; color=black@0.3:size=1080x1920:d=10[bg]; [vid][bg]overlay=shortest=1[bgvid]; [bgvid]{{ $json.drawText }}[outv]; [1:a]volume=0.8[aout]\" -map \"[outv]\" -map \"[aout]\" -aspect 9:16 -c:v libx264 -c:a aac -shortest output.mp4 -y"},"typeVersion":1,"notes":"This executeCommand node performs automated tasks as part of the workflow."},{"id":"460d3ddc-b24b-4714-8e00-023294da8375","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[1100,-120],"parameters":{"color":3,"width":700,"height":660,"content":"## File Download & Video Processing\nDownload the selected files, write them to disk, prepare overlay text (quote and author), and generate the final video clip using FFmpeg."},"typeVersion":1,"notes":"This stickyNote node performs automated tasks as part of the workflow."},{"id":"b148528f-7d45-4a59-9b29-52c7229f05e8","name":"Initiate YouTube Resumable Upload","type":"n8n-nodes-base.httpRequest","position":[1860,20],"parameters":{"url":"{{ $env.BASE_URL }}","body":"={\n  \"snippet\": {\n    \"title\": \"{{ $('Save Music Background Locally').item.json.quote.Qoute }}\",\n    \"description\": \"{{ $('Save Music Background Locally').item.json.quote.Qoute }}\\n{{ $('Save Music Background Locally').item.json.quote.Author }}\",\n    \"defaultLanguage\": \"en\",\n    \"defaultAudioLanguage\": \"en\"\n  },\n  \"status\": {\n    \"privacyStatus\": \"public\",\n    \"license\": \"youtube\",\n    \"embeddable\": true,\n    \"publicStatsViewable\": true,\n    \"madeForKids\": false\n  }\n}","method":"POST","options":{"response":{"response":{"fullResponse":true}}},"sendBody":true,"contentType":"raw","sendHeaders":true,"authentication":"{{ $credentials.predefinedCredentialType }}","rawContentType":"RAW/JSON","headerParameters":{"parameters":[{"name":"Content-Type","value":"application/json"},{"name":"X-Upload-Content-Type","value":"video/webm"}]},"nodeCredentialType":"YOUR_CREDENTIAL_HERE"},"credentials":{"youTubeOAuth2Api":{"id":"f9uNp5YNQMnXrNw2","name":"YouTube account"}},"typeVersion":4.2,"notes":"This httpRequest node performs automated tasks as part of the workflow."},{"id":"e8a97b56-be01-497b-bc91-ec84bc59d039","name":"Read output file","type":"n8n-nodes-base.readWriteFile","position":[2060,20],"parameters":{"options":{},"fileSelector":"=output.mp4"},"typeVersion":1,"notes":"This readWriteFile node performs automated tasks as part of the workflow."},{"id":"7965943e-e5c9-4c97-afca-18b3fc5881cd","name":"Upload Video to YouTube","type":"n8n-nodes-base.httpRequest","position":[2260,20],"parameters":{"url":"{{ $env.BASE_URL }}","method":"PUT","options":{},"sendBody":true,"contentType":"binaryData","sendHeaders":true,"authentication":"{{ $credentials.predefinedCredentialType }}","headerParameters":{"parameters":[{"name":"Content-Type","value":"video/webm"}]},"inputDataFieldName":"data","nodeCredentialType":"YOUR_CREDENTIAL_HERE"},"credentials":{"youTubeOAuth2Api":{"id":"f9uNp5YNQMnXrNw2","name":"YouTube account"}},"typeVersion":4.2,"notes":"This httpRequest node performs automated tasks as part of the workflow."},{"id":"040f9064-9d7f-4106-9f1c-55222d6bf4d4","name":"Update Quote Upload Status","type":"n8n-nodes-base.googleSheets","position":[1860,340],"parameters":{"columns":{"value":{"Index":"={{ $('Save Music Background Locally').item.json.quote.Index }}","YoutubeURL":"{{ $env.BASE_URL }}","CreateStatus":"DONE"},"schema":[{"id":"Index","type":"string","display":true,"removed":false,"required":false,"displayName":"Index","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Qoute","type":"string","display":true,"required":false,"displayName":"Qoute","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Author","type":"string","display":true,"required":false,"displayName":"Author","defaultMatch":false,"canBeUsedToMatch":true},{"id":"CreateStatus","type":"string","display":true,"required":false,"displayName":"CreateStatus","defaultMatch":false,"canBeUsedToMatch":true},{"id":"YoutubeURL","type":"string","display":true,"required":false,"displayName":"YoutubeURL","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["Index"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"appendOrUpdate","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"{{ $env.WEBHOOK_URL }}","cachedResultName":"Quotes_status"},"documentId":{"__rl":true,"mode":"id","value":"184-zcrfWSzQpDa-t57Oo_8DLyAF-2B_6yvGrybrcd5I"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Ra2f1dlqOJ13jTtb","name":"Google Sheets account"}},"typeVersion":4.5,"notes":"This googleSheets node performs automated tasks as part of the workflow."},{"id":"526ffabc-3f12-4619-abe3-01d729f96db6","name":"Mark Background as Used","type":"n8n-nodes-base.googleSheets","position":[2240,340],"parameters":{"columns":{"value":{"BackgroundURL":"{{ $('Read/Write Files from Disk1').item.json.video.BackgroundURL }}","BackgroudStatus":"DONE"},"schema":[{"id":"BackgroundURL","type":"string","display":true,"removed":false,"required":false,"displayName":"BackgroundURL","defaultMatch":false,"canBeUsedToMatch":true},{"id":"BackgroudStatus","type":"string","display":true,"required":false,"displayName":"BackgroudStatus","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["BackgroundURL"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"appendOrUpdate","sheetName":{"__rl":true,"mode":"list","value":90817124,"cachedResultUrl":"{{ $env.WEBHOOK_URL }}","cachedResultName":"video_backgroud_list"},"documentId":{"__rl":true,"mode":"url","value":"{{ $env.WEBHOOK_URL }}"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Ra2f1dlqOJ13jTtb","name":"Google Sheets account"}},"typeVersion":4.5,"notes":"This googleSheets node performs automated tasks as part of the workflow."},{"id":"5c833f0d-5c4b-489a-a53b-234b38433a2a","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[1820,-120],"parameters":{"width":620,"height":660,"content":"## Video Upload & Post-Processing\nUpload the final video to YouTube using the YouTube API and update your Google Sheets with upload statuses and YouTube links."},"typeVersion":1,"notes":"This stickyNote node performs automated tasks as part of the workflow."}],"active":false,"settings":{"executionOrder":"v1","saveManualExecutions":true,"callerPolicy":"workflowsFromSameOwner","errorWorkflow":null,"timezone":"UTC","executionTimeout":3600,"maxExecutions":1000,"retryOnFail":true,"retryCount":3,"retryDelay":1000},"versionId":"49ffd0ae-2689-483f-9821-b99b9083ac8b","connections":{"Initiate YouTube Resumable Upload":{"main":[[],[],[],[],[],[],[],[],[]]},"Upload Video to YouTube":{"main":[[],[],[],[],[],[],[],[],[]]},"Retrieve Video Background Data":{"main":[[]]},"Retrieve Quote Data":{"main":[[]]},"List Video Background Files":{"main":[[]]},"List Music Background Files":{"main":[[]]},"Retrieve Music Background Data":{"main":[[]]},"Download Selected Video Background":{"main":[[]]},"Download Selected Music Background":{"main":[[]]},"Save Video Background Locally":{"main":[[]]},"Save Music Background Locally":{"main":[[]]},"Read output file":{"main":[[]]},"Update Quote Upload Status":{"main":[[]]},"Mark Background as Used":{"main":[[]]}},"description":"Automated workflow: AutoClip – Automatically Generate Video Clips and Upload to YouTube. This workflow integrates 11 different services: stickyNote, httpRequest, code, readWriteFile, merge. It contains 39 nodes and follows best practices for error handling and security.","notes":"Excellent quality workflow: AutoClip – Automatically Generate Video Clips and Upload to YouTube. This workflow has been optimized for production use with comprehensive error handling, security, and documentation."}