@hallya/ds-api
v1.5.1
Published
A TypeScript library for interacting with Synology Download Station API, compatible with both Deno and Node.js
Maintainers
Readme
Synology Download Station API
A TypeScript library for interacting with Synology Download Station API, compatible with both Deno and Node.js.
Installation
Node.js / npm
npm install @hallya/ds-apiRequirements:
- Node.js 18+
- Access to a Synology NAS with Download Station package installed
- Valid Synology user credentials with Download Station permissions
Deno
You can use this library in Deno in two ways:
Option 1: Import from npm (recommended)
import { SynologyDS } from "npm:@hallya/ds-api";Option 2: Import from GitHub
import { SynologyDS } from "https://raw.githubusercontent.com/hallya/ds-api/main/index.ts";Requirements:
- Deno 1.28+
- Access to a Synology NAS with Download Station package installed
- Valid Synology user credentials with Download Station permissions
- Required permissions:
--allow-env --allow-net --allow-read
Quick Setup
Copy
.env.exampleto.envand configure your settings:cp .env.example .envEdit
.envwith your Synology NAS details:NAS_URL=https://your-nas-url SYNOLOGY_USERNAME=your_username SYNOLOGY_PASSWORD=your_password_here
Usage
As a Library
Simple API (recommended)
import { SynologyDS } from '@hallya/ds-api';
async function example() {
// Initialize with configuration
const ds = await new SynologyDS({
baseUrl: 'https://your-nas-url',
username: 'your-username',
password: 'your-password'
}).initialize();
// Authenticate with the NAS
await ds.authenticate();
// Get all tasks sorted by upload size and completion time
const tasks = await ds.getTasksByUploadAndTime();
console.log('Tasks:', tasks);
// Remove tasks until total size is 10.5 GB or more
const result = await ds.purgeTasksBySize(10.5);
console.log(result.message);
// Always disconnect when done
await ds.disconnect();
}Advanced Examples
Error handling and cleanup:
async function safeExample() {
let ds;
try {
ds = await new SynologyDS({
baseUrl: 'https://your-nas-url',
username: 'your-username',
password: 'your-password'
}).initialize();
await ds.authenticate();
// Your operations here
const tasks = await ds.getTasks();
console.log(`Found ${tasks.length} tasks`);
} catch (error) {
console.error('Operation failed:', error.message);
} finally {
if (ds) {
await ds.disconnect();
}
}
}Working with specific tasks:
async function taskManagement() {
const ds = await new SynologyDS({
baseUrl: 'https://your-nas-url',
username: 'your-username',
password: 'your-password'
}).initialize();
await ds.authenticate();
// Get detailed info about a specific task
const taskInfo = await ds.getTaskInfo('ubuntu-22.04.iso');
console.log('Task details:', taskInfo);
// Remove tasks by title
await ds.removeTasksByTitles('old-movie.avi,expired-document.pdf');
await ds.disconnect();
}Advanced API (low-level functions)
import {
getApiInfo,
login,
listTasks,
removeTasks,
logout,
pickAuthVersion,
pickTaskVersion
} from '@hallya/ds-api';
async function example() {
const info = await getApiInfo();
const authVer = pickAuthVersion(info);
const taskVer = pickTaskVersion(info);
const loginResp = await login('username', 'password', 'DownloadStation', authVer);
const sid = loginResp.data.sid;
const tasks = await listTasks(sid, taskVer);
console.log(tasks);
await logout(sid, authVer);
}CLI Usage
The CLI tool provides several commands for managing your Synology Download Station torrents:
Installation
First, install the package globally or run it using npx:
npm install -g @hallya/ds-api
# or
npx ds-api
#### Commands
```bash
# List all torrents
ds-api list
# Export torrents to JSON file
ds-api list --json
# Remove torrents by title (comma-separated)
ds-api remove "title1,title2"
# Purge torrents until total size is at or above specified limit (in GB)
# Removes oldest/lowest-ratio torrents (sorted by upload size, then oldest completion timestamp) until total size is at or below limit
ds-api purge "10.5"
# Dry run purge (simulation - shows what would be deleted)
ds-api purge "10.5" --dry-run
# Show detailed information for a specific torrent
ds-api info "torrent_title"Common Use Cases
Daily cleanup: Remove torrents when disk space gets low
ds-api purge "50" # Remove torrents until total size is 50GB or moreSelective removal: Remove specific completed torrents
ds-api remove "ubuntu.iso,windows.iso"Monitor downloads: Check current download status
ds-api listExport data: Get torrents data in JSON format for scripting
ds-api list --json # Creates torrents.json fileInvestigate issues: Get detailed info about a specific torrent
ds-api info "problematic_torrent"Usage with Deno
As a Library
Simple API (recommended)
import { SynologyDS } from "npm:@hallya/ds-api";
async function example() {
// Initialize with configuration
const ds = await new SynologyDS({
baseUrl: 'https://your-nas-url',
username: 'your-username',
password: 'your-password'
}).initialize();
// Authenticate with the NAS
await ds.authenticate();
// Get all tasks sorted by upload size and completion time
const tasks = await ds.getTasksByUploadAndTime();
console.log('Tasks:', tasks);
// Remove tasks until total size is 10.5 GB or more
const result = await ds.purgeTasksBySize(10.5);
console.log(result.message);
// Always disconnect when done
await ds.disconnect();
}
example().catch(console.error);Using Environment Variables
Create a .env file:
NAS_URL=https://your-nas-url
SYNOLOGY_USERNAME=your_username
SYNOLOGY_PASSWORD=your_password_here
LOG_LEVEL=INFOThen use the library:
import { load } from "std/dotenv";
import { SynologyDS } from "npm:@hallya/ds-api";
await load({ export: true });
const ds = await new SynologyDS().initialize();
await ds.authenticate();
// ... use the library
await ds.disconnect();CLI Usage with Deno
You can run the CLI directly with Deno:
# Run with required permissions
deno run --allow-env --allow-net --allow-read --allow-write \
https://raw.githubusercontent.com/hallya/ds-api/main/bin/cli.ts list
# Or clone the repo and run locally
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts listCommands (same as Node.js version)
# List all torrents
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts list
# Export torrents to JSON file
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts list --json
# Remove torrents by title
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts remove "title1,title2"
# Purge torrents by size
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts purge "10.5"
# Dry run purge
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts purge "10.5" --dry-run
# Show detailed information
deno run --allow-env --allow-net --allow-read --allow-write bin/cli.ts info "torrent_title"Using Deno Tasks (recommended)
If you clone the repository, you can use Deno tasks defined in deno.json:
# List torrents
deno task list
# List as JSON
deno task list:json
# Remove torrents
deno task remove "title1,title2"
# Purge torrents
deno task purge "10.5"
# Get info
deno task info "torrent_title"Differences between Deno and Node.js
Runtime Compatibility
This library is fully compatible with both Node.js and Deno runtimes. Here are the key differences:
Node.js (18+)
- Uses ESM modules (
type: "module"in package.json) - Environment variables via
process.env - Uses
pinologger andnpm:pathmodule - No permissions required
- Import:
import { SynologyDS } from '@hallya/ds-api'
Deno (1.28+)
- Native TypeScript support
- Environment variables via
Deno.envorstd/dotenv - Uses
pinologger (vianpm:pino) andstd/pathmodule - Requires explicit permissions:
--allow-env --allow-net --allow-read - Import options:
- From npm:
import { SynologyDS } from "npm:@hallya/ds-api" - From JSR:
import { SynologyDS } from "jsr:@hallya/ds-api" - From GitHub:
import { SynologyDS } from "https://raw.githubusercontent.com/hallya/ds-api/main/index.ts"
- From npm:
Logging
- Both runtimes use
pinologger - Log levels:
error,warn,info,debug(lowercase) - Environment variable:
LOG_LEVEL(accepts both uppercase and lowercase) - Default level:
info
Path Handling
- Node.js: Uses
npm:pathmodule (automatically bundled) - Deno: Uses
std/pathmodule (native Deno standard library) - Both handle path separators correctly for their respective platforms
Configuration
Environment Variables
SYNOLOGY_USERNAME: Synology usernameSYNOLOGY_PASSWORD: Synology password (required)SYNOLOGY_BASE_PATH: Base path for file operations (default:/volume1)SYNOLOGY_DISABLE_SSL_VERIFICATION: Set totrueto disable SSL verification (default:false)LOG_LEVEL: Logging level (error,warn,info,debug) (default:info)NAS_URL: Synology NAS URL (default:https://download.lcn-dlc.dev)RETRY_ATTEMPTS: Number of retry attempts for API calls (default:3)RETRY_DELAY: Delay between retry attempts in milliseconds (default:1000)
Configuration Options
When using the library programmatically, you can pass configuration options to the SynologyDS constructor:
const ds = new SynologyDS({
baseUrl: 'https://your-nas-url',
username: 'your-username',
path: '/custom/path'
});API Reference
Classes
SynologyDS: Main class for interacting with Synology Download Stationconstructor(options): Create instance with configurationinitialize(): Initialize API infoauthenticate(): Login to Synologydisconnect(): Logout and cleanupgetTasks(): Get all tasksgetTasksByUploadAndTime(): Get tasks sorted by upload sizeremoveTasksByIds(ids, forceComplete): Remove tasks by IDsremoveTasksByTitles(titles): Remove tasks by titlespurgeTasksBySize(maxSizeGB, dryRun): Purge tasks by size limitgetTaskByTitle(title): Get single task by titlegetTaskInfo(title): Get detailed task info
CLIHandler: Command-line interface handlerconstructor(options): Create CLI handlerinitialize(): Initialize handlersetDryRun(dryRun): Enable/disable dry-run modesetJson(json): Enable/disable JSON output modeexecuteCommand(action, arg): Execute CLI command
Authentication
getApiInfo(): Get API informationlogin(account, passwd, session, version): Login to Synologylogout(sid, version): Logout from SynologypickAuthVersion(info): Get appropriate auth API version
Tasks
listTasks(sid, version): List download tasksremoveTasks(sid, idsCsv, forceComplete, version): Remove taskspickTaskVersion(info): Get appropriate task API versionsortTasksByUploadAndTime(tasks): Sort tasks by upload size and completion timecalculateTotalSize(tasks): Calculate total file size of tasksselectTasksForPurge(tasks, maxSizeGB): Select tasks to purge based on size limit
CLI Utilities
displayTasks(tasks): Display formatted task listvalidateRemoveArgs(titlesArg): Validate remove command argumentsfindTaskIdsByTitles(titlesArg, tasks): Find task IDs by titlesvalidatePurgeArgs(sizeArg): Validate purge command argumentsvalidateInfoArgs(titleArg): Validate info command argumentsdisplayTaskInfo(task): Display detailed task informationformatBytes(bytes): Format bytes to human readable formatformatTimestamp(timestamp): Format timestamp to readable date
Task Utilities
sortTasksByUploadAndTime(tasks): Sort tasks by upload size and completion timecalculateTotalSize(tasks): Calculate total file size of tasksselectTasksForPurge(tasks, maxSizeGB): Select tasks to purge based on cumulative file size
Troubleshooting
Common Issues
Authentication failed
- Verify your Synology credentials are correct
- Ensure your user has Download Station permissions
- Check that Download Station package is installed and running
Connection timeout
- Verify the NAS URL is accessible
- Check network connectivity
- Try increasing
RETRY_ATTEMPTSorRETRY_DELAY
SSL certificate errors
- Set
SYNOLOGY_DISABLE_SSL_VERIFICATION=truefor self-signed certificates - Or configure proper SSL certificates on your NAS
Debug Mode
Enable debug logging to troubleshoot issues:
LOG_LEVEL=debug ds-api listOr programmatically:
const ds = new SynologyDS({
// ... other options
logLevel: 'debug'
});Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
- Clone the repository
- Install dependencies:
npm install - Copy and configure environment:
cp .env.example .env - Run tests:
npm test(when tests are added) - Run linting:
npm run lint(when linting is configured)
Release Process
The project uses automated releases via GitHub Actions:
- Make changes and commit them
- Create a release:
npm run release- This will bump the version, create a git tag, and push to GitHub
- GitHub Actions will automatically publish to npm
Manual release (if needed):
npm version patch # or minor/major
git push --follow-tagsLicense
MIT - see LICENSE file for details
Changelog
See CHANGELOG.md for version history and updates.
