📄 Lectures: открытие + скачивание через Telegram API

- api.ts: LectureListItem обновлён (title, file_url, level_code, lecture_language)
- LecturesPage.tsx: открытие через Telegram.WebApp.openLink,
  скачивание через Telegram.WebApp.downloadFile
- telegram.d.ts: типы openLink, openTelegramLink, downloadFile
This commit is contained in:
2026-09-27 12:16:51 +03:00
parent 00f734592c
commit f83028b105
3 changed files with 119 additions and 251 deletions
+5 -8
View File
@@ -1358,17 +1358,14 @@ export const getWrongBecause = (): Promise<{ items: WrongBecauseItem[] }> =>
export interface LectureListItem {
id: number;
title_pl: string;
title_ru: string;
title_uk: string;
title_en: string;
description_pl: string;
description_ru: string;
description_uk: string;
description_en: string;
level_code: string;
lecture_language: string;
title: string;
file_type: string;
file_size_kb: number;
file_url: string;
order_number: number;
created_at: string | null;
}
export interface LecturesListResponse {
+108 -243
View File
@@ -2,21 +2,21 @@ import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getLectures, getLecture, downloadLecture, type LectureListItem, type LectureDetail } from '../api';
import { getLectures, type LectureListItem } from '../api';
/**
* LecturesPage — список лекций по уровню пользователя.
* Открывает PDF/HTML в viewer, даёт скачать.
*
* Открытие: через Telegram.WebApp.openLink() — открывает PDF в браузере.
* Скачивание: через Telegram.WebApp.downloadFile() — скачивает файл.
*/
const LecturesPage: React.FC = () => {
const navigate = useNavigate();
const { t, language } = useLanguage();
const { t } = useLanguage();
const [lectures, setLectures] = useState<LectureListItem[]>([]);
const [level, setLevel] = useState('A1');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeLecture, setActiveLecture] = useState<LectureDetail | null>(null);
const [downloading, setDownloading] = useState(false);
const brandColor = '#2ECC71';
const lectureColor = '#4FA9E8';
@@ -46,183 +46,51 @@ const LecturesPage: React.FC = () => {
});
}, []);
const getTitle = (lecture: LectureListItem): string => {
const field = `title_${language}` as keyof LectureListItem;
return (lecture[field] as string) || lecture.title_en || lecture.title_pl || '';
const getFileUrl = (lecture: LectureListItem): string => {
return `https://api.filwordspl.com${lecture.file_url}`;
};
const getDescription = (lecture: LectureListItem): string => {
const field = `description_${language}` as keyof LectureListItem;
return (lecture[field] as string) || lecture.description_en || lecture.description_pl || '';
};
/**
* Открыть лекцию: в Telegram — через openLink (Safari/Chrome),
* в браузере — через window.open.
*/
const handleOpenLecture = (lecture: LectureListItem) => {
const url = getFileUrl(lecture);
const handleOpenLecture = async (lectureId: number) => {
try {
const detail = await getLecture(lectureId);
setActiveLecture(detail);
} catch (e) {
console.error('Failed to open lecture:', e);
alert(t('loadError') || 'Ошибка загрузки');
if (window.Telegram?.WebApp?.openLink) {
window.Telegram.WebApp.openLink(url);
} else {
window.open(url, '_blank');
}
};
const handleDownload = async () => {
if (!activeLecture || downloading) return;
setDownloading(true);
try {
const blob = await downloadLecture(activeLecture.id);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${activeLecture.title_pl || 'lecture'}.${activeLecture.file_type}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (e) {
console.error('Download failed:', e);
alert(t('loadError') || 'Ошибка скачивания');
} finally {
setDownloading(false);
/**
* Скачать лекцию: в Telegram — через downloadFile,
* в браузере — через скрытую ссылку.
*/
const handleDownloadLecture = (lecture: LectureListItem) => {
const url = getFileUrl(lecture);
// Telegram WebApp имеет свой метод downloadFile
if (window.Telegram?.WebApp?.downloadFile) {
window.Telegram.WebApp.downloadFile({
url,
file_name: `${lecture.title}.${lecture.file_type}`,
});
return;
}
// Fallback — обычное скачивание через ссылку
const a = document.createElement('a');
a.href = url;
a.download = `${lecture.title}.${lecture.file_type}`;
a.target = '_blank';
a.rel = 'noopener noreferrer';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
// ============ VIEWER ЛЕКЦИИ ============
if (activeLecture) {
return (
<div style={{
minHeight: '100vh',
background: '#F4F5F7',
color: textColor,
fontFamily: fonts.main,
display: 'flex',
flexDirection: 'column',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-120px', left: '-90px', width: '320px', height: '320px', borderRadius: '50%', background: lectureColor, opacity: 0.20, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1, padding: '16px' }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '10px',
marginBottom: '16px',
flexShrink: 0,
}}>
<button
onClick={() => setActiveLecture(null)}
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: textColor,
fontSize: '13px',
fontWeight: 600,
cursor: 'pointer',
}}
>
←
</button>
<h1 style={{
fontSize: '16px',
fontWeight: 800,
margin: 0,
color: textColor,
flex: 1,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}>
{activeLecture.title_pl}
</h1>
<button
onClick={handleDownload}
disabled={downloading}
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: lectureColor,
fontSize: '13px',
fontWeight: 700,
cursor: downloading ? 'default' : 'pointer',
opacity: downloading ? 0.6 : 1,
}}
>
{downloading ? '...' : '⬇'}
</button>
</div>
{/* Просмотр */}
<div style={{
flex: 1,
borderRadius: radius.lg,
background: 'rgba(255,255,255,0.85)',
border: '1px solid rgba(0,0,0,0.06)',
overflow: 'hidden',
boxShadow: '0 8px 32px rgba(31,38,73,0.10)',
minHeight: 0,
}}>
{activeLecture.file_type === 'pdf' ? (
<iframe
src={`https://api.filwordspl.com${activeLecture.file_url}`}
style={{
width: '100%',
height: '100%',
border: 'none',
}}
title={activeLecture.title_pl}
/>
) : activeLecture.file_type === 'html' ? (
<iframe
src={`https://api.filwordspl.com${activeLecture.file_url}`}
style={{
width: '100%',
height: '100%',
border: 'none',
}}
title={activeLecture.title_pl}
/>
) : (
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
padding: '40px',
textAlign: 'center',
}}>
<div style={{ fontSize: '64px', marginBottom: '16px' }}>📄</div>
<p style={{ fontSize: '16px', color: subColor, marginBottom: '20px' }}>
{t('lecturePreviewNotAvailable') || 'Просмотр недоступен для этого формата'}
</p>
<button
onClick={handleDownload}
disabled={downloading}
style={{
padding: '14px 28px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, ${lectureColor}, #3B82F6)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: downloading ? 'default' : 'pointer',
opacity: downloading ? 0.6 : 1,
}}
>
{downloading ? '...' : `⬇ ${t('download') || 'Скачать'}`}
</button>
</div>
)}
</div>
</div>
</div>
);
}
// ============ СПИСОК ЛЕКЦИЙ ============
return (
<div style={{
minHeight: '100vh',
@@ -235,43 +103,37 @@ const LecturesPage: React.FC = () => {
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-120px', left: '-90px', width: '320px', height: '320px', borderRadius: '50%', background: lectureColor, opacity: 0.20, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{
position: 'fixed', top: '-120px', left: '-90px',
width: '320px', height: '320px', borderRadius: '50%',
background: lectureColor, opacity: 0.20, filter: 'blur(90px)',
pointerEvents: 'none', zIndex: 0,
}} />
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '10px',
display: 'flex', alignItems: 'center', gap: '10px',
marginBottom: '24px',
}}>
<button
onClick={() => navigate('/learning')}
style={{
...glass({ padding: '10px 14px', borderRadius: radius.md }),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer',
}}
>
←
</button>
<h1 style={{
fontSize: '22px',
fontWeight: 800,
margin: 0,
color: textColor,
flex: 1,
fontSize: '22px', fontWeight: 800, margin: 0, color: textColor, flex: 1,
}}>
📄 {t('lectures') || 'Лекции'}
</h1>
<span style={{
...glass({ padding: '6px 12px', borderRadius: radius.sm }),
fontSize: '14px',
fontWeight: 800,
color: brandColor,
fontSize: '14px', fontWeight: 800, color: brandColor,
}}>
{level}
</span>
@@ -288,10 +150,7 @@ const LecturesPage: React.FC = () => {
</div>
) : lectures.length === 0 ? (
<div style={{
textAlign: 'center',
padding: '60px 20px',
color: subColor,
animation: 'fadeIn 0.3s ease',
textAlign: 'center', padding: '60px 20px', color: subColor,
}}>
<div style={{ fontSize: '64px', marginBottom: '16px' }}>📭</div>
<p style={{ fontSize: '16px', marginBottom: '8px', fontWeight: 600 }}>
@@ -303,14 +162,11 @@ const LecturesPage: React.FC = () => {
</div>
) : (
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
display: 'flex', flexDirection: 'column', gap: '12px',
}}>
{lectures.map((lecture) => (
<button
<div
key={lecture.id}
onClick={() => handleOpenLecture(lecture.id)}
style={{
padding: '18px 20px',
borderRadius: radius.lg,
@@ -319,62 +175,71 @@ const LecturesPage: React.FC = () => {
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
boxShadow: '0 6px 20px rgba(31,38,73,0.08), inset 0 1px 0 rgba(255,255,255,0.85)',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '16px',
textAlign: 'left',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<div style={{
fontSize: '32px',
flexShrink: 0,
}}>
{lecture.file_type === 'pdf' ? '📕' : lecture.file_type === 'html' ? '🌐' : '📄'}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: '16px',
fontWeight: 700,
color: textColor,
marginBottom: '4px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}>
{getTitle(lecture)}
{/* Клик по иконке/названию — открыть */}
<button
onClick={() => handleOpenLecture(lecture)}
style={{
flex: 1,
display: 'flex',
alignItems: 'center',
gap: '16px',
border: 'none',
background: 'transparent',
cursor: 'pointer',
textAlign: 'left',
padding: 0,
fontFamily: fonts.main,
}}
>
<div style={{ fontSize: '32px', flexShrink: 0 }}>
{lecture.file_type === 'pdf' ? '📕' : lecture.file_type === 'html' ? '🌐' : '📄'}
</div>
{getDescription(lecture) && (
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: '13px',
color: subColor,
fontSize: '16px', fontWeight: 700, color: textColor,
marginBottom: '4px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{getDescription(lecture)}
{lecture.title}
</div>
<div style={{
fontSize: '11px', color: subColor, opacity: 0.7,
}}>
{lecture.file_type.toUpperCase()} · {lecture.file_size_kb} KB
</div>
)}
<div style={{
fontSize: '11px',
color: subColor,
opacity: 0.7,
}}>
{lecture.file_type.toUpperCase()} · {lecture.file_size_kb} KB
</div>
</div>
<div style={{
fontSize: '20px',
color: lectureColor,
flexShrink: 0,
}}>
→
</div>
</button>
</button>
{/* Кнопка скачать */}
<button
onClick={() => handleDownloadLecture(lecture)}
style={{
width: '44px',
height: '44px',
borderRadius: radius.md,
border: `1px solid ${brandColor}30`,
background: `${brandColor}15`,
color: brandColor,
fontSize: '18px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
title={t('download') || 'Скачать'}
>
⬇
</button>
</div>
))}
</div>
)}
+6
View File
@@ -15,6 +15,12 @@ declare global {
expand: () => void;
close: () => void;
disableVerticalSwipes: () => void;
// 🔧 НОВОЕ (27.09.2026): для открытия и скачивания лекций
openLink: (url: string, options?: { try_instant_view?: boolean }) => void;
openTelegramLink: (url: string) => void;
downloadFile: (params: { url: string; file_name: string }) => void;
MainButton: {
setText: (text: string) => void;
show: () => void;