#!/usr/bin/env python3
"""Build a website content inventory before a migration, with the Ujeebu Crawl API.
Crawls the site as HTML without JavaScript (the cheapest format), then writes:
inventory.csv the content inventory: one row per URL with status, title, canonical, depth,
links in and out, plus empty action and notes columns for the audit
broken-links.csv URLs that answer 404 or 410, with the pages that link to them
redirects.csv a first redirect map: each page and its URL on the new site
pip install requests
UJEEBU_API_KEY=your-key python3 site_inventory.py
"""
import collections
import csv
import os
import time
from urllib.parse import urlparse
import requests
API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY")
API = "https://api.ujeebu.com"
CRAWL = {
"urls": ["https://ujeebu.com/"],
"scope": {"max_depth": 2, "max_pages": 100},
"format": "html",
"page": {"js": False}, # plain HTML: the cheapest page
"max_credits": 150,
"concurrency": 3,
}
NEW_SITE = "https://new.example.com" # where the site is moving
MOVES = [ # old path prefix -> new path prefix, first match wins
("/blog/", "/resources/blog/"),
("/docs/", "/developers/docs/"),
]
http = requests.Session()
http.headers["ApiKey"] = API_KEY
def api(method, path, **kwargs):
"""Call the Crawl API. A GET is tried again after a network error: polling runs for minutes."""
for attempt in range(1, 4):
try:
response = http.request(method, API + path, timeout=60, **kwargs)
break
except requests.ConnectionError:
if method != "GET" or attempt == 3:
raise
time.sleep(5 * attempt)
if response.status_code >= 400:
raise SystemExit(f"{method} {path}: {response.status_code} {response.text}")
return response.json()
def wait(job_id):
while True:
job = api("GET", f"/crawl/{job_id}")
if job["finished"]:
return job
print(f" {job['status']}: {job['counts']['done']} done, {job['counts']['pending']} pending")
time.sleep(10)
def page_records(job_id):
after = 0
while True:
batch = api("GET", f"/crawl/{job_id}/pages", params={"after": after, "limit": 50})
yield from batch["pages"]
if not batch["has_more"]:
return
after = batch["next_after"]
def new_url(url):
"""The page's URL on the new site: same path, unless a MOVES rule applies."""
path = urlparse(url).path or "/"
for old, new in MOVES:
old, new = old.rstrip("/"), new.rstrip("/")
if path == old or path.startswith(old + "/"):
return NEW_SITE + new + path[len(old):]
return NEW_SITE + path
def keeper(page):
"""The URL that stays for this page's document: the canonical URL, else the page itself."""
if page.get("duplicate_of") in by_url:
page = by_url[page["duplicate_of"]]
return page.get("canonical_url") or page["url"]
job = api("POST", "/crawl", json=CRAWL)
print(f"Started {job['job_id']}")
job = wait(job["job_id"])
pages = list(page_records(job["job_id"]))
by_url = {p["url"]: p for p in pages}
# Who links to whom: links are absolute URLs, one list per page (up to 300, links_total says how many).
linked_from = collections.defaultdict(set)
for page in pages:
for link in page.get("links") or []:
linked_from[link.split("#")[0]].add(page["url"])
with open("inventory.csv", "w", newline="") as f:
out = csv.writer(f)
out.writerow(["url", "state", "http_status", "error_class", "title", "canonical_url", "duplicate_of",
"depth", "links_out", "links_in", "action", "notes"])
for p in pages:
out.writerow([p["url"], p["state"], p.get("http_status", ""), p.get("error_class") or "",
p.get("title", ""), p.get("canonical_url", ""), p.get("duplicate_of", ""),
p["depth"], p.get("links_total", 0), len(linked_from[p["url"]]), "", ""])
broken = [p for p in pages if p.get("error_class") == "not_found"]
with open("broken-links.csv", "w", newline="") as f:
out = csv.writer(f)
out.writerow(["broken_url", "http_status", "linked_from"])
for p in broken:
out.writerow([p["url"], p.get("http_status", ""), " ".join(sorted(linked_from[p["url"]]))])
with open("redirects.csv", "w", newline="") as f:
out = csv.writer(f)
out.writerow(["old_url", "new_url", "note"])
for p in pages:
if p["state"] == "done" or p.get("error_class") == "duplicate":
keep = keeper(p)
out.writerow([p["url"], new_url(keep), f"same document as {keep}" if keep != p["url"] else ""])
states = collections.Counter(p.get("error_class") or p["state"] for p in pages)
print(f"{len(pages)} URLs: {dict(states)}; {job['credits_used']} credits ({job['stop_reason']})")
print(f"{len(broken)} broken URLs")
for p in broken[:10]:
print(f" {p['url']} ({p.get('http_status')}), linked from {len(linked_from[p['url']])} pages")
#!/usr/bin/env node
/**
* Build a website content inventory before a migration, with the Ujeebu Crawl API.
*
* Crawls the site as HTML without JavaScript (the cheapest format), then writes:
* inventory.csv the content inventory: one row per URL with status, title, canonical, depth,
* links in and out, plus empty action and notes columns for the audit
* broken-links.csv URLs that answer 404 or 410, with the pages that link to them
* redirects.csv a first redirect map: each page and its URL on the new site
*
* UJEEBU_API_KEY=your-key node site-inventory.js (Node.js 18 or later, no dependencies)
*/
const fs = require('fs');
const API_KEY = process.env.UJEEBU_API_KEY || 'YOUR_API_KEY';
const API = 'https://api.ujeebu.com';
const CRAWL = {
urls: ['https://ujeebu.com/'],
scope: { max_depth: 2, max_pages: 100 },
format: 'html',
page: { js: false }, // plain HTML: the cheapest page
max_credits: 150,
concurrency: 3,
};
const NEW_SITE = 'https://new.example.com'; // where the site is moving
const MOVES = [ // old path prefix -> new path prefix, first match wins
['/blog/', '/resources/blog/'],
['/docs/', '/developers/docs/'],
];
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Call the Crawl API. A GET is tried again after a network error: polling runs for minutes. */
async function api(method, path, body) {
for (let attempt = 1; ; attempt += 1) {
let response;
try {
response = await fetch(API + path, {
method,
headers: { ApiKey: API_KEY, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (err) {
if (method !== 'GET' || attempt === 3) throw err;
await sleep(5000 * attempt);
continue;
}
if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${await response.text()}`);
return response.json();
}
}
async function wait(jobId) {
for (;;) {
const job = await api('GET', `/crawl/${jobId}`);
if (job.finished) return job;
console.log(` ${job.status}: ${job.counts.done} done, ${job.counts.pending} pending`);
await sleep(10000);
}
}
async function pageRecords(jobId) {
const pages = [];
let after = 0;
for (;;) {
const batch = await api('GET', `/crawl/${jobId}/pages?after=${after}&limit=50`);
pages.push(...batch.pages);
if (!batch.has_more) return pages;
after = batch.next_after;
}
}
/** The page's URL on the new site: same path, unless a MOVES rule applies. */
function newUrl(url) {
const path = new URL(url).pathname || '/';
for (const [from, to] of MOVES) {
const old = from.replace(/\/$/, '');
if (path === old || path.startsWith(old + '/')) return NEW_SITE + to.replace(/\/$/, '') + path.slice(old.length);
}
return NEW_SITE + path;
}
const csvCell = (v) => (/[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v));
const writeCsv = (file, rows) => fs.writeFileSync(file, rows.map((r) => r.map(csvCell).join(',')).join('\n') + '\n');
async function main() {
let job = await api('POST', '/crawl', CRAWL);
console.log(`Started ${job.job_id}`);
job = await wait(job.job_id);
const pages = await pageRecords(job.job_id);
const byUrl = new Map(pages.map((p) => [p.url, p]));
// Who links to whom: links are absolute URLs, one list per page (up to 300, links_total says how many).
const linkedFrom = new Map();
for (const page of pages) {
for (const link of page.links || []) {
const target = link.split('#')[0];
if (!linkedFrom.has(target)) linkedFrom.set(target, new Set());
linkedFrom.get(target).add(page.url);
}
}
const inlinks = (url) => [...(linkedFrom.get(url) || [])];
/** The URL that stays for this page's document: the canonical URL, else the page itself. */
const keeper = (page) => {
const doc = byUrl.get(page.duplicate_of) || page;
return doc.canonical_url || doc.url;
};
writeCsv('inventory.csv', [
['url', 'state', 'http_status', 'error_class', 'title', 'canonical_url', 'duplicate_of',
'depth', 'links_out', 'links_in', 'action', 'notes'],
...pages.map((p) => [p.url, p.state, p.http_status ?? '', p.error_class || '', p.title || '',
p.canonical_url || '', p.duplicate_of || '', p.depth, p.links_total || 0, inlinks(p.url).length, '', '']),
]);
const broken = pages.filter((p) => p.error_class === 'not_found');
writeCsv('broken-links.csv', [
['broken_url', 'http_status', 'linked_from'],
...broken.map((p) => [p.url, p.http_status ?? '', inlinks(p.url).sort().join(' ')]),
]);
writeCsv('redirects.csv', [
['old_url', 'new_url', 'note'],
...pages.filter((p) => p.state === 'done' || p.error_class === 'duplicate').map((p) => {
const keep = keeper(p);
return [p.url, newUrl(keep), keep !== p.url ? `same document as ${keep}` : ''];
}),
]);
const states = {};
for (const p of pages) states[p.error_class || p.state] = (states[p.error_class || p.state] || 0) + 1;
console.log(`${pages.length} URLs: ${JSON.stringify(states)}; ${job.credits_used} credits (${job.stop_reason})`);
console.log(`${broken.length} broken URLs`);
for (const p of broken.slice(0, 10)) {
console.log(` ${p.url} (${p.http_status}), linked from ${inlinks(p.url).length} pages`);
}
}
main().catch((err) => { console.error(err.message); process.exit(1); });