Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/commands/download.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import chalk from 'chalk';
import { Command } from 'commander';
import { DownloadOptions } from '../types/commands';
import { createSlackClient } from '../utils/client-factory';
import { renderByFormat } from '../utils/command-support';
import { wrapCommand } from '../utils/command-wrapper';
import { parseProfile } from '../utils/option-parsers';
import type { DownloadFileResult } from '../utils/slack-operations/file-operations';
import { createValidationHook } from '../utils/validators';

function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export function setupDownloadCommand(): Command {
const downloadCommand = new Command('download')
.description('Download a file from Slack')
.option('-u, --url <url>', 'File URL (url_private or url_private_download from message)')
.option('-i, --id <id>', 'Slack file ID (e.g. F0BFXAEP1UZ)')
.option('-o, --output <path>', 'Output file path (defaults to original filename in current dir)')
.option('--format <format>', 'Output format: table, simple, json', 'table')
.option('--profile <profile>', 'Use specific workspace profile')
.hook(
'preAction',
createValidationHook([
(options) => {
if (!options.url && !options.id) {
return 'You must specify either --url or --id';
}
if (options.url && options.id) {
return 'Cannot use both --url and --id';
}
return null;
},
])
)
.action(
wrapCommand(async (options: DownloadOptions) => {
const profile = parseProfile(options.profile);
const client = await createSlackClient(profile);

const result = await client.downloadFile({
url: options.url,
fileId: options.id,
outputPath: options.output,
});

renderByFormat<DownloadFileResult>(options, result, {
table: (data) => {
console.log(chalk.green(`✓ Downloaded: ${data.fileName}`));
console.log(` path: ${data.filePath}`);
console.log(` size: ${formatFileSize(data.size)}`);
},
simple: (data) => {
console.log(data.filePath);
},
});
})
);

return downloadCommand;
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { setupChannelCommand } from './commands/channel';
import { setupChannelsCommand } from './commands/channels';
import { setupConfigCommand } from './commands/config';
import { setupDeleteCommand } from './commands/delete';
import { setupDownloadCommand } from './commands/download';
import { setupEditCommand } from './commands/edit';
import { setupHistoryCommand } from './commands/history';
import { setupInviteCommand } from './commands/invite';
Expand Down Expand Up @@ -56,6 +57,7 @@ export function createProgram(): Command {
program.addCommand(setupEditCommand());
program.addCommand(setupDeleteCommand());
program.addCommand(setupUploadCommand());
program.addCommand(setupDownloadCommand());
program.addCommand(setupReactionCommand());
program.addCommand(setupPinCommand());
program.addCommand(setupUsersCommand());
Expand Down
8 changes: 8 additions & 0 deletions src/types/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,11 @@ export interface CanvasListOptions {
format?: 'table' | 'simple' | 'json';
profile?: string;
}

export interface DownloadOptions {
url?: string;
id?: string;
output?: string;
format?: 'table' | 'simple' | 'json';
profile?: string;
}
9 changes: 8 additions & 1 deletion src/utils/slack-client-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ import type {
import { createSlackClientContext } from './slack-operations/base-client';
import { CanvasOperations } from './slack-operations/canvas-operations';
import { ChannelOperations } from './slack-operations/channel-operations';
import type { UploadFileOptions } from './slack-operations/file-operations';
import type {
DownloadFileOptions,
UploadFileOptions,
} from './slack-operations/file-operations';
import { FileOperations } from './slack-operations/file-operations';
import { MessageOperations } from './slack-operations/message-operations';
import { PinOperations } from './slack-operations/pin-operations';
Expand Down Expand Up @@ -167,6 +170,10 @@ export class SlackApiClient {
return this.fileOps.uploadFile(options);
}

async downloadFile(options: DownloadFileOptions) {
return this.fileOps.downloadFile(options);
}

async addReaction(channel: string, timestamp: string, emoji: string): Promise<void> {
return this.reactionOps.addReaction(channel, timestamp, emoji);
}
Expand Down
59 changes: 58 additions & 1 deletion src/utils/slack-operations/file-operations.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { basename } from 'path';
import { createWriteStream } from 'fs';
import { basename, join } from 'path';
import { pipeline } from 'stream/promises';
import { BaseSlackClient, SlackClientDependency } from './base-client';
import { ChannelOperations } from './channel-operations';

Expand Down Expand Up @@ -27,6 +29,19 @@ export interface UploadFileResult {
files: UploadedFileInfo[];
}

export interface DownloadFileOptions {
url?: string;
fileId?: string;
outputDir?: string;
outputPath?: string;
}

export interface DownloadFileResult {
filePath: string;
fileName: string;
size: number;
}

export class FileOperations extends BaseSlackClient {
private channelOps: ChannelOperations;

Expand All @@ -35,6 +50,48 @@ export class FileOperations extends BaseSlackClient {
this.channelOps = channelOps ?? new ChannelOperations(dependency);
}

async downloadFile(options: DownloadFileOptions): Promise<DownloadFileResult> {
let url: string;
let fileName: string;

if (options.fileId) {
const info = (await this.client.files.info({ file: options.fileId })) as {
file?: { url_private_download?: string; url_private?: string; name?: string };
};
url = info.file?.url_private_download || info.file?.url_private || '';
fileName = info.file?.name || options.fileId;
if (!url) throw new Error('No download URL found for this file');
} else if (options.url) {
url = options.url;
const urlPath = new URL(url).pathname;
fileName = decodeURIComponent(basename(urlPath));
} else {
throw new Error('Either --url or --id is required');
}

const outputPath = options.outputPath || join(options.outputDir || '.', fileName);
const token = this.client.token;
if (!token) throw new Error('No token available');

const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
});

if (!response.ok) {
throw new Error(`Download failed: ${response.status} ${response.statusText}`);
}
if (!response.body) {
throw new Error('No response body');
}

const fileStream = createWriteStream(outputPath);
await pipeline(response.body as unknown as NodeJS.ReadableStream, fileStream);

const { size } = await import('fs').then((fs) => fs.promises.stat(outputPath));

return { filePath: outputPath, fileName, size };
}

async uploadFile(options: UploadFileOptions): Promise<UploadFileResult> {
const channelId = await this.channelOps.resolveChannelId(options.channel);

Expand Down
Loading