If your app follows creators, like a clip tool, a search index over a channel or an archive, you need each new upload as a file soon after it's posted, without anyone pasting links. Finding the new videos is the easy part. Every YouTube channel has a public Atom feed, and it needs no API key:
https://www.youtube.com/feeds/videos.xml?channel_id=UC_x5XG1OV2P6uZZ5FSM9Ttw
It lists the channel's 15 most recent uploads, newest first, each with its video id. If the script runs more often than the channel posts 15 videos, it never misses one.
The download is the hard part. It works on a laptop, then the same code goes to a server and the requests get blocked, because sites block datacenter IPs. I built Importly for that, so that's what this script calls: you send it one video link and get the file in your own bucket, with the captions. It works from servers. Whatever you call for the download, the job has the same shape, and that's what most of this post is about.
What the script does
- It sends each video once. The video id is the primary key in SQLite, so a re-run skips anything already started, finished or failed.
- No run waits on a long download. Each run first saves the imports that finished since the last run, then reads the feed, then starts up to 5 new videos.
- Each video has a cost cap (
maxCostDollars), so a 6-hour stream can't use up the budget. - Live streams are in the feed while they're live. They fail, and the script sends them again an hour later, up to 3 tries.
- Shorts are in the same feed with
/shorts/links. The script skips them unless you setSKIP_SHORTS=0.
The code
import Database from 'better-sqlite3'
import { XMLParser } from 'fast-xml-parser'
const API = 'https://api.importly.io'
const CHANNEL_ID = process.argv[2] // the UC... id from the channel page's URL or page source
const FEED_URL = `https://www.youtube.com/feeds/videos.xml?channel_id=${CHANNEL_ID}`
const MAX_COST = Number(process.env.MAX_COST_PER_VIDEO ?? '1.00') // about an hour of 720p
const SKIP_SHORTS = (process.env.SKIP_SHORTS ?? '1') === '1'
const MAX_NEW_PER_RUN = 5
const RETRY_LATER = { LIVE_NOT_SUPPORTED: 3600, SOURCE_THROTTLED: 300 } // code -> seconds to wait
const MAX_ATTEMPTS = 3
const headers = {
Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
'Content-Type': 'application/json',
}
const now = () => Date.now() / 1000
const db = new Database('channel.db')
db.exec(`
create table if not exists videos (
video_id text primary key,
title text,
url text,
status text, -- waiting, queued, running, completed, failed
job_id text,
attempts integer default 0,
not_before real default 0,
bucket_key text,
media_url text,
transcript text,
cost real,
error text
)
`)
// Add each video in the feed that isn't in the table yet
async function addNewVideos() {
const res = await fetch(FEED_URL)
if (!res.ok) throw new Error(`Feed returned ${res.status}`)
const parser = new XMLParser({ ignoreAttributes: false, isArray: (name) => name === 'entry' })
const feed = parser.parse(await res.text()).feed
const insert = db.prepare(
`insert or ignore into videos (video_id, title, url, status) values (?, ?, ?, 'waiting')`
)
for (const entry of feed.entry ?? []) {
const videoId = entry['yt:videoId']
if (!videoId) continue
if (SKIP_SHORTS && entry.link?.['@_href']?.includes('/shorts/')) continue
insert.run(videoId, String(entry.title), `https://www.youtube.com/watch?v=${videoId}`)
}
}
async function startWaiting() {
const rows = db
.prepare(`select video_id, url from videos where status = 'waiting' and not_before <= ? limit ?`)
.all(now(), MAX_NEW_PER_RUN)
for (const { video_id: videoId, url } of rows) {
const res = await fetch(`${API}/import`, {
method: 'POST',
headers,
body: JSON.stringify({
url,
videoQuality: '720p', // a ceiling: lower if the source has no 720p
maxCostDollars: MAX_COST, // the most one video may cost, captions included
includeTranscript: true, // the video's captions, $0.003
store: true, // copy the file to your bucket
storagePath: `youtube/${CHANNEL_ID}`,
storageFilename: videoId,
}),
})
const body = await res.json()
if (res.status === 402 || res.status === 429) {
// Out of credits, or the hourly or in-progress limit: try the rest next run
console.log(`Stopping for this run: ${body.code} ${body.error}`)
return
}
if (!res.ok || !body.success) {
db.prepare(`update videos set status = 'failed', error = ? where video_id = ?`)
.run(body.error ?? null, videoId)
} else {
db.prepare(`update videos set status = 'queued', job_id = ? where video_id = ?`)
.run(body.data.jobId, videoId)
console.log(`Started: ${videoId}`)
}
}
}
async function collectFinished() {
const pending = db
.prepare(`select video_id, job_id, attempts from videos where status in ('queued', 'running')`)
.all()
for (const { video_id: videoId, job_id: jobId, attempts } of pending) {
const res = await fetch(`${API}/import/status?id=${jobId}`, { headers })
const { data } = await res.json()
if (data.status === 'completed') {
const { result } = data
db.prepare(
`update videos set status = 'completed', bucket_key = ?, media_url = ?,
transcript = ?, cost = ?, error = ? where video_id = ?`
).run(
result.s3Storage?.key ?? null,
result.mediaUrl, // expires after 7 days
result.transcript?.text ?? null, // null when the video has no captions
result.totalCostInDollars,
result.s3StorageError ?? null, // set if the copy to your bucket failed
videoId
)
} else if (data.status === 'failed') {
const wait = RETRY_LATER[data.code]
if (wait && attempts + 1 < MAX_ATTEMPTS) {
// Still live, or the source asked us to slow down: send it again later
db.prepare(
`update videos set status = 'waiting', attempts = ?, not_before = ? where video_id = ?`
).run(attempts + 1, now() + wait, videoId)
} else {
db.prepare(`update videos set status = 'failed', error = ? where video_id = ?`)
.run(`${data.code}: ${data.message}`, videoId)
}
} else {
db.prepare(`update videos set status = ? where video_id = ?`).run(data.status, videoId)
}
}
}
await collectFinished()
await addNewVideos()
await startWaiting()
npm install better-sqlite3 fast-xml-parser
export IMPORTLY_API_KEY=your_api_key
# Run it every 15 minutes with the channel's id (Node 18 or later)
node import-channel.mjs UC_x5XG1OV2P6uZZ5FSM9Ttw
Run it from cron every 15 minutes (*/15 * * * *), or from the scheduler your app already uses. It needs Node 18 or later for the built-in fetch and top-level await.
Things to know before you run it
The first run starts the 5 newest videos, and the rest of the feed follows over the next two runs. If you only want videos posted from today on, insert the current feed's ids as completed before the first run.
A 402 (out of credit) or 429 (rate limit) on the start request doesn't mean the video failed. The script stops starting videos for that run, and the next run picks them up.
The download link in the result expires after 7 days. If you need the file later, keep the copy in your bucket (that's what store: true is for) rather than the link.
better-sqlite3 writes channel.db to local disk. On a host with no persistent disk, like serverless functions or most container platforms, the file is gone on the next deploy, so keep the same table in your app's database instead.
The full recipe, with the response you get back and the errors to handle, is in the Importly docs. It's free to try, no card required.
Top comments (0)