Exemples complets
Un script qui valide un dossier sans zip et sort en erreur si un fichier n’est pas prêt : une étape de workflow telle quelle, avant la mise en ligne. Il relit les verdicts au lieu d’attendre un webhook, pour tenir en un fichier. Il s’arrête sur un zip : décompressez un zip de fichiers, mais déposez une bannière HTML5 dans ValidFile, qui la juge, plutôt que de la décompresser.
En Node
Node 20 ou plus, sans dépendance : node validate.mjs ./hiver "Votre client" "Hiver 2027" Meta,Display.
// node validate.mjs <folder> <client> <campaign> <platforms, comma-separated>
import { openAsBlob } from 'node:fs';
import { readdir, stat } from 'node:fs/promises';
import { join, relative, sep } from 'node:path';
const API = 'https://validfile.ca/api/v1';
const KEY = process.env.VALIDFILE_KEY;
const [folder, client, campaign, platforms] = process.argv.slice(2);
const sleep = (s) => new Promise((done) => setTimeout(done, s * 1000));
async function call(method, path, body) {
for (;;) {
const res = await fetch(API + path, {
method,
headers: { Authorization: `Bearer ${KEY}`, ...(body && { 'Content-Type': 'application/json' }) },
body: body && JSON.stringify(body),
});
if (res.status === 429) {
await sleep(Number(res.headers.get('Retry-After') ?? 10));
continue;
}
const data = res.status === 204 ? null : await res.json();
if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${data?.error}`);
return data;
}
}
// System files are skipped, and folders joined with "_", as ValidFile's page does:
// the name helps choose the placement.
const JUNK = /^\.|^__MACOSX$|^_?Thumbs\.db$|^desktop\.ini$/i;
// A link is refused, before anything is made: one script went into it and the other did not.
async function* filesIn(root, at = root) {
for (const entry of await readdir(at, { withFileTypes: true })) {
if (JUNK.test(entry.name)) continue;
const path = join(at, entry.name);
if (entry.isSymbolicLink()) throw new Error(`${relative(root, path)}: a link; copy what it points to into the folder`);
if (entry.isDirectory()) yield* filesIn(root, path);
else yield { path, name: relative(root, path).split(sep).join('_') };
}
}
const TYPES = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', mp4: 'video/mp4', mov: 'video/quicktime', mp3: 'audio/mpeg', wav: 'audio/wav' };
const files = [];
for await (const f of filesIn(folder)) files.push(f);
// In the order of the names sent, as the Python script does.
files.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
const zip = files.find((f) => /\.zip$/i.test(f.name));
if (zip) throw new Error(`${zip.name}: the API takes no zip; unzip a zip of files, and drop an HTML5 banner in ValidFile`);
const { delivery } = await call('POST', '/deliveries', { client, campaign, platforms: platforms.split(',') });
for (const f of files) {
const { size } = await stat(f.path);
if (size === 0) continue;
const type = TYPES[f.name.split('.').pop().toLowerCase()] ?? 'application/octet-stream';
const { file, uploadUrl } = await call('POST', `/deliveries/${delivery.id}/files`, { name: f.name, size, type });
try {
const put = await fetch(uploadUrl, { method: 'PUT', headers: { 'Content-Type': type }, body: await openAsBlob(f.path) });
if (!put.ok) throw new Error(`${f.name}: upload refused (${put.status})`);
await call('POST', `/deliveries/${delivery.id}/files/${file.id}/complete`);
} catch (err) {
// Given up at once, rather than its credit waiting a day.
await call('DELETE', `/deliveries/${delivery.id}/files/${file.id}`).catch(() => {});
throw err;
}
}
await call('POST', `/deliveries/${delivery.id}/close`);
let review;
for (;;) {
review = await call('GET', `/deliveries/${delivery.id}`);
if (!review.files.some((f) => f.verdict === 'pending' || f.antivirus?.state === 'scanning')) break;
await sleep(10);
}
for (const f of review.files) console.log((f.ready ? 'ready' : f.heldReason).padEnd(16), f.name);
console.log('Review:', review.reviewUrl);
process.exitCode = review.files.every((f) => f.ready) ? 0 : 1;
En Python
Le même script, les mêmes appels dans le même ordre, en Python 3.9 ou plus avec requests (pip install requests) : python validate.py ./hiver "Votre client" "Hiver 2027" Meta,Display.
# python validate.py <folder> <client> <campaign> <platforms, comma-separated>
import os
import re
import sys
import time
import requests
API = "https://validfile.ca/api/v1"
folder, client, campaign, platforms = sys.argv[1:5]
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['VALIDFILE_KEY']}"
def call(method, path, body=None):
while True:
res = session.request(method, API + path, json=body)
if res.status_code == 429:
time.sleep(int(res.headers.get("Retry-After", "10")))
continue
data = None if res.status_code == 204 else res.json()
if not res.ok:
raise RuntimeError(f"{method} {path}: {res.status_code} {data and data.get('error')}")
return data
# System files are skipped, and folders joined with "_", as ValidFile's page does:
# the name helps choose the placement.
JUNK = re.compile(r"^\.|^__MACOSX$|^_?Thumbs\.db$|^desktop\.ini$", re.I)
# A link is refused, before anything is made: one script went into it and the other did not.
def files_in(root):
for at, dirs, names in os.walk(root):
dirs[:] = [d for d in dirs if not JUNK.search(d)]
for name in dirs + names:
if not JUNK.search(name) and os.path.islink(os.path.join(at, name)):
sys.exit(f"{os.path.relpath(os.path.join(at, name), root)}: a link; copy what it points to into the folder")
for name in names:
if not JUNK.search(name):
path = os.path.join(at, name)
yield path, "_".join(os.path.relpath(path, root).split(os.sep))
TYPES = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "gif": "image/gif", "webp": "image/webp",
"mp4": "video/mp4", "mov": "video/quicktime", "mp3": "audio/mpeg", "wav": "audio/wav"}
# In the order of the names sent, as the Node script does.
files = sorted(files_in(folder), key=lambda f: f[1])
for path, name in files:
if name.lower().endswith(".zip"):
sys.exit(f"{name}: the API takes no zip; unzip a zip of files, and drop an HTML5 banner in ValidFile")
delivery = call("POST", "/deliveries", {"client": client, "campaign": campaign, "platforms": platforms.split(",")})["delivery"]
for path, name in files:
size = os.path.getsize(path)
if size == 0:
continue
kind = TYPES.get(name.rsplit(".", 1)[-1].lower(), "application/octet-stream")
announced = call("POST", f"/deliveries/{delivery['id']}/files", {"name": name, "size": size, "type": kind})
file_id = announced["file"]["id"]
try:
with open(path, "rb") as body:
requests.put(announced["uploadUrl"], data=body, headers={"Content-Type": kind}).raise_for_status()
call("POST", f"/deliveries/{delivery['id']}/files/{file_id}/complete")
except Exception:
# Given up at once, rather than its credit waiting a day.
try:
call("DELETE", f"/deliveries/{delivery['id']}/files/{file_id}")
except Exception:
pass
raise
call("POST", f"/deliveries/{delivery['id']}/close")
while True:
review = call("GET", f"/deliveries/{delivery['id']}")
if not any(f["verdict"] == "pending" or (f["antivirus"] or {}).get("state") == "scanning" for f in review["files"]):
break
time.sleep(10)
for f in review["files"]:
print(("ready" if f["ready"] else f["heldReason"]).ljust(16), f["name"])
print("Review:", review["reviewUrl"])
sys.exit(0 if all(f["ready"] for f in review["files"]) else 1)
Ce qu’il dit
Une ligne par fichier, ready ou la raison qui le retient, puis le lien vers la revue :
ready Display_FR_300x250-hiver.jpg
ready Meta_FR_story-hiver.mp4
refused Meta_FR_story-hiver-v2.mp4
Review: https://validfile.ca/livraisons/0b6c2f4e-8d1a-4c7b-9f3e-5a2d1c8b7e60/revue
Il sort avec 1 dès qu’un fichier n’est pas ready, quelle que soit la raison : un fichier refusé, mais aussi un emplacement à confirmer ou un fichier hors campagne, que quelqu’un doit regarder dans ValidFile.