📄 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 { export interface LectureListItem {
id: number; id: number;
title_pl: string; level_code: string;
title_ru: string; lecture_language: string;
title_uk: string; title: string;
title_en: string;
description_pl: string;
description_ru: string;
description_uk: string;
description_en: string;
file_type: string; file_type: string;
file_size_kb: number; file_size_kb: number;
file_url: string;
order_number: number; order_number: number;
created_at: string | null;
} }
export interface LecturesListResponse { export interface LecturesListResponse {
+108 -243
View File
@@ -2,21 +2,21 @@ import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext'; import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme'; import { fonts, radius } from '../styles/theme';
import { getLectures, getLecture, downloadLecture, type LectureListItem, type LectureDetail } from '../api'; import { getLectures, type LectureListItem } from '../api';
/** /**
* LecturesPage — список лекций по уровню пользователя. * LecturesPage — список лекций по уровню пользователя.
* Открывает PDF/HTML в viewer, даёт скачать. *
* Открытие: через Telegram.WebApp.openLink() — открывает PDF в браузере.
* Скачивание: через Telegram.WebApp.downloadFile() — скачивает файл.
*/ */
const LecturesPage: React.FC = () => { const LecturesPage: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { t, language } = useLanguage(); const { t } = useLanguage();
const [lectures, setLectures] = useState<LectureListItem[]>([]); const [lectures, setLectures] = useState<LectureListItem[]>([]);
const [level, setLevel] = useState('A1'); const [level, setLevel] = useState('A1');
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [activeLecture, setActiveLecture] = useState<LectureDetail | null>(null);
const [downloading, setDownloading] = useState(false);
const brandColor = '#2ECC71'; const brandColor = '#2ECC71';
const lectureColor = '#4FA9E8'; const lectureColor = '#4FA9E8';
@@ -46,183 +46,51 @@ const LecturesPage: React.FC = () => {
}); });
}, []); }, []);
const getTitle = (lecture: LectureListItem): string => { const getFileUrl = (lecture: LectureListItem): string => {
const field = `title_${language}` as keyof LectureListItem; return `https://api.filwordspl.com${lecture.file_url}`;
return (lecture[field] as string) || lecture.title_en || lecture.title_pl || '';
}; };
const getDescription = (lecture: LectureListItem): string => { /**
const field = `description_${language}` as keyof LectureListItem; * Открыть лекцию: в Telegram — через openLink (Safari/Chrome),
return (lecture[field] as string) || lecture.description_en || lecture.description_pl || ''; * в браузере — через window.open.
}; */
const handleOpenLecture = (lecture: LectureListItem) => {
const url = getFileUrl(lecture);
const handleOpenLecture = async (lectureId: number) => { if (window.Telegram?.WebApp?.openLink) {
try { window.Telegram.WebApp.openLink(url);
const detail = await getLecture(lectureId); } else {
setActiveLecture(detail); window.open(url, '_blank');
} catch (e) {
console.error('Failed to open lecture:', e);
alert(t('loadError') || 'Ошибка загрузки');
} }
}; };
const handleDownload = async () => { /**
if (!activeLecture || downloading) return; * Скачать лекцию: в Telegram — через downloadFile,
setDownloading(true); * в браузере — через скрытую ссылку.
try { */
const blob = await downloadLecture(activeLecture.id); const handleDownloadLecture = (lecture: LectureListItem) => {
const url = URL.createObjectURL(blob); const url = getFileUrl(lecture);
const a = document.createElement('a');
a.href = url; // Telegram WebApp имеет свой метод downloadFile
a.download = `${activeLecture.title_pl || 'lecture'}.${activeLecture.file_type}`; if (window.Telegram?.WebApp?.downloadFile) {
document.body.appendChild(a); window.Telegram.WebApp.downloadFile({
a.click(); url,
document.body.removeChild(a); file_name: `${lecture.title}.${lecture.file_type}`,
URL.revokeObjectURL(url); });
} catch (e) { return;
console.error('Download failed:', e);
alert(t('loadError') || 'Ошибка скачивания');
} finally {
setDownloading(false);
} }
// 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 ( return (
<div style={{ <div style={{
minHeight: '100vh', minHeight: '100vh',
@@ -235,43 +103,37 @@ const LecturesPage: React.FC = () => {
position: 'relative', position: 'relative',
overflow: 'hidden', 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={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */} {/* Заголовок */}
<div style={{ <div style={{
display: 'flex', display: 'flex', alignItems: 'center', gap: '10px',
alignItems: 'center',
gap: '10px',
marginBottom: '24px', marginBottom: '24px',
}}> }}>
<button <button
onClick={() => navigate('/learning')} onClick={() => navigate('/learning')}
style={{ style={{
...glass({ padding: '10px 14px', borderRadius: radius.md }), ...glass({ padding: '10px 14px', borderRadius: radius.md }),
color: textColor, color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer',
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
}} }}
> >
← ←
</button> </button>
<h1 style={{ <h1 style={{
fontSize: '22px', fontSize: '22px', fontWeight: 800, margin: 0, color: textColor, flex: 1,
fontWeight: 800,
margin: 0,
color: textColor,
flex: 1,
}}> }}>
📄 {t('lectures') || 'Лекции'} 📄 {t('lectures') || 'Лекции'}
</h1> </h1>
<span style={{ <span style={{
...glass({ padding: '6px 12px', borderRadius: radius.sm }), ...glass({ padding: '6px 12px', borderRadius: radius.sm }),
fontSize: '14px', fontSize: '14px', fontWeight: 800, color: brandColor,
fontWeight: 800,
color: brandColor,
}}> }}>
{level} {level}
</span> </span>
@@ -288,10 +150,7 @@ const LecturesPage: React.FC = () => {
</div> </div>
) : lectures.length === 0 ? ( ) : lectures.length === 0 ? (
<div style={{ <div style={{
textAlign: 'center', textAlign: 'center', padding: '60px 20px', color: subColor,
padding: '60px 20px',
color: subColor,
animation: 'fadeIn 0.3s ease',
}}> }}>
<div style={{ fontSize: '64px', marginBottom: '16px' }}>📭</div> <div style={{ fontSize: '64px', marginBottom: '16px' }}>📭</div>
<p style={{ fontSize: '16px', marginBottom: '8px', fontWeight: 600 }}> <p style={{ fontSize: '16px', marginBottom: '8px', fontWeight: 600 }}>
@@ -303,14 +162,11 @@ const LecturesPage: React.FC = () => {
</div> </div>
) : ( ) : (
<div style={{ <div style={{
display: 'flex', display: 'flex', flexDirection: 'column', gap: '12px',
flexDirection: 'column',
gap: '12px',
}}> }}>
{lectures.map((lecture) => ( {lectures.map((lecture) => (
<button <div
key={lecture.id} key={lecture.id}
onClick={() => handleOpenLecture(lecture.id)}
style={{ style={{
padding: '18px 20px', padding: '18px 20px',
borderRadius: radius.lg, borderRadius: radius.lg,
@@ -319,62 +175,71 @@ const LecturesPage: React.FC = () => {
backdropFilter: 'blur(24px) saturate(180%)', backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: '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)', boxShadow: '0 6px 20px rgba(31,38,73,0.08), inset 0 1px 0 rgba(255,255,255,0.85)',
cursor: 'pointer',
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
gap: '16px', 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', <button
flexShrink: 0, onClick={() => handleOpenLecture(lecture)}
}}> style={{
{lecture.file_type === 'pdf' ? '📕' : lecture.file_type === 'html' ? '🌐' : '📄'} flex: 1,
</div> display: 'flex',
<div style={{ flex: 1, minWidth: 0 }}> alignItems: 'center',
<div style={{ gap: '16px',
fontSize: '16px', border: 'none',
fontWeight: 700, background: 'transparent',
color: textColor, cursor: 'pointer',
marginBottom: '4px', textAlign: 'left',
overflow: 'hidden', padding: 0,
textOverflow: 'ellipsis', fontFamily: fonts.main,
whiteSpace: 'nowrap', }}
}}> >
{getTitle(lecture)} <div style={{ fontSize: '32px', flexShrink: 0 }}>
{lecture.file_type === 'pdf' ? '📕' : lecture.file_type === 'html' ? '🌐' : '📄'}
</div> </div>
{getDescription(lecture) && ( <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ <div style={{
fontSize: '13px', fontSize: '16px', fontWeight: 700, color: textColor,
color: subColor,
marginBottom: '4px', marginBottom: '4px',
overflow: 'hidden', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
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>
)}
<div style={{
fontSize: '11px',
color: subColor,
opacity: 0.7,
}}>
{lecture.file_type.toUpperCase()} · {lecture.file_size_kb} KB
</div> </div>
</div> </button>
<div style={{
fontSize: '20px', {/* Кнопка скачать */}
color: lectureColor, <button
flexShrink: 0, onClick={() => handleDownloadLecture(lecture)}
}}> style={{
→ width: '44px',
</div> height: '44px',
</button> 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> </div>
)} )}
+6
View File
@@ -15,6 +15,12 @@ declare global {
expand: () => void; expand: () => void;
close: () => void; close: () => void;
disableVerticalSwipes: () => 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: { MainButton: {
setText: (text: string) => void; setText: (text: string) => void;
show: () => void; show: () => void;