This document provides practical examples and common workflows for both the SDK and CLI.
import { Alldebrid } from "alldebrid";
const client = new Alldebrid({
apiKey: process.env.ALLDEBRID_API_KEY!,
logLevel: "warn",
});async function getUserInfo() {
try {
const user = await client.user.get();
console.log(`Welcome ${user.username}!`);
console.log(`Premium until: ${user.premiumUntil.toLocaleString()}`);
console.log(`Fidelity points: ${user.fidelityPoints}`);
if (!user.isPremium) {
console.log("β οΈ Premium account required for full functionality");
}
} catch (error) {
console.error("Failed to get user info:", error);
}
}async function checkPremiumStatus() {
const user = await client.user.get();
if (user.isPremium) {
const daysRemaining = user.premiumUntil.diffNow('days').days;
console.log(`β
Premium active - ${Math.ceil(daysRemaining)} days remaining`);
} else {
console.log("β Premium expired or not active");
}
}async function manageSavedLinks() {
// Save multiple links
const linksToSave = [
"https://rapidgator.net/file/abc123",
"https://mega.nz/file/def456",
];
await client.user.saveLinks(linksToSave);
console.log(`β
Saved ${linksToSave.length} links`);
// List all saved links
const savedLinks = await client.user.listSavedLinks();
console.log(`π You have ${savedLinks.length} saved links`);
// Delete specific links
const linksToDelete = savedLinks
.filter(link => link.filename.includes("old"))
.map(link => link.link);
if (linksToDelete.length > 0) {
await client.user.deleteLinks(linksToDelete);
console.log(`ποΈ Deleted ${linksToDelete.length} old links`);
}
}async function uploadTorrent(magnetLink: string) {
console.log("π€ Uploading magnet...");
const results = await client.magnet.upload([magnetLink]);
const result = results[0];
if (result.success) {
console.log(`β
Upload successful! ID: ${result.id}`);
// Monitor progress
await monitorMagnet(result.id);
} else {
console.error(`β Upload failed: ${result.error.message}`);
}
}
async function monitorMagnet(id: number) {
console.log(`π Monitoring magnet ${id}...`);
let attempts = 0;
const maxAttempts = 30; // 5 minutes with 10s intervals
while (attempts < maxAttempts) {
const magnet = await client.magnet.get(id);
console.log(`Status: ${magnet.status} (${magnet.statusCode})`);
if (magnet.status === "Ready") {
console.log(`π Magnet ready! ${magnet.files.length} files available`);
// List download links
magnet.files.forEach((file, index) => {
console.log(`${index + 1}. ${file.name} (${formatBytes(file.size)})`);
if (file.link) {
console.log(` π₯ ${file.link}`);
}
});
break;
} else if (magnet.status === "Error") {
console.error(`β Magnet failed: ${magnet.error?.message || "Unknown error"}`);
break;
}
// Wait 10 seconds before next check
await new Promise(resolve => setTimeout(resolve, 10000));
attempts++;
}
if (attempts >= maxAttempts) {
console.log("β° Monitoring timeout - magnet still processing");
}
}
function formatBytes(bytes: number): string {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(1)} ${units[unitIndex]}`;
}async function cleanupOldMagnets() {
const magnets = await client.magnet.list();
const oneWeekAgo = DateTime.now().minus({ weeks: 1 });
const oldMagnets = magnets.filter(magnet =>
magnet.status === "Error" ||
(magnet.completionDate && magnet.completionDate < oneWeekAgo)
);
console.log(`π§Ή Found ${oldMagnets.length} old magnets to cleanup`);
for (const magnet of oldMagnets) {
try {
await client.magnet.delete(magnet.id);
console.log(`ποΈ Deleted: ${magnet.filename}`);
} catch (error) {
console.error(`β Failed to delete ${magnet.filename}:`, error);
}
}
}async function processLinks(links: string[]) {
for (const link of links) {
try {
// Get info first
console.log(`π Checking: ${link}`);
const info = await client.link.getInfo(link);
console.log(`π ${info.filename} (${formatBytes(info.filesize)})`);
// Unlock the link
const result = await client.link.debrid(link);
console.log(`β
Unlocked: ${result.link}`);
// Save to recent links automatically happens via API
} catch (error) {
console.error(`β Failed to process ${link}:`, error);
}
}
}async function unlockProtectedLink(url: string, password: string) {
try {
// Check if password is needed
const info = await client.link.getInfo(url);
console.log(`π Protected file: ${info.filename}`);
// Unlock with password
const result = await client.link.debrid(url, password);
console.log(`β
Unlocked with password: ${result.link}`);
return result.link;
} catch (error) {
console.error("β Password unlock failed:", error);
throw error;
}
}async function checkHostAvailability(domain: string) {
const hosts = await client.host.list();
const host = hosts.hosts.find(h =>
h.name.toLowerCase() === domain.toLowerCase()
);
if (host) {
console.log(`π ${host.name}: ${host.status}`);
return host.status === "up";
} else {
console.log(`β Host ${domain} not found or not supported`);
return false;
}
}# Quick status check
alldebrid user info
# Get detailed info in JSON for scripting
alldebrid user info --format json | jq '.premiumUntil'# Upload a magnet
alldebrid magnet upload "magnet:?xt=urn:btih:abc123..."
# Check all active downloads
alldebrid magnet list --status active
# Get details for a specific magnet
alldebrid magnet get 123456
# When ready, extract download URLs
alldebrid magnet get 123456 --format json | jq -r '.files[].link' | grep -v null# Check link info before unlocking
alldebrid link info "https://rapidgator.net/file/abc123"
# Unlock the link
alldebrid link unlock "https://rapidgator.net/file/abc123"
# Process password-protected link
alldebrid link info "https://protected-site.com/file" --password "mypass"#!/bin/bash
# download-manager.sh
MAGNET_LINK="$1"
if [ -z "$MAGNET_LINK" ]; then
echo "Usage: $0 <magnet-link>"
exit 1
fi
echo "π Starting download process..."
# Upload magnet
UPLOAD_RESULT=$(alldebrid magnet upload "$MAGNET_LINK" --format json)
MAGNET_ID=$(echo "$UPLOAD_RESULT" | jq -r '.[0].id')
if [ "$MAGNET_ID" = "null" ]; then
echo "β Upload failed"
exit 1
fi
echo "β
Upload successful - ID: $MAGNET_ID"
echo "β³ Waiting for completion..."
# Monitor until ready
while true; do
STATUS=$(alldebrid magnet get "$MAGNET_ID" --format json | jq -r '.status')
case "$STATUS" in
"Ready")
echo "π Download ready!"
# Extract download links
alldebrid magnet get "$MAGNET_ID" --format json | \
jq -r '.files[] | select(.link != null) | "\(.name): \(.link)"'
break
;;
"Error")
echo "β Download failed"
exit 1
;;
*)
echo "π Status: $STATUS"
sleep 30
;;
esac
done#!/usr/bin/env python3
import subprocess
import json
import time
import sys
def run_cli(cmd):
"""Run alldebrid CLI command and return JSON result"""
result = subprocess.run(
["alldebrid"] + cmd + ["--format", "json"],
capture_output=True,
text=True
)
if result.returncode != 0:
raise Exception(f"CLI error: {result.stderr}")
return json.loads(result.stdout)
def batch_upload_magnets(magnet_file):
"""Upload multiple magnets from file"""
with open(magnet_file, 'r') as f:
magnets = [line.strip() for line in f if line.strip()]
print(f"π€ Uploading {len(magnets)} magnets...")
for i, magnet in enumerate(magnets, 1):
try:
result = run_cli(["magnet", "upload", magnet])
magnet_id = result[0]["id"]
print(f"{i}/{len(magnets)} β
Uploaded: {magnet_id}")
except Exception as e:
print(f"{i}/{len(magnets)} β Failed: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 batch_upload.py <magnet_file>")
sys.exit(1)
batch_upload_magnets(sys.argv[1])# Check if host is supported
alldebrid hosts | grep -i rapidgator
# Get link information
alldebrid link info "https://rapidgator.net/file/abc123"
# Unlock and download
DIRECT_LINK=$(alldebrid link unlock "https://rapidgator.net/file/abc123" --format json | jq -r '.link')
curl -L -o "downloaded_file" "$DIRECT_LINK"# Upload magnet
MAGNET_ID=$(alldebrid magnet upload "magnet:?xt=urn:btih:..." --format json | jq -r '.[0].id')
# Wait for processing (manual check)
alldebrid magnet get "$MAGNET_ID"
# When ready, get download links
alldebrid magnet get "$MAGNET_ID" --format json | jq -r '.files[].link' > download_links.txt
# Download all files
while IFS= read -r link; do
if [ "$link" != "null" ]; then
curl -L -O "$link"
fi
done < download_links.txt#!/bin/bash
# cleanup.sh
echo "π§Ή Cleaning up old torrents..."
# Delete expired magnets
EXPIRED=$(alldebrid magnet list --status expired --format json)
echo "$EXPIRED" | jq -r '.[].id' | while read -r id; do
alldebrid magnet delete "$id"
echo "ποΈ Deleted expired magnet: $id"
done
# Delete error magnets
ERROR=$(alldebrid magnet list --status error --format json)
echo "$ERROR" | jq -r '.[].id' | while read -r id; do
alldebrid magnet delete "$id"
echo "ποΈ Deleted failed magnet: $id"
done
echo "β
Cleanup complete"import {
ApiError,
NetworkError,
ValidationError,
ConfigurationError
} from "alldebrid";
async function robustApiCall() {
try {
const result = await client.user.get();
return result;
} catch (error) {
if (error instanceof ApiError) {
// API-specific errors (invalid key, quota exceeded, etc.)
console.error(`API Error [${error.code}]: ${error.message}`);
if (error.code === "AUTH_BAD_APIKEY") {
console.log("π‘ Check your API key in the configuration");
} else if (error.code === "AUTH_USER_BANNED") {
console.log("π« Account is banned - contact AllDebrid support");
}
} else if (error instanceof NetworkError) {
// Network/HTTP errors
console.error(`Network Error: ${error.message}`);
console.log("π Check your internet connection and try again");
} else if (error instanceof ValidationError) {
// Response parsing errors
console.error(`Validation Error: ${error.message}`);
console.log("β οΈ API response format may have changed - check for SDK updates");
} else if (error instanceof ConfigurationError) {
// Client configuration errors
console.error(`Config Error: ${error.message}`);
console.log("βοΈ Check your client configuration");
} else {
// Unknown errors
console.error("Unknown error:", error);
}
throw error; // Re-throw if needed
}
}#!/bin/bash
# robust-cli.sh
set -euo pipefail # Exit on error
# Function to check if command succeeded
check_command() {
if [ $? -eq 0 ]; then
echo "β
$1 successful"
else
echo "β $1 failed"
exit 1
fi
}
# Test API connectivity
echo "π Testing API connection..."
alldebrid user info --format json > /dev/null 2>&1
check_command "API connection test"
# Robust magnet upload with retries
upload_with_retry() {
local magnet="$1"
local max_attempts=3
local attempt=1
while [ $attempt -le $max_attempts ]; do
echo "π€ Upload attempt $attempt/$max_attempts"
if alldebrid magnet upload "$magnet" --format json; then
echo "β
Upload successful on attempt $attempt"
return 0
else
echo "β Attempt $attempt failed"
if [ $attempt -eq $max_attempts ]; then
echo "π₯ All upload attempts failed"
return 1
fi
sleep 5
fi
((attempt++))
done
}# .github/workflows/alldebrid.yml
name: AllDebrid Backup
on:
schedule:
- cron: '0 2 * * *' # Daily at 2 AM
workflow_dispatch:
jobs:
backup:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install AllDebrid CLI
run: npm install -g alldebrid
- name: Backup saved links
run: |
alldebrid user saved-links-list --format yaml > saved-links-backup.yml
env:
ALLDEBRID_API_KEY: ${{ secrets.ALLDEBRID_API_KEY }}
- name: Commit backup
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add saved-links-backup.yml
git commit -m "Daily backup: $(date)" || exit 0
git push# Dockerfile
FROM node:20-alpine
# Install CLI globally
RUN npm install -g alldebrid
# Create app directory
WORKDIR /app
# Copy scripts
COPY scripts/ ./scripts/
RUN chmod +x scripts/*.sh
# Set default command
CMD ["./scripts/monitor.sh"]# docker-compose.yml
version: '3.8'
services:
alldebrid-monitor:
build: .
environment:
- ALLDEBRID_API_KEY=${ALLDEBRID_API_KEY}
volumes:
- ./downloads:/downloads
restart: unless-stopped// Express.js endpoint
const express = require('express');
const { exec } = require('child_process');
const app = express();
app.post('/api/upload-magnet', async (req, res) => {
const { magnetLink } = req.body;
if (!magnetLink) {
return res.status(400).json({ error: 'Magnet link required' });
}
const command = `alldebrid magnet upload "${magnetLink}" --format json`;
exec(command, { env: { ...process.env } }, (error, stdout, stderr) => {
if (error) {
console.error('CLI error:', error);
return res.status(500).json({ error: 'Upload failed' });
}
try {
const result = JSON.parse(stdout);
res.json({ success: true, data: result });
} catch (parseError) {
res.status(500).json({ error: 'Invalid response format' });
}
});
});- Always check API limits: Monitor your usage to avoid hitting rate limits
- Use status filters:
--status readyfor completed torrents saves bandwidth - Implement retries: Network requests can fail, especially for large operations
- Cache host information: Host list doesn't change frequently
- Use configuration files: Avoid hardcoding API keys in scripts
- Monitor disk space: Downloads can be large, ensure adequate storage
- Log operations: Keep track of successful/failed operations for debugging
- Use batch operations: More efficient than individual API calls
- Handle timeouts: Large torrents may take time to process
- Test with small files first: Validate your workflow before processing large batches