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
8 changes: 8 additions & 0 deletions TelegramDownloader/ClientApp/apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,25 @@
"@tfm/api-client": "*",
"@tfm/file-manager": "*",
"@tfm/ui": "*",
"docx-preview": "^0.4.1",
"highlight.js": "^11.12.0",
"lucide-react": "^0.562.0",
"music-metadata": "^11.16.1",
"papaparse": "^5.7.1",
"pdfjs-dist": "^6.5.438",
"radix-ui": "^1.8.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-markdown": "^10.1.0",
"react-router": "^7.11.0",
"read-excel-file": "^9.3.20",
"remark-gfm": "^4.0.1",
"uqr": "^0.1.3",
"zustand": "^5.0.9"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"@types/papaparse": "^5.5.2",
"@vitejs/plugin-react": "^5.1.1",
"sharp": "^0.35.5",
"tailwindcss": "^4.1.18",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,19 @@ describe('messageMedia', () => {
});
});

it('opens Word, Excel, Markdown and log attachments in the document viewer', () => {
const doc = (id: number, fileName: string) => messageMedia('5', msg(id, at, { hasMedia: true, mediaType: 'document', fileName }), url, 'x');
expect(doc(13, 'Report.docx')).toMatchObject({ kind: 'document', name: 'Report.docx' });
expect(doc(14, 'Budget.xlsx')).toMatchObject({ kind: 'document' });
expect(doc(15, 'README.md')).toMatchObject({ kind: 'text' });
expect(doc(16, 'server.log')).toMatchObject({ kind: 'text' });
});

it('has no viewer for the old binary Office formats', () => {
expect(messageMedia('5', msg(17, at, { hasMedia: true, mediaType: 'document', fileName: 'Old.doc' }), url, 'x')).toBeNull();
expect(messageMedia('5', msg(18, at, { hasMedia: true, mediaType: 'document', fileName: 'Old.xls' }), url, 'x')).toBeNull();
});

it('leaves other files and text messages alone', () => {
expect(messageMedia('5', msg(11, at, { hasMedia: true, mediaType: 'document', fileName: 'backup.zip' }), url, 'x')).toBeNull();
expect(messageMedia('5', msg(12, at), url, 'x')).toBeNull();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ApiChatMessageDto, ApiChatWindowDto, ChatMessageKind } from '@tfm/api-client';
import { documentViewerKind } from '@/features/player/public';

/** How long the search in the chat waits after the last key (Enter does not wait). */
export const CHAT_SEARCH_DELAY_MS = 1200;
Expand Down Expand Up @@ -169,15 +170,15 @@ export function fileTypeLabel(m: Pick<ApiChatMessageDto, 'fileName' | 'mimeType'
/** What the player/viewer can do with the file of a message that is not in the channel index. */
export type MessageMedia =
| { kind: 'audio'; id: string; title: string; artist?: string; url: string; size: number; durationSeconds?: number }
| { kind: 'video' | 'image' | 'pdf'; id: string; name: string; url: string; downloadUrl: string; mimeType?: string; size: number };
| { kind: 'video' | 'image' | 'pdf' | 'text' | 'document'; id: string; name: string; url: string; downloadUrl: string; mimeType?: string; size: number };

const IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.avif']);

/**
* Plays a message attachment straight from Telegram
* (`GET /api/v1/channels/{id}/messages/{messageId}/content`), without
* indexing it first: audio for the player, video/photo/PDF for the viewer.
* Null for other files (they still go through "Download to server").
* indexing it first: audio for the player, video, photos and documents
* (PDF, text, Markdown, CSV, Word, Excel) for the viewer. Null for other files (they still go through "Download to server").
*/
export function messageMedia(
channelId: string,
Expand All @@ -196,7 +197,11 @@ export function messageMedia(
return { kind: 'audio', id, title, artist: m.performer ?? undefined, url, size: m.fileSize, durationSeconds: m.duration ?? undefined };
}
const kind =
m.mediaType === 'video' ? 'video' : m.mediaType === 'photo' || IMAGE_EXT.has(ext) ? 'image' : ext === '.pdf' || m.mimeType === 'application/pdf' ? 'pdf' : null;
m.mediaType === 'video'
? 'video'
: m.mediaType === 'photo' || IMAGE_EXT.has(ext)
? 'image'
: documentViewerKind(m.fileName, m.mimeType);
if (!kind) return null;
return { kind, id, name, url, downloadUrl: contentUrl(m.id, 'attachment'), mimeType: m.mimeType ?? undefined, size: m.fileSize };
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ApiFileDto, BrowseFilter, BrowseSortBy } from '@tfm/api-client';
import { entryMediaKind, extensionOf, joinPath, mediaKindOf, normalizePath, type FileEntry, type ListFilter, type MediaKind, type SortSpec } from '@tfm/file-manager';
import type { AudioTrack, ViewerItem } from '@/features/player/public';
import { documentViewerKind, type AudioTrack, type ViewerItem } from '@/features/player/public';
import { getAudioInfo } from './audioInfo';

const CATEGORY_KIND: Record<string, MediaKind> = {
Expand Down Expand Up @@ -102,9 +102,7 @@ export function viewerKind(entry: FileEntry): ViewerKind | null {
if (kind === 'image') return 'image';
if (kind === 'video') return 'video';
if (kind === 'audio') return 'audio';
if (entry.extension === 'pdf') return 'pdf';
if (kind === 'text') return 'text';
return null;
return documentViewerKind(entry.name) ?? (kind === 'text' ? 'text' : null);
}

/** An entry as a viewer item (inline URL, optional transcoding URL). */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest';
import { codeLanguageOf, documentFormatOf, documentViewerKind, extensionOfName } from './documentFormats';

describe('documentFormatOf', () => {
it('knows the documents by extension, in any case', () => {
expect(documentFormatOf('Manual.PDF')).toBe('pdf');
expect(documentFormatOf('README.md')).toBe('markdown');
expect(documentFormatOf('notes.markdown')).toBe('markdown');
expect(documentFormatOf('data.csv')).toBe('csv');
expect(documentFormatOf('data.tsv')).toBe('tsv');
expect(documentFormatOf('Budget.xlsx')).toBe('xlsx');
expect(documentFormatOf('Report.docx')).toBe('docx');
});

it('opens logs, subtitles and notes as plain text', () => {
expect(documentFormatOf('server.log')).toBe('text');
expect(documentFormatOf('movie.srt')).toBe('text');
expect(documentFormatOf('release.nfo')).toBe('text');
expect(documentFormatOf('todo.txt')).toBe('text');
});

it('opens source and config files as code', () => {
expect(documentFormatOf('appsettings.json')).toBe('code');
expect(documentFormatOf('docker-compose.yml')).toBe('code');
expect(documentFormatOf('script.py')).toBe('code');
});

it('has no viewer for the old Office formats nor for archives', () => {
expect(documentFormatOf('Old.doc')).toBeNull();
expect(documentFormatOf('Old.xls')).toBeNull();
expect(documentFormatOf('Slides.ppt')).toBeNull();
expect(documentFormatOf('backup.zip')).toBeNull();
});

it('falls back to the MIME type of files without an extension', () => {
expect(documentFormatOf('attachment', 'application/pdf')).toBe('pdf');
expect(documentFormatOf('attachment', 'text/plain; charset=utf-8')).toBe('text');
expect(documentFormatOf(null, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')).toBe('docx');
});

it('trusts the extension over the MIME type', () => {
expect(documentFormatOf('notes.md', 'text/plain')).toBe('markdown');
});
});

describe('documentViewerKind', () => {
it('is pdf, document (Word and Excel) or text', () => {
expect(documentViewerKind('a.pdf')).toBe('pdf');
expect(documentViewerKind('a.docx')).toBe('document');
expect(documentViewerKind('a.xlsx')).toBe('document');
expect(documentViewerKind('a.md')).toBe('text');
expect(documentViewerKind('a.csv')).toBe('text');
expect(documentViewerKind('a.log')).toBe('text');
expect(documentViewerKind('a.rar')).toBeNull();
});
});

describe('codeLanguageOf', () => {
it('gives the highlighting language of code files only', () => {
expect(codeLanguageOf('Program.cs')).toBe('csharp');
expect(codeLanguageOf('config.toml')).toBe('ini');
expect(codeLanguageOf('server.log')).toBeUndefined();
});
});

describe('extensionOfName', () => {
it('reads the last extension of the file name, not of a folder', () => {
expect(extensionOfName('archive.tar.gz')).toBe('gz');
expect(extensionOfName('/var/my.folder/README')).toBe('');
expect(extensionOfName('.gitignore')).toBe('gitignore');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* Which document viewer opens a file, from its name (and MIME type when
* there is no extension). Pure and small: used by every place that opens the
* viewer; the viewers themselves are lazy chunks.
*/
export type DocumentFormat = 'pdf' | 'markdown' | 'csv' | 'tsv' | 'xlsx' | 'docx' | 'code' | 'text';

/** Highlight.js language of each source/config extension. */
const CODE_LANGUAGES: Record<string, string> = {
json: 'json',
jsonc: 'json',
xml: 'xml',
html: 'xml',
htm: 'xml',
xhtml: 'xml',
plist: 'xml',
yml: 'yaml',
yaml: 'yaml',
toml: 'ini',
ini: 'ini',
cfg: 'ini',
conf: 'ini',
properties: 'properties',
css: 'css',
scss: 'scss',
js: 'javascript',
mjs: 'javascript',
cjs: 'javascript',
jsx: 'javascript',
ts: 'typescript',
tsx: 'typescript',
py: 'python',
sh: 'bash',
bash: 'bash',
zsh: 'bash',
ps1: 'powershell',
bat: 'dos',
cmd: 'dos',
sql: 'sql',
cs: 'csharp',
java: 'java',
kt: 'kotlin',
kts: 'kotlin',
go: 'go',
rs: 'rust',
c: 'c',
h: 'c',
cpp: 'cpp',
cc: 'cpp',
hpp: 'cpp',
php: 'php',
rb: 'ruby',
lua: 'lua',
diff: 'diff',
patch: 'diff'
};

/** Plain text: shown as is (logs, subtitles, notes...). */
const PLAIN_TEXT = new Set(['txt', 'text', 'log', 'out', 'nfo', 'srt', 'vtt', 'ass', 'lrc', 'cue', 'env', 'csproj', 'sln', 'gitignore']);

const BY_EXTENSION: Record<string, DocumentFormat> = {
pdf: 'pdf',
md: 'markdown',
markdown: 'markdown',
csv: 'csv',
tsv: 'tsv',
xlsx: 'xlsx',
xlsm: 'xlsx',
docx: 'docx'
};

const BY_MIME: Record<string, DocumentFormat> = {
'application/pdf': 'pdf',
'text/markdown': 'markdown',
'text/csv': 'csv',
'text/tab-separated-values': 'tsv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
'application/json': 'code',
'application/xml': 'code',
'text/xml': 'code'
};

/** Lower-case extension of a file name, without the dot ('' when none). */
export function extensionOfName(name: string | undefined | null): string {
if (!name) return '';
const slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
const base = name.slice(slash + 1);
const dot = base.lastIndexOf('.');
// ".gitignore" has no extension but is named after one
if (dot === 0) return base.slice(1).toLowerCase();
return dot > 0 ? base.slice(dot + 1).toLowerCase() : '';
}

/** The viewer of a file, or null when there is none (old Office formats, archives...). */
export function documentFormatOf(name: string | undefined | null, mimeType?: string | null): DocumentFormat | null {
const ext = extensionOfName(name);
if (ext) {
if (BY_EXTENSION[ext]) return BY_EXTENSION[ext];
if (CODE_LANGUAGES[ext]) return 'code';
if (PLAIN_TEXT.has(ext)) return 'text';
}
const mime = (mimeType ?? '').toLowerCase().split(';')[0].trim();
if (BY_MIME[mime]) return BY_MIME[mime];
if (!ext && mime.startsWith('text/')) return 'text';
return null;
}

/** Highlight.js language for a `code` file (undefined: no highlighting). */
export function codeLanguageOf(name: string | undefined | null): string | undefined {
return CODE_LANGUAGES[extensionOfName(name)];
}

/** The viewer kind a document opens with (`document`: Word and Excel). */
export function documentViewerKind(name: string | undefined | null, mimeType?: string | null): 'pdf' | 'text' | 'document' | null {
const format = documentFormatOf(name, mimeType);
if (!format) return null;
if (format === 'pdf') return 'pdf';
if (format === 'xlsx' || format === 'docx') return 'document';
return 'text';
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
*/
import { useViewer } from './viewerStore';

export { codeLanguageOf, documentFormatOf, documentViewerKind, type DocumentFormat } from './documentFormats';

/** A playable audio item. URLs must be playable by an <audio> element (same-origin cookie auth). */
export interface AudioTrack {
/** Stable id (file id, or local path for local files). */
Expand Down Expand Up @@ -35,11 +37,12 @@ export interface AudioTrack {
clip?: { start: number; end?: number | null };
}

/** Something to show in the viewer (image gallery, video player, PDF, text). */
/** Something to show in the viewer (image gallery, video player, PDF, text, Word and Excel documents). */
export interface ViewerItem {
id: string;
name: string;
kind: 'image' | 'video' | 'audio' | 'pdf' | 'text' | 'other';
/** `text`: plain text, code, Markdown, CSV; `document`: Word (.docx) and Excel (.xlsx). */
kind: 'image' | 'video' | 'audio' | 'pdf' | 'text' | 'document' | 'other';
/** Inline URL (Range-capable for video). */
url: string;
/** Optional transcoding URL for video formats the browser can't play natively. */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,54 +1,12 @@
import { Button, Spinner } from '@tfm/ui';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@tfm/ui';
import { Download, FileQuestion, FileText } from 'lucide-react';
import { t } from '@/i18n';
import { formatBytes } from '@/lib/format';
import type { ViewerItem } from '../public';

/** Text files above this size are not previewed (offered as a download). */
export const TEXT_PREVIEW_MAX_BYTES = 2 * 1024 * 1024;

/** PDF in the browser's own viewer. */
export function PdfView({ item }: { item: ViewerItem }) {
return (
<div className="flex size-full flex-col px-2 pb-2 pt-20 sm:px-6 sm:pb-6">
<iframe title={item.name} src={item.url} className="min-h-0 w-full flex-1 rounded-2xl border border-white/10 bg-white shadow-elevated" />
</div>
);
}

/** Small text files, shown as plain text. */
export function TextView({ item }: { item: ViewerItem }) {
const tooBig = (item.size ?? 0) > TEXT_PREVIEW_MAX_BYTES;
const { data, isLoading, isError } = useQuery({
queryKey: ['player', 'text-preview', item.url],
enabled: !tooBig,
staleTime: 60_000,
queryFn: async ({ signal }) => {
const res = await fetch(item.url, { signal, credentials: 'same-origin', headers: { Range: `bytes=0-${TEXT_PREVIEW_MAX_BYTES - 1}` } });
if (!res.ok) throw new Error(String(res.status));
return res.text();
}
});
if (tooBig || isError) return <DownloadCard item={item} reason={tooBig ? t('This file is too large to preview.') : t('The file could not be loaded')} />;
return (
<div className="flex size-full flex-col px-2 pb-2 pt-20 sm:px-6 sm:pb-6">
<div className="min-h-0 w-full flex-1 overflow-auto rounded-2xl border border-white/10 bg-neutral-950/80 shadow-elevated" data-no-player-keys>
{isLoading ? (
<div className="flex h-full items-center justify-center">
<Spinner size="lg" className="text-white" />
</div>
) : (
<pre className="whitespace-pre-wrap break-words p-4 font-mono text-[13px] leading-relaxed text-neutral-100 sm:p-6">{data}</pre>
)}
</div>
</div>
);
}

/** Anything the browser cannot show. */
export function DownloadCard({ item, reason }: { item: ViewerItem; reason?: string }) {
const Icon = item.kind === 'text' ? FileText : FileQuestion;
const Icon = item.kind === 'text' || item.kind === 'document' || item.kind === 'pdf' ? FileText : FileQuestion;
return (
<div className="mx-4 flex w-full max-w-sm flex-col items-center gap-4 rounded-3xl border border-white/10 bg-white/5 p-8 text-center shadow-elevated backdrop-blur-xl">
<div className="flex size-16 items-center justify-center rounded-2xl bg-white/10">
Expand Down
Loading
Loading