A Node.js library for interacting with Synology Download Station API.
npm install @hallya/ds-api- Node.js 18+
- Access to a Synology NAS with Download Station package installed
- Valid Synology user credentials with Download Station permissions
-
Copy
.env.exampleto.envand configure your settings:cp .env.example .env
-
Edit
.envwith your Synology NAS details:NAS_URL=https://your-nas-url SYNOLOGY_USERNAME=your_username SYNOLOGY_PASSWORD=your_password_here
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();
}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();
}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);
}The CLI tool provides several commands for managing your Synology Download Station torrents:
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"
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 file
ds-api list --json /path/to/dir # Creates /path/to/dir/torrents.json
ds-api list --json /path/to/file.json # Creates /path/to/file.jsonInvestigate issues: Get detailed info about a specific torrent
ds-api info "problematic_torrent"SYNOLOGY_USERNAME: Synology usernameSYNOLOGY_PASSWORD: Synology password (required)SYNOLOGY_DOWNLOAD_ROOT_PATH: Root path for download operations and security validation (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)
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",
});-
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
getApiInfo(): Get API informationlogin(account, passwd, session, version): Login to Synologylogout(sid, version): Logout from SynologypickAuthVersion(info): Get appropriate auth API version
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
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
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
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
Enable debug logging to troubleshoot issues:
LOG_LEVEL=debug ds-api listOr programmatically:
const ds = new SynologyDS({
// ... other options
logLevel: "debug",
});Contributions are welcome! Please feel free to submit a Pull Request.
- 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)
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-tagsMIT - see LICENSE file for details
See CHANGELOG.md for version history and updates.