Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/google

Google helpers for Gmail, Calendar, Drive, People, YouTube (including upload), and Analytics.

FollowFork

Files

copy-drive-to-dropbox.mjs

221 lines · 11.2 KB · JavaScript
#!/usr/bin/env node
import { fileURLToPath } from 'node:url'
import { checkpointWriter, lockCheckpoint } from './lib/checkpoint.mjs'
import { runCopyStep } from './lib/copy-step.mjs'
// Copy Google Drive files (one file or a whole folder) into Dropbox through Kody
// execute, using @kentcdodds/google/drive downloadFile (Range requests) and
// @kentcdodds/dropbox/upload-session. Every execute run stays under a time
// budget and returns a resume cursor, so it works within local (bounded 4 MiB blocks,
// one step per run) and cloud (~3 min) limits. Each file is verified against Dropbox's
// content_hash, computed from the bytes as they stream through.
//
// Usage:
//   node copy-drive-to-dropbox.mjs --folder <driveFolderId> <dropbox folder> [options]
//   node copy-drive-to-dropbox.mjs --file <driveFileId> <dropbox folder> [options]
//
// Options:
//   --account <alias>      Google account alias (default: personal)
//   --recursive            With --folder, include subfolders (keeps relative paths)
//   --mode add|overwrite   Commit mode (default: add)
//   --no-skip-existing     Re-copy even when the Dropbox file already has the same verified content hash
//   --budget-s <n>         Seconds of work per execute run, 10 to 150 (default: 50)
//   --where local|chain|cloud  Where each execute runs: this machine (default),
//                          your Kody context chain, or Kody cloud
//   --dry-run              List what would be copied, copy nothing
//   --use-checkout         Resolve packages from local checkouts in cwd (dev only)
//
// Needs Node 22+ and a signed-in Kody CLI. Override the CLI command with
// KODY_CLI (requires >=3.33.1; default pinned 3.33.1). Progress goes to stderr;
// stdout is one JSON summary. Exit 0 only when every file copied and verified.

import { spawn, spawnSync } from 'node:child_process'
import { randomBytes, createHash } from 'node:crypto'
import { readFile, mkdtemp, rm, unlink, writeFile } from 'node:fs/promises'
import { tmpdir, homedir } from 'node:os'
import { resolve, join } from 'node:path'

const MAX_FAILED_ATTEMPTS = 6

function log(message) {
	process.stderr.write(`[copy-drive-to-dropbox] ${message}\n`)
}
function fail(message, extra = {}) {
	process.stdout.write(`${JSON.stringify({ ok: false, error: message, ...extra })}\n`)
	process.exit(1)
}

function parseArgs(argv) {
	const o = { account: 'personal', recursive: false, mode: 'add', skipExisting: true, budgetS: 50, where: 'local', dryRun: false }
	const positional = []
	for (let i = 0; i < argv.length; i += 1) {
		const a = argv[i]
		if (a === '--folder') o.folder = argv[++i]
		else if (a === '--file') o.file = argv[++i]
		else if (a === '--account') o.account = argv[++i]
		else if (a === '--recursive') o.recursive = true
		else if (a === '--mode') o.mode = argv[++i]
		else if (a === '--no-skip-existing') o.skipExisting = false
		else if (a === '--budget-s') o.budgetS = Number(argv[++i])
		else if (a === '--where') o.where = argv[++i]
		else if (a === '--dry-run') o.dryRun = true
		else if (a === '--use-checkout') o.useCheckout = true
		else if (a === '-h' || a === '--help') o.help = true
		else if (a.startsWith('--')) fail(`Unknown option ${a}`)
		else positional.push(a)
	}
	return { o, positional }
}

const LIST_MODULE = `
import { listFolderFiles, getFileMetadata } from 'kody:@kentcdodds/google/drive'
import { dropboxRpc, DropboxApiError } from 'kody:@kentcdodds/dropbox/request'
export default async function main(p) {
	let files
	if (p.fileId) {
		const m = await getFileMetadata({ account: p.account, fileId: p.fileId, fields: 'id,name,mimeType,size,md5Checksum,modifiedTime,version' })
		files = [{ id: m.id, md5Checksum:m.md5Checksum, modifiedTime:m.modifiedTime, version:m.version, name: m.name, mimeType: m.mimeType, size: m.size === undefined ? null : Number(m.size), path: m.name }]
	} else {
		files = (await listFolderFiles({ account: p.account, folderId: p.folderId, recursive: p.recursive })).files
	}
	const out = []
	for (const f of files) {
		const dest = p.dest.replace(/\\/+$/, '') + '/' + f.path
		let existingSize = null
		try {
			const meta = await dropboxRpc('files/get_metadata', { path: dest })
			const body = meta && meta.body ? meta.body : meta
			existingSize = typeof body.size === 'number' ? body.size : null
		} catch (error) {
			if (!(error instanceof DropboxApiError && error.status === 409)) throw error
		}
		out.push({ ...f, dest, existingSize })
	}
	return { files: out }
}
`

// One budgeted step for one file. Works in whole 4 MiB blocks so the Dropbox
// content_hash block digests can be carried in the cursor between runs.
export const STEP_MODULE = `
import { downloadFile, getFileMetadata } from 'kody:@kentcdodds/google/drive'
import { startUploadSession, appendUploadSession, finishUploadSession, getUploadSessionOffset } from 'kody:@kentcdodds/dropbox/upload-session'
import { dropboxRpc } from 'kody:@kentcdodds/dropbox/request'
const runCopyStep = ${runCopyStep.toString()}
export default async function main(p) { return runCopyStep(p, {downloadFile,getFileMetadata,startUploadSession,appendUploadSession,finishUploadSession,getUploadSessionOffset,dropboxRpc}) }
`

function runExecute({ cliCommand, cwd, file, params, where }) {
	const [command, ...base] = cliCommand
	const placement = where === 'local' ? ['--local'] : where === 'cloud' ? ['--chain', 'cloud'] : []
	const args = [...base, 'execute', ...placement, '--json', '--file', file, '--params', JSON.stringify(params)]
	return new Promise((resolve) => {
		const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] })
		let stdout = ''
		let stderr = ''
		child.stdout.on('data', (c) => (stdout += c))
		child.stderr.on('data', (c) => (stderr += c))
		child.on('close', (code) => resolve({ code, stdout, stderr }))
		child.on('error', (e) => resolve({ code: -1, stdout, stderr: String(e) }))
	})
}

function parseResult(stdout) {
	const at = stdout.indexOf('{')
	if (at < 0) return null
	try {
		const parsed = JSON.parse(stdout.slice(at))
		if (parsed?.isError) return null
		return parsed?.structuredContent?.result ?? null
	} catch {
		return null
	}
}

async function main() {
	const { o, positional } = parseArgs(process.argv.slice(2))
	if (o.help || positional.length !== 1 || (!o.folder === !o.file)) {
		process.stderr.write('Usage: node copy-drive-to-dropbox.mjs (--folder <id> | --file <id>) <dropbox folder> [--account personal] [--recursive] [--mode add|overwrite] [--no-skip-existing] [--budget-s 50] [--where local|chain|cloud] [--dry-run]\n')
		process.exit(o.help ? 0 : 1)
	}
	const dest = positional[0]
	if (!dest.startsWith('/')) fail('Dropbox folder must start with "/" (Kody writes usually live under /Apps/Kody/).')
	if (o.mode !== 'add' && o.mode !== 'overwrite') fail('--mode must be add or overwrite.')
	if (!['local', 'chain', 'cloud'].includes(o.where)) fail('--where must be local, chain, or cloud.')
	if (!(o.budgetS >= 10 && o.budgetS <= 150)) fail('--budget-s must be between 10 and 150.')
	const cliCommand = (process.env.KODY_CLI ?? 'npx -y @kodycodes/cli@3.33.1').split(/\s+/).filter(Boolean)
	const vr=spawnSync(cliCommand[0],[...cliCommand.slice(1),'--version'],{encoding:'utf8'});const vm=/([0-9]+)\.([0-9]+)\.([0-9]+)/.exec(vr.stdout??'');if(vr.status!==0||!vm||(+vm[1]<3||(+vm[1]===3&&(+vm[2]<33||(+vm[2]===33&&+vm[3]<1))))) throw new Error('CLI >=3.33.1 required')
	const work = await mkdtemp(join(tmpdir(), 'kody-drive-dropbox-'))
	const cwd = o.useCheckout ? process.cwd() : work
	const exec = async (source, params) => {
		const file = join(cwd, `.copy-drive-to-dropbox-${Date.now()}-${randomBytes(4).toString('hex')}.mjs`)
		await writeFile(file, source)
		try {
			return await runExecute({ cliCommand, cwd, file, params, where: o.where })
		} finally {
			await unlink(file).catch(() => {})
		}
	}
	const started = Date.now()
	try {
		log('listing Drive files and checking Dropbox')
		const listed = await exec(LIST_MODULE, { account: o.account, folderId: o.folder, fileId: o.file, recursive: o.recursive, dest })
		const list = parseResult(listed.stdout)
		if (listed.code !== 0 || !list?.files) fail(`listing failed: ${`${listed.stderr}\n${listed.stdout}`.trim().slice(-600)}`)
		const results = []
		for (const f of list.files) {
			if (f.mimeType?.startsWith('application/vnd.google-apps.')) {
				results.push({ path: f.path, status: 'skipped', reason: 'Google-native file; export it instead' })
				continue
			}

			if (o.dryRun) {
				results.push({ path: f.path, status: 'would-copy', size: f.size, dest: f.dest })
				continue
			}
			log(`copying ${f.path} (${((f.size ?? 0) / 1048576).toFixed(1)} MiB)`)
			const stateKey = createHash('sha256').update(JSON.stringify([o.account,f.id,f.md5Checksum,f.modifiedTime,f.size,f.dest,o.mode])).digest('hex')
			const statePath = join(homedir(), '.cache', 'kody-drive-dropbox',stateKey+'.json')
			const releaseLock = await lockCheckpoint(statePath)
			let cursor = { account:o.account,fileId:f.id,dest:f.dest,mode:o.mode,skipExisting:o.skipExisting,expectedMd5:f.md5Checksum,offset:0,blocks:[] }
			try {cursor=JSON.parse(await readFile(statePath,'utf8'))} catch(e) {if(e.code!=='ENOENT') throw new Error('Checkpoint unreadable; refusing restart')}
			const save=checkpointWriter(statePath)
			let failed = 0
			let outcome = null
			let lastError = ''
			while (!outcome && failed < MAX_FAILED_ATTEMPTS) {
				const input=cursor
				cursor={...cursor,phase:cursor.phase==='ready_finish'?'finishing':cursor.phase==='ready_start'?'starting':cursor.phase}
				await save(cursor)
				const r = await exec(STEP_MODULE, input)
				const res = r.code === 0 ? parseResult(r.stdout) : null
				if (res?.done) {outcome = res;await save({...res,phase:'done'})}
				else if (res && typeof res.offset === 'number') {
					failed = 0
					cursor = res
					await save(cursor)
					log('checkpoint saved; '+(res.phase??'working'))
				} else {
					failed += 1
					lastError = `${r.stderr}\n${r.stdout}`.trim().split('\n').filter(Boolean).slice(-3).join(' | ').slice(0, 500)
					log(`  attempt failed (${failed}): ${lastError}`)
					if (/RECONCILIATION_REQUIRED|SOURCE_IDENTITY_REQUIRED|already exists|conflict|insufficient_space|no_write_permission|not authenticated|not signed in/i.test(lastError)) break
					await new Promise((s) => setTimeout(s, 2000 * failed))
				}
			}
			releaseLock()
			if (!outcome) {
				results.push({ path: f.path, status: 'failed', error: lastError || 'no progress' })
				continue
			}
			const verified = outcome.metadata.content_hash === outcome.contentHash && (f.size === null || outcome.metadata.size === f.size)
			results.push({ path: f.path, status: verified ? (outcome.skipped?'skipped':'copied') : 'mismatch', dest: outcome.metadata.path_display, size: outcome.metadata.size })
		}
		const bad = results.filter((r) => r.status === 'failed' || r.status === 'mismatch')
		process.stdout.write(`${JSON.stringify({ ok: bad.length === 0, dryRun: o.dryRun, total: results.length, copied: results.filter((r) => r.status === 'copied').length, skipped: results.filter((r) => r.status === 'skipped').length, failed: bad.length, durationMs: Date.now() - started, results })}\n`)
		process.exitCode = bad.length ? 2 : 0
	} finally {
		await rm(work, { recursive: true, force: true })
	}
}

if(process.argv[1] && resolve(process.argv[1])===fileURLToPath(import.meta.url)) main().catch(()=>fail('Copy stopped; checkpoint preserved. No automatic restart after uncertain completion.'))