新增赋能中心一楼设备教程:上传、搜索与在线播放
This commit is contained in:
Vendored
+11
@@ -718,4 +718,15 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
|
||||
.center-history { margin-top:28px; }
|
||||
.center-history summary { cursor:pointer; padding:12px 0; }
|
||||
.center-history .acard { margin-top:12px; }
|
||||
/* ---------- 设备使用教程 ---------- */
|
||||
.tutorial-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:16px; align-items:start; }
|
||||
.tutorial-card { display:flex; flex-direction:column; gap:10px; padding:14px; background:var(--card); border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); }
|
||||
.tutorial-head { display:flex; align-items:center; gap:8px; flex-wrap:wrap; min-width:0; }
|
||||
.tutorial-head b { font-size:15px; font-weight:600; overflow-wrap:anywhere; }
|
||||
.tutorial-head .tag { max-width:100%; overflow-wrap:anywhere; white-space:normal; }
|
||||
.tutorial-video { display:block; width:100%; aspect-ratio:16/9; background:#101613; border-radius:10px; }
|
||||
.tutorial-note { margin:0; font-size:13px; line-height:1.65; white-space:pre-wrap; overflow-wrap:anywhere; }
|
||||
.tutorial-meta { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; margin-top:auto; }
|
||||
.tutorial-meta .muted { min-width:0; overflow-wrap:anywhere; }
|
||||
@media (max-width:760px) { .tutorial-grid { grid-template-columns:1fr; } }
|
||||
@media (min-width:761px) and (max-width:1000px) { .topbar-inner { flex-wrap:wrap; } #nav { order:3; flex-basis:100%; } }
|
||||
|
||||
Vendored
+12
-4
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WorkLog · 活动记录</title>
|
||||
<meta name="theme-color" content="#f5f7f5" />
|
||||
<link rel="stylesheet" href="/assets/styles.css?v=28" />
|
||||
<link rel="stylesheet" href="/assets/styles.css?v=29" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
@@ -132,7 +132,7 @@
|
||||
</div>
|
||||
<section class="center-shortcuts" aria-label="赋能中心一楼快捷入口">
|
||||
<div><strong>赋能中心一楼</strong><p>上传活动照片,完成每日清点,申请物品借用</p></div>
|
||||
<div class="center-shortcut-actions"><a class="btn primary" href="#center-records">一楼活动记录</a><a class="btn" href="#center-duty">一楼值班</a><a class="btn" href="#center-assets">物品清点与借出</a><a class="btn" href="#timetables">课表收取</a></div>
|
||||
<div class="center-shortcut-actions"><a class="btn primary" href="#center-records">一楼活动记录</a><a class="btn" href="#center-tutorials">设备教程</a><a class="btn" href="#center-duty">一楼值班</a><a class="btn" href="#center-assets">物品清点与借出</a><a class="btn" href="#timetables">课表收取</a></div>
|
||||
</section>
|
||||
<div class="filters">
|
||||
<input id="feed-q" aria-label="搜索活动或地点" placeholder="搜索活动 / 地点" type="search" />
|
||||
@@ -175,11 +175,19 @@
|
||||
<p class="muted" id="center-export-status" role="status"></p>
|
||||
<p class="muted">程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。</p>
|
||||
</details>
|
||||
<div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="duty">一楼值班</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button></div>
|
||||
<div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="tutorials">设备教程</button><button class="tab" data-center-tab="duty">一楼值班</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button></div>
|
||||
<section id="center-records">
|
||||
<div class="filters center-toolbar"><input id="center-q" type="search" aria-label="搜索活动主题" placeholder="搜索活动主题" /><input id="center-from" type="date" aria-label="活动起始日期" /><input id="center-to" type="date" aria-label="活动截止日期" /><button id="center-new" class="btn primary">+ 记录一楼活动</button></div>
|
||||
<div id="center-record-list" class="card-list"></div>
|
||||
</section>
|
||||
<section id="center-tutorials" class="hidden">
|
||||
<div class="filters center-toolbar"><input id="tutorial-q" type="search" aria-label="搜索教室号、器材名或备注" placeholder="搜索教室号 / 器材名 / 备注" /><button id="tutorial-new" class="btn primary" type="button">+ 上传教程</button></div>
|
||||
<p class="muted">教程视频仅登录成员可在线播放;原始视频只有上传者可以下载保存,其他人可在线观看。</p>
|
||||
<div id="tutorial-list" class="tutorial-grid"></div>
|
||||
<div id="tutorial-empty" class="empty hidden">还没有教程,点「+ 上传教程」添加第一份。</div>
|
||||
<div class="form-actions"><button id="tutorial-more" class="btn hidden" type="button">加载更多</button></div>
|
||||
<p class="muted" id="tutorial-status" role="status"></p>
|
||||
</section>
|
||||
<section id="center-duty" class="hidden">
|
||||
<div class="center-duty-head">
|
||||
<div>
|
||||
@@ -358,7 +366,7 @@
|
||||
|
||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||
|
||||
<script src="/js/app.js?v=48"></script>
|
||||
<script src="/js/app.js?v=49"></script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Vendored
+178
-2
@@ -1535,10 +1535,11 @@
|
||||
let centerRecords = [];
|
||||
function openCenterFromHash() {
|
||||
if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
|
||||
if (!state.me || !['#center', '#center-records', '#center-duty', '#center-assets', '#center-hall'].includes(location.hash)) return false;
|
||||
centerTab = location.hash === '#center-duty' ? 'duty' : location.hash === '#center-assets' ? 'assets' : location.hash === '#center-hall' ? 'hall' : 'records';
|
||||
if (!state.me || !['#center', '#center-records', '#center-tutorials', '#center-duty', '#center-assets', '#center-hall'].includes(location.hash)) return false;
|
||||
centerTab = location.hash === '#center-tutorials' ? 'tutorials' : location.hash === '#center-duty' ? 'duty' : location.hash === '#center-assets' ? 'assets' : location.hash === '#center-hall' ? 'hall' : 'records';
|
||||
$$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab));
|
||||
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
||||
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
|
||||
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
|
||||
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
||||
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
|
||||
@@ -1560,6 +1561,8 @@
|
||||
const data = await api(`/activities?${p}`); centerRecords = data.items;
|
||||
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录工作时请上传照片。</div>';
|
||||
bindCardEvents($('#center-record-list'));
|
||||
} else if (centerTab === 'tutorials') {
|
||||
await loadTutorials();
|
||||
} else if (centerTab === 'duty') {
|
||||
await loadCenterDuty();
|
||||
} else if (centerTab === 'hall') {
|
||||
@@ -1612,6 +1615,7 @@
|
||||
history.replaceState(null, '', '#center-' + centerTab);
|
||||
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b === button));
|
||||
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
||||
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
|
||||
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
|
||||
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
||||
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
|
||||
@@ -1634,6 +1638,178 @@
|
||||
<label>${isDuty ? '值班人及联系方式' : '使用单位联系人及联系方式'}<input name="duty" maxlength="200" value="${esc(current && current !== '—' ? current : '')}" placeholder="例如:张三 13800000000" /></label>`,
|
||||
async f => { await api('/center/hall-log/duty', { method: 'POST', body: { row, column, value: f.duty.value.trim() } }); toast('已保存并同步到金山文档'); });
|
||||
});
|
||||
|
||||
// ---- 设备使用教程
|
||||
const TUTORIAL_PAGE = 60;
|
||||
const tutorialState = { items: [], q: '', hasMore: false, seq: 0 };
|
||||
let tutorialDebounce = null, tutorialProgressHandler = null;
|
||||
const fmtBytes = (bytes) => {
|
||||
if (!bytes) return '';
|
||||
if (bytes >= 1024 ** 3) return (bytes / 1024 ** 3).toFixed(1) + ' GB';
|
||||
if (bytes >= 1024 ** 2) return Math.round(bytes / 1024 ** 2) + ' MB';
|
||||
return Math.max(1, Math.round(bytes / 1024)) + ' KB';
|
||||
};
|
||||
function tutorialCard(item, index) {
|
||||
const canDownload = item.uploader_id === state.me?.id;
|
||||
const src = `/api/center/tutorials/${encodeURIComponent(item.id)}`;
|
||||
return `<article class="tutorial-card" data-tutorial="${esc(item.id)}">
|
||||
<div class="tutorial-head"><b>${esc(item.room)}</b><span class="tag cat">${esc(item.equipment)}</span></div>
|
||||
<video class="tutorial-video" controls preload="none" playsinline data-index="${index}" data-loaded="0"><source data-index="${index}" /></video>
|
||||
${item.note ? `<p class="tutorial-note">${esc(item.note)}</p>` : '<p class="tutorial-note muted">暂无备注</p>'}
|
||||
<div class="tutorial-meta"><span class="muted">${esc(item.uploader)} · ${fmtDate(item.created_at)}${item.video_bytes ? ` · ${fmtBytes(item.video_bytes)}` : ''}</span>${canDownload ? `<button class="btn sm" type="button" data-tutorial-download="${esc(item.id)}">下载原视频</button>` : ''}</div>
|
||||
</article>`;
|
||||
}
|
||||
function paintTutorials() {
|
||||
const list = $('#tutorial-list');
|
||||
list.innerHTML = tutorialState.items.map(tutorialCard).join('');
|
||||
$('#tutorial-empty').classList.toggle('hidden', !!tutorialState.items.length || !!tutorialState.q);
|
||||
$('#tutorial-more').classList.toggle('hidden', !tutorialState.hasMore);
|
||||
$('#tutorial-empty').textContent = tutorialState.q ? '没有匹配的教程,换个教室号或器材名试试。' : '还没有教程,点「+ 上传教程」添加第一份。';
|
||||
}
|
||||
function playTutorial(index) {
|
||||
const card = $('#tutorial-list article:nth-child(' + (index + 1) + ')');
|
||||
const video = card?.querySelector('video');
|
||||
const item = tutorialState.items[index];
|
||||
if (!video || !item) return;
|
||||
const source = video.querySelector('source');
|
||||
if (video.dataset.loaded === '0') {
|
||||
const ext = (item.video_file || '').split('.').pop();
|
||||
source.type = { mp4: 'video/mp4', mov: 'video/quicktime', webm: 'video/webm' }[ext] || 'video/mp4';
|
||||
source.src = `/api/center/tutorials/${encodeURIComponent(item.id)}`;
|
||||
video.dataset.loaded = '1';
|
||||
video.load();
|
||||
}
|
||||
video.play().catch(() => {});
|
||||
}
|
||||
async function loadTutorials({ fresh = false } = {}) {
|
||||
const seq = ++tutorialState.seq;
|
||||
tutorialState.freshMode = fresh;
|
||||
const p = new URLSearchParams({ limit: TUTORIAL_PAGE });
|
||||
if (tutorialState.q) p.set('q', tutorialState.q);
|
||||
const append = !fresh && $('#tutorial-more').dataset.mode === 'append';
|
||||
$('#tutorial-more').dataset.mode = '';
|
||||
if (append && tutorialState.items.length) p.set('offset', String(tutorialState.items.length));
|
||||
$('#tutorial-status').textContent = tutorialState.items.length ? '正在加载更多…' : '正在读取教程…';
|
||||
try {
|
||||
const data = await api(`/center/tutorials?${p}`);
|
||||
if (seq !== tutorialState.seq) return;
|
||||
tutorialState.items = append ? tutorialState.items.concat(data.items) : data.items;
|
||||
tutorialState.hasMore = data.has_more;
|
||||
paintTutorials();
|
||||
$('#tutorial-status').textContent = tutorialState.q
|
||||
? `搜索「${tutorialState.q}」共 ${tutorialState.items.length} 条${data.has_more ? '(可加载更多)' : ''}`
|
||||
: `共 ${tutorialState.items.length} 条教程${data.has_more ? ',还有更多' : ''}`;
|
||||
} catch (error) {
|
||||
$('#tutorial-status').textContent = '';
|
||||
toast(error.message, true);
|
||||
} finally {
|
||||
if (seq === tutorialState.seq) tutorialState.freshMode = false;
|
||||
}
|
||||
}
|
||||
function searchTutorials() {
|
||||
clearTimeout(tutorialDebounce);
|
||||
tutorialDebounce = setTimeout(() => {
|
||||
tutorialState.q = $('#tutorial-q').value.trim();
|
||||
tutorialState.items = [];
|
||||
loadTutorials({ fresh: true });
|
||||
}, 250);
|
||||
}
|
||||
function openTutorialForm() {
|
||||
modal(`<h3>上传设备使用教程</h3>
|
||||
<form id="tutorial-form" novalidate>
|
||||
<label>教室号 *<input name="room" required maxlength="40" placeholder="例如:赋能中心一楼 A101" /></label>
|
||||
<label>器材名 *<input name="equipment" required maxlength="100" placeholder="例如:激光切割机、投影仪" /></label>
|
||||
<label>教程视频 * <span class="hint-inline">(MP4 / MOV / WebM,单个不超过 1GB)</span><input name="video" type="file" accept="video/mp4,video/quicktime,video/webm,.mp4,.mov,.webm" required /></label>
|
||||
<label>备注 <span class="hint-inline">(选填)</span><textarea name="note" rows="3" maxlength="2000" placeholder="开机步骤、注意事项、常见问题…"></textarea></label>
|
||||
<div class="upload-progress hidden" id="tutorial-progress"><p id="tutorial-progress-label" role="status" aria-live="polite"></p><progress id="tutorial-meter" max="100" value="0" aria-labelledby="tutorial-progress-label"></progress></div>
|
||||
<div class="form-error" id="tutorial-error" role="alert"></div>
|
||||
<div class="form-actions"><button type="button" class="btn" id="tutorial-cancel">取消</button><button type="submit" class="btn primary">上传并保存</button><button type="button" class="btn hidden" id="tutorial-abort">取消上传</button></div>
|
||||
</form>`);
|
||||
const form = $('#tutorial-form'), errorBox = $('#tutorial-error');
|
||||
const box = $('#tutorial-progress'), label = $('#tutorial-progress-label'), meter = $('#tutorial-meter');
|
||||
const button = form.querySelector('[type=submit]'), abortButton = $('#tutorial-abort');
|
||||
let submitted = false;
|
||||
$('#tutorial-cancel').addEventListener('click', () => { if (!submitted || !materialUpload) closeModal(); else abortButton.click(); });
|
||||
abortButton.addEventListener('click', () => materialUpload?.abort());
|
||||
form.video.addEventListener('change', () => {
|
||||
const size = form.video.files[0]?.size || 0;
|
||||
errorBox.textContent = size > 1024 ** 3 ? '视频超过 1GB,请先压缩再上传' : '';
|
||||
});
|
||||
const showProgress = (loaded, total) => {
|
||||
box.classList.remove('hidden');
|
||||
const pct = total ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
|
||||
meter.value = pct;
|
||||
label.textContent = pct >= 100 ? `视频已上传,正在保存…(${fmtBytes(loaded)})` : `正在上传视频 ${pct}%(${fmtBytes(loaded)} / ${fmtBytes(total)})`;
|
||||
};
|
||||
tutorialProgressHandler = showProgress;
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (button.disabled) return;
|
||||
errorBox.textContent = '';
|
||||
if (!form.reportValidity()) return;
|
||||
const room = form.room.value.trim(), equipment = form.equipment.value.trim();
|
||||
const file = form.video.files[0], note = form.note.value.trim();
|
||||
if (!file) { errorBox.textContent = '请选择教程视频'; return; }
|
||||
if (file.size > 1024 ** 3) { errorBox.textContent = '视频超过 1GB,请先压缩再上传'; return; }
|
||||
submitted = true;
|
||||
button.disabled = true; form.room.disabled = form.equipment.disabled = form.video.disabled = form.note.disabled = true;
|
||||
abortButton.classList.remove('hidden');
|
||||
button.textContent = '正在上传…';
|
||||
const params = new URLSearchParams({ room, equipment, note });
|
||||
const ext = (file.name.split('.').pop() || '').toLowerCase();
|
||||
const type = file.type || ({ mp4: 'video/mp4', mov: 'video/quicktime', m4v: 'video/mp4', webm: 'video/webm' })[ext] || 'application/octet-stream';
|
||||
try {
|
||||
await uploadFile(`/api/center/tutorials?${params}`, 'POST', file, showProgress, type);
|
||||
closeModal();
|
||||
toast('教程已上传');
|
||||
if (centerTab !== 'tutorials') { centerTab = 'tutorials'; history.replaceState(null, '', '#center-tutorials'); }
|
||||
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b.dataset.centerTab === 'tutorials'));
|
||||
$('#center-records').classList.add('hidden'); $('#center-tutorials').classList.remove('hidden');
|
||||
$('#center-duty').classList.add('hidden'); $('#center-assets').classList.add('hidden'); $('#center-hall').classList.add('hidden');
|
||||
tutorialState.items = []; tutorialState.q = ''; $('#tutorial-q').value = '';
|
||||
await loadTutorials({ fresh: true });
|
||||
} catch (error) {
|
||||
submitted = false;
|
||||
errorBox.textContent = error.message;
|
||||
label.textContent = '上传未完成,可以直接重试。';
|
||||
abortButton.classList.add('hidden');
|
||||
button.disabled = false; button.textContent = '重新上传';
|
||||
form.room.disabled = form.equipment.disabled = form.video.disabled = form.note.disabled = false;
|
||||
if (!form.isConnected) { tutorialProgressHandler = null; return; }
|
||||
}
|
||||
tutorialProgressHandler = null;
|
||||
});
|
||||
}
|
||||
$('#tutorial-new').addEventListener('click', openTutorialForm);
|
||||
$('#tutorial-q').addEventListener('input', searchTutorials);
|
||||
$('#tutorial-more').addEventListener('click', async () => {
|
||||
if (tutorialState.freshMode) return;
|
||||
$('#tutorial-more').dataset.mode = 'append';
|
||||
await loadTutorials();
|
||||
});
|
||||
$('#tutorial-list').addEventListener('pointerenter', event => {
|
||||
const video = event.target.closest('.tutorial-video');
|
||||
if (video && !tutorialState.freshMode) playTutorial(Number(video.dataset.index));
|
||||
}, true);
|
||||
$('#tutorial-list').addEventListener('focusin', event => {
|
||||
});
|
||||
$('#tutorial-list').addEventListener('click', async event => {
|
||||
const button = event.target.closest('[data-tutorial-download]');
|
||||
if (button) {
|
||||
const item = tutorialState.items.find(t => t.id === button.dataset.tutorialDownload);
|
||||
button.disabled = true;
|
||||
try {
|
||||
const ext = (item?.video_file || '').split('.').pop() || 'mp4';
|
||||
await downloadCenterFile(`/api/center/tutorials/${encodeURIComponent(button.dataset.tutorialDownload)}?preview=1`,
|
||||
`${item?.room || '教程'}-${item?.equipment || ''}.${ext}`.replace(/[\\/:*?"<>|]/g, '_'));
|
||||
} catch (error) { toast(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
return;
|
||||
}
|
||||
const video = event.target.closest('.tutorial-video');
|
||||
if (video) playTutorial(Number(video.dataset.index));
|
||||
});
|
||||
|
||||
function openLoanForm() {
|
||||
centerForm('登记借出',
|
||||
`<p class="muted">这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。</p>
|
||||
|
||||
+101
-1
@@ -1,5 +1,6 @@
|
||||
"""赋能中心一楼:照片、物品、每日清点、借还登记、展厅登记和值班入口。"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
@@ -17,9 +18,10 @@ from PIL.Image import DecompressionBombError
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy import select, insert, update, delete, func, text, or_
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_items, center_loans, center_checks, activities, users
|
||||
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_items, center_loans, center_checks, center_tutorials, activities, users
|
||||
from .duty import BEIJING
|
||||
from .security import now_ms, PHONE_PATTERN
|
||||
from .spa_static import range_safe_file
|
||||
|
||||
|
||||
def required_text(value: str, message: str) -> str:
|
||||
@@ -95,6 +97,22 @@ MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
||||
MAX_ZIP_BYTES = 100 * 1024 * 1024
|
||||
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
|
||||
MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024
|
||||
# 设备教程视频:单段上传上限与格式白名单
|
||||
MAX_TUTORIAL_BYTES = 1024 * 1024 * 1024
|
||||
TUTORIAL_VIDEO_TYPES = {
|
||||
'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov',
|
||||
'application/mp4': 'mp4', 'application/octet-stream': None,
|
||||
}
|
||||
TUTORIAL_PLAYLESS_TYPES = {'video/mp4', 'video/webm', 'video/quicktime', 'application/mp4'}
|
||||
|
||||
|
||||
def detect_video_ext(head: bytes) -> str | None:
|
||||
"""按文件头判断视频格式,避免仅凭浏览器声明的类型落盘错误后缀。"""
|
||||
if len(head) >= 12 and head[4:8] == b'ftyp':
|
||||
return 'mov' if head[8:12] in (b'qt ',) else 'mp4'
|
||||
if head[:4] == b'\x1aE\xdf\xa3':
|
||||
return 'webm'
|
||||
return None
|
||||
DAILY_PHOTO_LIMIT = 1000
|
||||
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
@@ -355,6 +373,88 @@ def install(app, get_db, current_user, photo_root, visible_clause):
|
||||
if not path.is_file(): raise HTTPException(404, '照片文件不存在')
|
||||
return FileResponse(path, media_type='image/jpeg')
|
||||
|
||||
# ---------------------------------------------------------------- 设备使用教程
|
||||
@app.get('/api/center/tutorials')
|
||||
async def list_tutorials(q: str = '', offset: int = 0, limit: int = 60, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
keyword = q.strip()
|
||||
if keyword and len(keyword) > 100: raise HTTPException(422, '搜索关键词最多100字')
|
||||
offset, limit = max(0, offset), min(100, max(1, limit))
|
||||
stmt = select(center_tutorials.c.id, center_tutorials.c.room, center_tutorials.c.equipment,
|
||||
center_tutorials.c.note, center_tutorials.c.created_at, center_tutorials.c.uploader_id,
|
||||
center_tutorials.c.video_file, center_tutorials.c.video_bytes,
|
||||
users.c.display_name.label('uploader_name')).select_from(center_tutorials).outerjoin(users, users.c.id == center_tutorials.c.uploader_id)
|
||||
for word in keyword.split():
|
||||
like = '%' + word + '%'
|
||||
stmt = stmt.where(or_(center_tutorials.c.room.like(like), center_tutorials.c.equipment.like(like), center_tutorials.c.note.like(like)))
|
||||
rows = (await db.execute(stmt.order_by(center_tutorials.c.created_at.desc(), center_tutorials.c.id)
|
||||
.offset(offset).limit(limit + 1))).mappings().all()
|
||||
items = []
|
||||
for r in rows[:limit]:
|
||||
item = dict(r)
|
||||
item['uploader'] = item.pop('uploader_name') or '未命名成员'
|
||||
items.append(item)
|
||||
return {'items': items, 'has_more': len(rows) > limit}
|
||||
|
||||
@app.post('/api/center/tutorials')
|
||||
async def upload_tutorial(request: Request, room: str = '', equipment: str = '', note: str = '',
|
||||
db=Depends(get_db), viewer=Depends(current_user)):
|
||||
room, equipment, note = room.strip(), equipment.strip(), note.strip()
|
||||
if not room or len(room) > 40: raise HTTPException(422, '请填写教室号(40字以内)')
|
||||
if not equipment or len(equipment) > 100: raise HTTPException(422, '请填写器材名(100字以内)')
|
||||
if len(note) > 2000: raise HTTPException(422, '备注最多2000字')
|
||||
content_type = (request.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if content_type not in TUTORIAL_VIDEO_TYPES: raise HTTPException(422, '教程视频仅支持 MP4、MOV 或 WebM')
|
||||
received = 0
|
||||
head = b''
|
||||
path = None
|
||||
photo_root().mkdir(parents=True, exist_ok=True)
|
||||
staging_name = photo_root() / ('tutorial-' + uuid.uuid4().hex + '.part')
|
||||
staging = os.fdopen(os.open(staging_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 'wb', buffering=1024 * 1024)
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
if not head: head = chunk[:16]
|
||||
received += len(chunk)
|
||||
if received > MAX_TUTORIAL_BYTES: raise HTTPException(413, f'教程视频最大{MAX_TUTORIAL_BYTES // 1024 // 1024 // 1024}GB')
|
||||
await asyncio.to_thread(staging.write, chunk)
|
||||
staging.flush(); await asyncio.to_thread(os.fsync, staging.fileno())
|
||||
staging.close()
|
||||
if received <= 12: raise HTTPException(422, '教程视频为空,请重新选择')
|
||||
ext = detect_video_ext(head)
|
||||
if not ext: raise HTTPException(422, '无法识别视频格式,请上传 MP4、MOV 或 WebM')
|
||||
key = uuid.uuid4().hex
|
||||
path = photo_root() / (key + '.' + ext)
|
||||
os.replace(staging_name, path)
|
||||
try:
|
||||
await db.execute(insert(center_tutorials).values(
|
||||
id=key, room=room, equipment=equipment, video_file=key + '.' + ext, video_bytes=received,
|
||||
note=note, uploader_id=viewer['id'], created_at=now_ms()))
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
path.unlink(missing_ok=True)
|
||||
raise
|
||||
except BaseException:
|
||||
staging.close()
|
||||
staging_name.unlink(missing_ok=True)
|
||||
raise
|
||||
return {'id': key}
|
||||
|
||||
@app.api_route('/api/center/tutorials/{tutorial_id}', methods=['GET', 'HEAD'])
|
||||
async def tutorial_video(tutorial_id: str, preview: str = '0', db=Depends(get_db), viewer=Depends(current_user)):
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', tutorial_id): raise HTTPException(404, '教程不存在')
|
||||
row = (await db.execute(select(center_tutorials).where(center_tutorials.c.id == tutorial_id))).mappings().first()
|
||||
if not row: raise HTTPException(404, '教程不存在')
|
||||
path = photo_root() / row['video_file']
|
||||
if not path.is_file(): raise HTTPException(404, '教程视频文件不存在')
|
||||
ext = row['video_file'].rpartition('.')[2]
|
||||
media_type = {'mp4': 'video/mp4', 'mov': 'video/quicktime', 'webm': 'video/webm'}.get(ext, 'application/octet-stream')
|
||||
if preview == '1':
|
||||
if viewer['id'] != row['uploader_id']:
|
||||
raise HTTPException(403, '只有上传者可以下载原始视频')
|
||||
filename = f'{row["room"]}-{row["equipment"]}.{ext}'
|
||||
return range_safe_file(path, media_type=media_type, filename=filename)
|
||||
return range_safe_file(path, media_type=media_type, stat_result=path.stat(), content_disposition_type='inline')
|
||||
|
||||
@app.get('/api/center/items')
|
||||
async def items(q: str = '', db=Depends(get_db), viewer=Depends(current_user)):
|
||||
rows = (await db.execute(select(center_items).where(center_items.c.name.like('%'+q.strip()+'%')).order_by(center_items.c.name))).mappings().all()
|
||||
|
||||
+11
-1
@@ -169,6 +169,16 @@ center_duty_leaves = Table('center_duty_leaves', metadata,
|
||||
UniqueConstraint('duty_date', 'slot', 'user_id', name='uq_center_duty_leave_member'))
|
||||
Index('ix_center_duty_leave_date_slot', center_duty_leaves.c.duty_date, center_duty_leaves.c.slot)
|
||||
|
||||
center_tutorials = Table('center_tutorials', metadata,
|
||||
Column('id', String(36), primary_key=True),
|
||||
Column('room', String(40), nullable=False), Column('equipment', String(100), nullable=False),
|
||||
# 视频保存在 uploads/tutorials/{id}.{ext},这里只记文件名
|
||||
Column('video_file', String(80), nullable=False), Column('video_bytes', Integer, nullable=False),
|
||||
Column('note', Text, nullable=False, default=''),
|
||||
Column('uploader_id', String(36), ForeignKey('users.id'), nullable=False),
|
||||
Column('created_at', Integer, nullable=False))
|
||||
Index('ix_center_tutorials_created', center_tutorials.c.created_at)
|
||||
|
||||
timetables = Table('timetables', metadata,
|
||||
Column('user_id', String(36), ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||
Column('week_type', String(4), primary_key=True),
|
||||
@@ -180,5 +190,5 @@ timetables = Table('timetables', metadata,
|
||||
TABLES = (
|
||||
users, sessions, email_verifications, activities, participations, join_links,
|
||||
center_photos, center_materials, center_activity_materials, center_activity_meta,
|
||||
center_items, center_loans, center_checks, center_duty_leaves, timetables,
|
||||
center_items, center_loans, center_checks, center_duty_leaves, center_tutorials, timetables,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""静态文件响应:容忍媒体元素发出的异常 Range 头(#416 / #400)。"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from starlette.datastructures import Headers
|
||||
from starlette.responses import FileResponse
|
||||
from starlette.types import Receive, Scope, Send
|
||||
|
||||
|
||||
class RangeSafeFileResponse(FileResponse):
|
||||
"""不可满足或无法解析的 Range 头退化为整文件 200 响应。
|
||||
|
||||
浏览器视频元素偶尔会发出 ``Range: bytes=12345-`` 这类超出文件长度的请求,
|
||||
Starlette 会回 416,部分浏览器随即报错。这里只在可满足时走正常的 206 分段。
|
||||
"""
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http" or "range" not in Headers(scope=scope):
|
||||
await super().__call__(scope, receive, send)
|
||||
return
|
||||
if self.stat_result is None:
|
||||
self.stat_result = os.stat(self.path)
|
||||
self.set_stat_headers(self.stat_result)
|
||||
try:
|
||||
FileResponse._parse_range_header(Headers(scope=scope)["range"], self.stat_result.st_size)
|
||||
except Exception:
|
||||
scope = dict(scope)
|
||||
raw = list(scope["headers"])
|
||||
scope["headers"] = [(name, value) for name, value in raw if name.lower() not in (b"range", b"if-range")]
|
||||
await super().__call__(scope, receive, send)
|
||||
|
||||
|
||||
def range_safe_file(path: Path, media_type: str | None = None, filename: str | None = None,
|
||||
stat_result=None, content_disposition_type: str = "attachment") -> FileResponse:
|
||||
return RangeSafeFileResponse(path, media_type=media_type, filename=filename, stat_result=stat_result,
|
||||
content_disposition_type=content_disposition_type)
|
||||
@@ -0,0 +1,96 @@
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from test_api import ApiTestCase, auth, register
|
||||
|
||||
MP4_HEAD = b'\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom' + b'\x00' * 64
|
||||
|
||||
|
||||
class CenterTutorialTests(ApiTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
base = Path(__file__).resolve().parent.parent / 'outputs' / 'tests'
|
||||
self.root = base / ('center-tutorials-' + uuid.uuid4().hex)
|
||||
self.path_patch = patch.object(self.m, '_db_path', self.root / 'test.db'); self.path_patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.path_patch.stop(); shutil.rmtree(self.root, ignore_errors=True); super().tearDown()
|
||||
|
||||
async def upload(self, user, room='A101', equipment='激光切割机', note='先断电再开盖', body=MP4_HEAD,
|
||||
content_type='video/mp4'):
|
||||
response = await self.client.post('/api/center/tutorials', headers={**auth(user['token']),
|
||||
'content-type': content_type},
|
||||
params={'room': room, 'equipment': equipment, 'note': note}, content=body)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
return response.json()['id']
|
||||
|
||||
async def test_upload_list_and_range_streaming(self):
|
||||
user = await register(self.client, 'tutorialowner'); headers = auth(user['token'])
|
||||
tid = await self.upload(user)
|
||||
stored = self.root / 'uploads' / (tid + '.mp4')
|
||||
self.assertEqual(stored.read_bytes(), MP4_HEAD)
|
||||
listed = await self.client.get('/api/center/tutorials', headers=headers)
|
||||
self.assertEqual(listed.status_code, 200, listed.text)
|
||||
item = listed.json()['items'][0]
|
||||
self.assertEqual((item['room'], item['equipment'], item['note'], item['video_bytes']),
|
||||
('A101', '激光切割机', '先断电再开盖', len(MP4_HEAD)))
|
||||
self.assertEqual(item['uploader'], user['user']['display_name'])
|
||||
full = await self.client.get('/api/center/tutorials/' + tid, headers=headers)
|
||||
self.assertEqual((full.status_code, full.headers['content-type']), (200, 'video/mp4'))
|
||||
self.assertEqual(full.content, MP4_HEAD)
|
||||
part = await self.client.get('/api/center/tutorials/' + tid, headers={**headers, 'range': 'bytes=0-9'})
|
||||
self.assertEqual((part.status_code, part.content), (206, MP4_HEAD[:10]))
|
||||
past_end = await self.client.get('/api/center/tutorials/' + tid, headers={**headers, 'range': 'bytes=9999-'})
|
||||
self.assertEqual(past_end.status_code, 200)
|
||||
self.assertEqual(past_end.content, MP4_HEAD)
|
||||
|
||||
async def test_search_matches_room_equipment_and_note(self):
|
||||
user = await register(self.client, 'tutorialsearch'); headers = auth(user['token'])
|
||||
await self.upload(user, room='B202', equipment='投影仪', note='遥控器在讲台')
|
||||
await self.upload(user, room='A101', equipment='激光切割机', note='')
|
||||
self.assertEqual([i['room'] for i in (await self.client.get('/api/center/tutorials?q=B202', headers=headers)).json()['items']], ['B202'])
|
||||
self.assertEqual([i['equipment'] for i in (await self.client.get('/api/center/tutorials?q=激光', headers=headers)).json()['items']], ['激光切割机'])
|
||||
self.assertEqual([i['room'] for i in (await self.client.get('/api/center/tutorials?q=遥控器', headers=headers)).json()['items']], ['B202'])
|
||||
self.assertEqual((await self.client.get('/api/center/tutorials?q=不存在', headers=headers)).json(), {'items': [], 'has_more': False})
|
||||
|
||||
async def test_only_uploader_can_download_original(self):
|
||||
owner = await register(self.client, 'tutdlowner'); other = await register(self.client, 'tutdlother')
|
||||
tid = await self.upload(owner)
|
||||
self.assertEqual((await self.client.get('/api/center/tutorials/' + tid + '?preview=1', headers=auth(owner['token']))).status_code, 200)
|
||||
self.assertEqual((await self.client.get('/api/center/tutorials/' + tid + '?preview=1', headers=auth(other['token']))).status_code, 403)
|
||||
self.assertEqual((await self.client.get('/api/center/tutorials/' + tid, headers=auth(other['token']))).status_code, 200)
|
||||
|
||||
async def test_rejects_invalid_uploads_and_cleans_staging(self):
|
||||
user = await register(self.client, 'tutorialinvalid'); headers = auth(user['token'])
|
||||
base = {'content-type': 'video/mp4'}
|
||||
cases = [
|
||||
({'equipment': '投影仪'}, MP4_HEAD, 422),
|
||||
({'room': 'A101'}, MP4_HEAD, 422),
|
||||
({'room': 'A101', 'equipment': '投影仪'}, b'\x00\x01\x02GIF89a' + b'\x00' * 40, 422),
|
||||
({'room': 'A101', 'equipment': '投影仪'}, b'', 422),
|
||||
({'room': 'A' * 41, 'equipment': '投影仪'}, MP4_HEAD, 422),
|
||||
]
|
||||
for params, body, status in cases:
|
||||
response = await self.client.post('/api/center/tutorials', headers={**headers, **base}, params=params, content=body)
|
||||
self.assertEqual(response.status_code, status, (params, response.text))
|
||||
gif = await self.client.post('/api/center/tutorials', headers={**headers, 'content-type': 'image/gif'},
|
||||
params={'room': 'A101', 'equipment': '投影仪'}, content=MP4_HEAD)
|
||||
self.assertEqual(gif.status_code, 422)
|
||||
uploads = self.root / 'uploads'
|
||||
leftovers = [p.name for p in uploads.iterdir()] if uploads.is_dir() else []
|
||||
self.assertEqual(leftovers, [])
|
||||
self.assertEqual((await self.client.get('/api/center/tutorials', headers=headers)).json()['items'], [])
|
||||
|
||||
async def test_requires_login(self):
|
||||
self.assertEqual((await self.client.get('/api/center/tutorials')).status_code, 401)
|
||||
self.assertEqual((await self.client.post('/api/center/tutorials', params={'room': 'A', 'equipment': 'B'},
|
||||
headers={'content-type': 'video/mp4'}, content=MP4_HEAD)).status_code, 401)
|
||||
|
||||
async def test_lists_newest_first_with_paging(self):
|
||||
user = await register(self.client, 'tutorialpage'); headers = auth(user['token'])
|
||||
ids = [await self.upload(user, room=f'C{i:02d}', equipment='器材') for i in range(5)]
|
||||
first = (await self.client.get('/api/center/tutorials?limit=2', headers=headers)).json()
|
||||
self.assertEqual([i['id'] for i in first['items']], ids[::-1][:2]); self.assertTrue(first['has_more'])
|
||||
rest = (await self.client.get('/api/center/tutorials?limit=2&offset=2', headers=headers)).json()
|
||||
self.assertEqual([i['id'] for i in rest['items']], ids[::-1][2:4]); self.assertTrue(rest['has_more'])
|
||||
Reference in New Issue
Block a user