回滚到 982f0df:重构共享逻辑并修复值班提醒回执去重

This commit is contained in:
2026-11-22 23:17:01 +08:00
parent 1bb8f73f1e
commit cf97de9423
8 changed files with 42 additions and 314 deletions
+1 -7
View File
@@ -1,12 +1,6 @@
# 赋能中心一楼 # 赋能中心一楼
导航中的“赋能中心一楼”整合活动记录、独立值班、物品清点与借出登记、展厅使用登记和设备使用教程。原有活动、账号和招生就业服务队值班功能保留。 导航中的“赋能中心一楼”整合活动记录、独立值班、物品清点与借出登记。原有活动、账号和招生就业服务队值班功能保留。
## 设备使用教程
“设备使用教程”标签页提供视频上传、按教室号或设备名搜索、在线播放和本人删除。登录成员均可上传或观看,上传时需填写教室号和设备名,支持 MP4、WebM、MOV、M4V,单个文件不超过 500MB。
视频保存在业务数据库同目录的 `uploads/tutorials/`,不会出现在静态 `/uploads` 公开目录中;上传、列表、播放均需要登录,仅上传者可删除。浏览器通过登录请求取得视频,关闭播放弹层后释放临时视频资源。新增教程记录由启动时的表结构检查自动创建,不修改已有业务数据。部署备份继续保留整个 data 目录,包括教程视频。
## 赋能中心一楼值班 ## 赋能中心一楼值班
+6 -26
View File
@@ -19,8 +19,7 @@
--shadow: 0 2px 5px rgba(35, 64, 48, .025); --shadow: 0 2px 5px rgba(35, 64, 48, .025);
} }
* { box-sizing: border-box; -webkit-text-size-adjust: 100%; text-size-adjust: 100%; } * { box-sizing: border-box; }
.btn, button { font: inherit; }
html, body { html, body {
margin: 0; margin: 0;
@@ -99,7 +98,6 @@ textarea { width: 100%; resize: vertical; }
.topbar-user { display: flex; align-items: center; gap: 10px; white-space: nowrap; } .topbar-user { display: flex; align-items: center; gap: 10px; white-space: nowrap; }
#topbar-name { font-weight: 600; font-size: 14px; } #topbar-name { font-weight: 600; font-size: 14px; }
.menu-toggle { display: none; background: none; border: none; font-size: 20px; } .menu-toggle { display: none; background: none; border: none; font-size: 20px; }
.new-activity-short { display: none; }
/* ---------- 布局 ---------- */ /* ---------- 布局 ---------- */
.container { max-width: 1160px; margin: 0 auto; padding: 40px 28px 72px; } .container { max-width: 1160px; margin: 0 auto; padding: 40px 28px 72px; }
@@ -398,8 +396,6 @@ form input, form select, form textarea, .form-card input, .form-card select { wi
/* ---------- 响应式 ---------- */ /* ---------- 响应式 ---------- */
@media (max-width: 760px) { @media (max-width: 760px) {
:root { font-size: 14px; }
body { font-size: 14px; }
#nav { #nav {
display: none; display: none;
position: absolute; position: absolute;
@@ -517,12 +513,10 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.brand-mark { width: 26px; height: 28px; } .brand-mark { width: 26px; height: 28px; }
.topbar-user { margin-left: auto; } .topbar-user { margin-left: auto; }
.menu-toggle { display: grid; place-items: center; width: 42px; height: 42px; margin-left: 0; color: var(--ink); border-radius: 8px; } .menu-toggle { display: grid; place-items: center; width: 42px; height: 42px; margin-left: 0; color: var(--ink); border-radius: 8px; }
#nav { padding: 4px 10px 8px; z-index: 1; } #nav { padding: 12px 16px; box-shadow: 0 8px 12px #263c3508; }
#nav a { padding: 10px; font-size: 14px; } #nav a { padding: 12px; }
#nav a:last-child { border-top: 1px solid var(--line); margin-top: 4px; } #logout-btn { min-height: 42px; }
#new-activity-btn { flex: none; font-size: 13px; padding: 9px 12px; white-space: nowrap; } #new-activity-btn { font-size: 13px; padding: 9px 10px; }
.new-activity-label { display: none; }
.new-activity-short { display: inline; }
.container { padding: 28px 16px 56px; } .container { padding: 28px 16px 56px; }
.page-head { align-items: stretch; gap: 20px; } .page-head { align-items: stretch; gap: 20px; }
.page-head > div:first-child { width: 100%; } .page-head > div:first-child { width: 100%; }
@@ -536,18 +530,9 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.stat:nth-child(even), .stat:last-child { border-right: 0; } .stat:nth-child(even), .stat:last-child { border-right: 0; }
.stat b { font-size: 25px; } .stat b { font-size: 25px; }
.acard { padding: 20px; } .acard { padding: 20px; }
.acard-actions .btn { min-height: 40px; }
.photo-preview-summary { min-height: 40px; padding: 6px 10px; }
.photo-preview-summary [data-photo-preview] { min-height: 34px; padding-block: 2px; }
.acard-meta { gap: 8px 10px; margin-top: 12px; } .acard-meta { gap: 8px 10px; margin-top: 12px; }
.acard-meta .tag.cat { display: none; }
.meta-item { max-width: 100%; } .meta-item { max-width: 100%; }
.acard h3 { font-size: 17px; line-height: 1.4; }
.acard-desc { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; line-height: 1.6; }
.acard-actions .btn:not(.primary) { padding-inline: 10px; }
.acard-actions .btn { min-height: 42px; } .acard-actions .btn { min-height: 42px; }
.acard-actions { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.acard-actions .btn { justify-content: center; padding-inline: 6px; white-space: nowrap; }
.member-grid { grid-template-columns: repeat(auto-fill, minmax(min(230px, 100%), 1fr)); } .member-grid { grid-template-columns: repeat(auto-fill, minmax(min(230px, 100%), 1fr)); }
#members-table { table-layout: fixed; } #members-table { table-layout: fixed; }
#members-table th, #members-table td { padding: 12px 8px; font-size: 13px; overflow-wrap: anywhere; } #members-table th, #members-table td { padding: 12px 8px; font-size: 13px; overflow-wrap: anywhere; }
@@ -556,8 +541,6 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.form-card { padding: 22px; } .form-card { padding: 22px; }
.modal-mask { padding: 16px 10px; } .modal-mask { padding: 16px 10px; }
.modal { padding: 22px 18px; } .modal { padding: 22px 18px; }
.center-tabs { gap: 4px; }
.center-tabs .tab { flex: 0 0 auto; padding-inline: 10px; font-size: 13px; white-space: nowrap; }
.p-list li { flex-wrap: wrap; } .p-list li { flex-wrap: wrap; }
.add-member-row input { min-width: 0; } .add-member-row input { min-width: 0; }
} }
@@ -628,7 +611,7 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.center-shortcuts p { margin:5px 0 0; color:var(--muted); font-size:13px; } .center-shortcuts p { margin:5px 0 0; color:var(--muted); font-size:13px; }
.center-shortcut-actions { display:flex; flex-wrap:wrap; gap:10px; } .center-shortcut-actions { display:flex; flex-wrap:wrap; gap:10px; }
.center-shortcut-actions a { text-decoration:none; display:inline-flex; align-items:center; } .center-shortcut-actions a { text-decoration:none; display:inline-flex; align-items:center; }
.center-tabs { max-width:none; margin-bottom:24px; } .center-tabs { max-width:500px; margin-bottom:24px; }
.center-check-status { padding:18px 20px; background:var(--primary-soft); border:1px solid #d5e5da; border-radius:12px; margin-bottom:20px; } .center-check-status { padding:18px 20px; background:var(--primary-soft); border:1px solid #d5e5da; border-radius:12px; margin-bottom:20px; }
.center-subhead { margin-top:32px; } .center-subhead { margin-top:32px; }
.center-duty-head { display:flex; align-items:flex-end; justify-content:space-between; flex-wrap:wrap; gap:18px; margin-bottom:18px; } .center-duty-head { display:flex; align-items:flex-end; justify-content:space-between; flex-wrap:wrap; gap:18px; margin-bottom:18px; }
@@ -735,7 +718,4 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.center-history { margin-top:28px; } .center-history { margin-top:28px; }
.center-history summary { cursor:pointer; padding:12px 0; } .center-history summary { cursor:pointer; padding:12px 0; }
.center-history .acard { margin-top:12px; } .center-history .acard { margin-top:12px; }
.tutorial-video { display:block; width:100%; max-height:70vh; margin-top:18px; background:#151b17; border-radius:10px; }
.tutorial-actions { display:flex; align-items:center; gap:10px; margin-top:14px; }
.tutorial-upload-status { min-height:24px; }
@media (min-width:761px) and (max-width:1000px) { .topbar-inner { flex-wrap:wrap; } #nav { order:3; flex-basis:100%; } } @media (min-width:761px) and (max-width:1000px) { .topbar-inner { flex-wrap:wrap; } #nav { order:3; flex-basis:100%; } }
+5 -10
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WorkLog · 活动记录</title> <title>WorkLog · 活动记录</title>
<meta name="theme-color" content="#f5f7f5" /> <meta name="theme-color" content="#f5f7f5" />
<link rel="stylesheet" href="/assets/styles.css?v=29" /> <link rel="stylesheet" href="/assets/styles.css?v=28" />
</head> </head>
<body> <body>
<div id="app"> <div id="app">
@@ -16,7 +16,7 @@
<nav id="nav" aria-label="主导航"> <nav id="nav" aria-label="主导航">
<a href="#" data-view="feed">活动墙</a> <a href="#" data-view="feed">活动墙</a>
<a href="#" data-view="mine">我的记录</a> <a href="#" data-view="mine">我的记录</a>
<a href="#center-records" data-view="center">赋能中心一楼</a> <a href="#" data-view="center">赋能中心一楼</a>
<a href="#timetables" data-view="timetables">课表收取</a> <a href="#timetables" data-view="timetables">课表收取</a>
<a href="#" data-view="members">成员</a> <a href="#" data-view="members">成员</a>
<a href="#" data-view="profile">设置</a> <a href="#" data-view="profile">设置</a>
@@ -25,7 +25,7 @@
<span id="topbar-name"></span> <span id="topbar-name"></span>
<button class="btn ghost sm" id="logout-btn">退出</button> <button class="btn ghost sm" id="logout-btn">退出</button>
</div> </div>
<button class="btn primary" id="new-activity-btn" aria-label="+ 记录工作"><span class="new-activity-label">+ 记录工作</span><span class="new-activity-short" aria-hidden="true">+记录</span></button> <button class="btn primary" id="new-activity-btn">+ 记录工作</button>
<button class="menu-toggle" id="menu-toggle" aria-label="展开导航" aria-controls="nav" aria-expanded="false">☰</button> <button class="menu-toggle" id="menu-toggle" aria-label="展开导航" aria-controls="nav" aria-expanded="false">☰</button>
</div> </div>
</header> </header>
@@ -175,7 +175,7 @@
<p class="muted" id="center-export-status" role="status"></p> <p class="muted" id="center-export-status" role="status"></p>
<p class="muted">程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。</p> <p class="muted">程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。</p>
</details> </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><button class="tab" data-center-tab="tutorials">设备使用教程</button></div> <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>
<section id="center-records"> <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 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> <div id="center-record-list" class="card-list"></div>
@@ -210,11 +210,6 @@
<div class="filters center-toolbar"><button id="center-hall-refresh" class="btn">刷新登记数据</button><a id="center-hall-link" class="btn" href="#" target="_blank" rel="noopener">打开金山文档</a><span id="center-hall-status" class="muted" role="status"></span></div> <div class="filters center-toolbar"><button id="center-hall-refresh" class="btn">刷新登记数据</button><a id="center-hall-link" class="btn" href="#" target="_blank" rel="noopener">打开金山文档</a><span id="center-hall-status" class="muted" role="status"></span></div>
<div id="center-hall-list" class="card-list"></div> <div id="center-hall-list" class="card-list"></div>
</section> </section>
<section id="center-tutorials" class="hidden">
<div class="page-head center-subhead"><div><h3>设备使用教程</h3><p class="muted">按教室和设备查找视频,登录成员均可上传和观看。</p></div><button id="center-add-tutorial" class="btn primary" type="button">+ 添加教程</button></div>
<div class="filters center-toolbar"><input id="center-tutorial-q" type="search" aria-label="搜索设备教程" placeholder="搜索教室号 / 设备名" /><button id="center-tutorial-refresh" class="btn" type="button">刷新</button></div>
<div id="center-tutorial-list" class="card-list"></div>
</section>
</div> </div>
</main> </main>
<main id="timetables-view" class="view hidden"> <main id="timetables-view" class="view hidden">
@@ -363,7 +358,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div> <div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=51"></script> <script src="/js/app.js?v=48"></script>
</div> </div>
</body> </body>
</html> </html>
+24 -89
View File
@@ -26,7 +26,6 @@
}); });
const fmtDay = (ms) => const fmtDay = (ms) =>
new Date(ms).toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" }); new Date(ms).toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
const formatBytes = bytes => bytes >= MB ? `${(bytes / MB).toFixed(1)} MB` : `${Math.max(1, Math.ceil(bytes / 1024))} KB`;
const STATUS_LABEL = { joined: "已确认", attended: "已参加", absent: "缺席" }; const STATUS_LABEL = { joined: "已确认", attended: "已参加", absent: "缺席" };
const toLocalInput = (ms) => { const toLocalInput = (ms) => {
@@ -422,10 +421,15 @@
}); });
// ------------------------------------------------------------- 顶栏 // ------------------------------------------------------------- 顶栏
$("#brand").addEventListener("click", () => show("feed"));
$("#new-activity-btn").addEventListener("click", () => openActivityForm(null, state.view === 'center' ? 'center' : 'normal'));
$("#menu-toggle").addEventListener("click", () => { $("#menu-toggle").addEventListener("click", () => {
const open = $("#nav").classList.toggle("open"); const open = $("#nav").classList.toggle("open");
$("#menu-toggle").setAttribute("aria-expanded", String(open)); $("#menu-toggle").setAttribute("aria-expanded", String(open));
}); });
$$("#nav a").forEach((a) =>
a.addEventListener("click", (e) => { e.preventDefault(); show(a.dataset.view); })
);
// ------------------------------------------------------------- 活动卡片 // ------------------------------------------------------------- 活动卡片
const initials = (name) => { const initials = (name) => {
@@ -516,7 +520,6 @@
<h3><button class="activity-title" data-act="open">${esc(a.title)}</button></h3> <h3><button class="activity-title" data-act="open">${esc(a.title)}</button></h3>
<div class="acard-meta"> <div class="acard-meta">
${visTag}${statusTag} ${visTag}${statusTag}
${isCenter ? '<span class="tag cat">一楼记录</span>' : ''}
${full ? `<span class="tag full">已满 ${a.capacity} 人</span>` : ""} ${full ? `<span class="tag full">已满 ${a.capacity} 人</span>` : ""}
<span class="meta-item">📅 ${fmtDate(a.start_at)}</span> <span class="meta-item">📅 ${fmtDate(a.start_at)}</span>
${a.location ? `<span class="meta-item">📍 ${esc(a.location)}</span>` : ""} ${a.location ? `<span class="meta-item">📍 ${esc(a.location)}</span>` : ""}
@@ -524,11 +527,12 @@
</div> </div>
</div> </div>
${a.description ? `<p class="acard-desc">${esc(a.description).slice(0, 160)}${a.description.length > 160 ? "…" : ""}</p>` : ""} ${a.description ? `<p class="acard-desc">${esc(a.description).slice(0, 160)}${a.description.length > 160 ? "…" : ""}</p>` : ""}
${a.record_type === 'center' ? '<span class="tag cat">赋能中心一楼活动记录</span>' : ''}
${materialButtons(a)} ${materialButtons(a)}
${photoGallery(a.photo_ids)} ${photoGallery(a.photo_ids)}
<div class="acard-foot"> <div class="acard-foot">
<div class="faces"> <div class="faces">
${isCenter ? `<span class="faces-label">${a.organizer ? `由 ${esc(a.organizer.display_name)} 记录` : '全员可见'}</span>` : `${faces}${more}<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>`} ${isCenter ? `<span class="faces-label">仅作记录 · 全员可见${a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ''}</span>` : `${faces}${more}<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>`}
</div> </div>
<div class="acard-actions">${actions.join("")}</div> <div class="acard-actions">${actions.join("")}</div>
</div> </div>
@@ -891,33 +895,28 @@
return uploadFile('/api/center/materials', 'POST', file, onProgress, 'application/zip'); return uploadFile('/api/center/materials', 'POST', file, onProgress, 'application/zip');
} }
function uploadFile(path, method, file, onProgress, contentType, fields) { function uploadFile(path, method, file, onProgress, contentType) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
materialUpload = xhr; materialUpload = xhr;
xhr.open(method, path); xhr.open(method, path);
xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`); xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`);
if (contentType) xhr.setRequestHeader('Content-Type', contentType); xhr.setRequestHeader('Content-Type', contentType);
xhr.timeout = 10 * 60 * 1000; xhr.timeout = 10 * 60 * 1000;
xhr.upload.onprogress = event => onProgress(event.loaded, event.lengthComputable ? event.total : file.size); xhr.upload.onprogress = event => onProgress(event.loaded, event.lengthComputable ? event.total : file.size);
xhr.upload.onload = () => onProgress(file.size, file.size); xhr.upload.onload = () => onProgress(file.size, file.size);
xhr.onload = () => { xhr.onload = () => {
let result; let result;
try { result = JSON.parse(xhr.responseText); } catch { result = {}; } try { result = JSON.parse(xhr.responseText); } catch { result = {}; }
if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable || result.ok)) resolve(result); if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable)) resolve(result);
else reject(new Error(xhr.status === 413 ? (typeof result.detail === 'string' ? result.detail : '上传文件过大,请检查大小限制') : apiErrorMessage(result.detail, xhr.status))); else reject(new Error(xhr.status === 413 ? (typeof result.detail === 'string' ? result.detail : '上传文件过大,请检查大小限制') : apiErrorMessage(result.detail, xhr.status)));
}; };
xhr.onerror = () => reject(new Error('照片或附件没有上传成功:网络中断或文件过大(每张照片≤8MB、ZIP≤100MB)')); xhr.onerror = () => reject(new Error('上传失败,请检查网络后重试'));
xhr.ontimeout = () => reject(new Error('上传超时,请重试')); xhr.ontimeout = () => reject(new Error('上传超时,请重试'));
xhr.onabort = () => reject(new Error('上传已取消')); xhr.onabort = () => reject(new Error('上传已取消'));
xhr.onloadend = () => { if (materialUpload === xhr) materialUpload = null; }; xhr.onloadend = () => { if (materialUpload === xhr) materialUpload = null; };
onProgress(0, file.size); onProgress(0, file.size);
if (fields) { xhr.send(file);
const data = new FormData();
Object.entries(fields).forEach(([key, value]) => data.append(key, value));
data.append('video', file);
xhr.send(data);
} else xhr.send(file);
}); });
} }
@@ -938,11 +937,11 @@
} }
} }
function centerUploadFields(prefix, photoLabel = '照片') { function centerUploadFields(prefix) {
return `<label>${photoLabel}<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label> return `<label>活动照片<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label>
<p class="muted">可选JPG、PNG、WebP,自动转成统一JPEG;最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张≤${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div> <p class="muted">可直接多选相册照片或拍照,支持JPG、PNG、WebP并自动转为统一JPEG;每次最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张不超过${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div>
<label>ZIP附件 <span class="hint-inline">(选填)</span><input name="materials" type="file" accept=".zip,application/zip" /></label> <label>ZIP附件 <span class="hint-inline">(选填)</span><input name="materials" type="file" accept=".zip,application/zip" /></label>
<p class="muted">有PDF、Word、Excel等文档时打包成ZIP,最大${CENTER_ZIP_MAX_MB}MB。</p>`; <p class="muted">需要附PDF、Word、Excel等文档时再上传ZIP,最大${CENTER_ZIP_MAX_MB}MB,可不含照片。</p>`;
} }
function bindCenterUploads(form, box, label, meter, prefix) { function bindCenterUploads(form, box, label, meter, prefix) {
@@ -1050,12 +1049,11 @@
// ---- 新建 / 编辑活动 // ---- 新建 / 编辑活动
function openActivityForm(existing = null, defaultType = 'normal') { function openActivityForm(existing = null, defaultType = 'normal') {
const isEdit = !!existing; const isEdit = !!existing;
const isCenter = existing?.record_type === 'center' || defaultType === 'center';
modal(` modal(`
<h3>${isEdit ? "编辑工作" : (isCenter ? "记录一楼活动" : "记录一项工作")}</h3> <h3>${isEdit ? "编辑工作" : "记录一项工作"}</h3>
<p class="modal-sub muted">${isCenter ? "提交后立即生效,一楼活动记录全员可见。" : "提交后立即生效,所有人可见。"}</p> <p class="modal-sub muted">提交后立即生效,所有人可见。</p>
<form id="act-form"> <form id="act-form">
<label id="act-type-field">记录类型<select name="record_type"><option value="normal">普通工作记录</option><option value="center" hidden>一楼活动记录</option></select></label> <label>记录类型<select name="record_type"><option value="normal">普通工作记录</option></select></label>
<label>工作名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label> <label>工作名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label>
<div class="form-row"> <div class="form-row">
<label>开始时间 *<input name="start_at" type="datetime-local" required value="${existing ? toLocalInput(existing.start_at) : ""}" /></label> <label>开始时间 *<input name="start_at" type="datetime-local" required value="${existing ? toLocalInput(existing.start_at) : ""}" /></label>
@@ -1063,9 +1061,9 @@
</div> </div>
<label>人数上限 <span class="hint-inline">(选填,留空不限人数)</span><input name="capacity" type="number" min="1" max="500" step="1" value="${existing?.capacity ?? ""}" placeholder="不限人数" /></label> <label>人数上限 <span class="hint-inline">(选填,留空不限人数)</span><input name="capacity" type="number" min="1" max="500" step="1" value="${existing?.capacity ?? ""}" placeholder="不限人数" /></label>
<label>备注 <span class="hint-inline">(选填)</span><textarea name="description" rows="3" maxlength="2000" placeholder="做什么、带什么、注意事项…">${esc(existing?.description || "")}</textarea></label> <label>备注 <span class="hint-inline">(选填)</span><textarea name="description" rows="3" maxlength="2000" placeholder="做什么、带什么、注意事项…">${esc(existing?.description || "")}</textarea></label>
<div id="act-photo-fields" class="hidden">${centerUploadFields('act', isCenter ? '活动照片' : '照片')}<p class="muted">${isEdit ? '照片和ZIP至少选择一种。编辑时会保留原照片和附件,所选内容追加保存。' : '照片和ZIP至少选择一种,ZIP可选。'}</p><div id="act-photo-preview">${photoGallery(existing?.photo_ids, '已有活动照片')}</div></div> <div id="act-photo-fields" class="hidden">${centerUploadFields('act')}<p class="muted">照片和ZIP至少选择一种。编辑时会保留原照片和附件,所选内容追加保存。</p><div id="act-photo-preview">${photoGallery(existing?.photo_ids, '已有活动照片')}</div></div>
<label class="checkline" id="act-visibility"><input type="checkbox" name="visibility" ${!existing || existing.visibility === "public" ? "checked" : ""} /> 公开活动(所有人可见;不勾选则仅参加者可见)</label> <label class="checkline" id="act-visibility"><input type="checkbox" name="visibility" ${!existing || existing.visibility === "public" ? "checked" : ""} /> 公开活动(所有人可见;不勾选则仅参加者可见)</label>
<p id="act-center-policy" class="muted hidden">全员可见,仅作活动记录,无需报名,也不计入参加统计。</p> <p id="act-center-policy" class="muted hidden">全员可见,仅作活动记录,无需参加,也不计入参加统计。</p>
<div id="act-upload-progress" class="upload-progress hidden"> <div id="act-upload-progress" class="upload-progress hidden">
<p id="act-upload-status" role="status" aria-live="polite"></p> <p id="act-upload-status" role="status" aria-live="polite"></p>
<progress id="act-upload-meter" max="100" value="0" aria-labelledby="act-upload-status"></progress> <progress id="act-upload-meter" max="100" value="0" aria-labelledby="act-upload-status"></progress>
@@ -1083,12 +1081,11 @@
const errorBox = $('#act-error'); const errorBox = $('#act-error');
const collectUploads = bindCenterUploads(activityForm, progressBox, progressLabel, progressMeter, 'act'); const collectUploads = bindCenterUploads(activityForm, progressBox, progressLabel, progressMeter, 'act');
activityForm.record_type.value = existing?.record_type || defaultType; activityForm.record_type.value = existing?.record_type || defaultType;
activityForm.record_type.disabled = defaultType === 'center'; activityForm.record_type.disabled = state.view === 'center';
const togglePhotos = () => { const togglePhotos = () => {
const isCenter = activityForm.record_type.value === 'center'; const isCenter = activityForm.record_type.value === 'center';
$('#act-photo-fields').classList.toggle('hidden', !isCenter); $('#act-photo-fields').classList.toggle('hidden', !isCenter);
$('#act-visibility').classList.toggle('hidden', isCenter); $('#act-visibility').classList.toggle('hidden', isCenter);
$('#act-type-field').classList.toggle('hidden', isCenter);
$('#act-center-policy').classList.toggle('hidden', !isCenter); $('#act-center-policy').classList.toggle('hidden', !isCenter);
activityForm.visibility.disabled = isCenter; activityForm.visibility.disabled = isCenter;
if (isCenter && !activityForm.location.value.trim()) activityForm.location.value = '赋能中心一楼'; if (isCenter && !activityForm.location.value.trim()) activityForm.location.value = '赋能中心一楼';
@@ -1123,8 +1120,6 @@
if (body.record_type === 'center') { if (body.record_type === 'center') {
if (!f.photos.files.length && !f.materials.files.length && !(existing?.photo_ids || []).length && !existing?.material_id && !existing?.materials?.length) throw new Error('请至少选择照片或ZIP附件'); if (!f.photos.files.length && !f.materials.files.length && !(existing?.photo_ids || []).length && !existing?.material_id && !existing?.materials?.length) throw new Error('请至少选择照片或ZIP附件');
btn.textContent = '正在上传…'; btn.textContent = '正在上传…';
progressBox.classList.remove('hidden');
progressLabel.textContent = '正在准备照片…';
const uploaded = await collectUploads(); const uploaded = await collectUploads();
body.photo_ids = uploaded.photo_ids; body.photo_ids = uploaded.photo_ids;
body.material_id = uploaded.material_id || existing?.material_id || null; body.material_id = uploaded.material_id || existing?.material_id || null;
@@ -1543,14 +1538,13 @@
let centerRecords = []; let centerRecords = [];
function openCenterFromHash() { function openCenterFromHash() {
if (state.me && location.hash === '#timetables') { show('timetables'); return true; } if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
if (!state.me || !['#center', '#center-records', '#center-duty', '#center-assets', '#center-hall', '#center-tutorials'].includes(location.hash)) return false; 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' : location.hash === '#center-tutorials' ? 'tutorials' : 'records'; centerTab = 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)); $$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab));
$('#center-records').classList.toggle('hidden', centerTab !== 'records'); $('#center-records').classList.toggle('hidden', centerTab !== 'records');
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty'); $('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets'); $('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall'); $('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
show('center'); show('center');
return true; return true;
} }
@@ -1571,8 +1565,6 @@
bindCardEvents($('#center-record-list')); bindCardEvents($('#center-record-list'));
} else if (centerTab === 'duty') { } else if (centerTab === 'duty') {
await loadCenterDuty(); await loadCenterDuty();
} else if (centerTab === 'tutorials') {
await loadCenterTutorials();
} else if (centerTab === 'hall') { } else if (centerTab === 'hall') {
$('#center-hall-status').textContent = '正在读取金山文档登记表…'; $('#center-hall-status').textContent = '正在读取金山文档登记表…';
const hall = await api('/center/hall-log'); const hall = await api('/center/hall-log');
@@ -1626,65 +1618,8 @@
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty'); $('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets'); $('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall'); $('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
loadCenter(); loadCenter();
})); }));
async function loadCenterTutorials() {
const data = await api('/center/tutorials?q=' + encodeURIComponent($('#center-tutorial-q').value.trim()));
$('#center-tutorial-list').innerHTML = data.items.length ? data.items.map(item => `
<article class="acard"><div class="acard-top"><div><h3>${esc(item.device_name)}</h3><div class="acard-meta"><span>教室 ${esc(item.classroom)}</span></div></div></div>
<div class="acard-foot"><span>${fmtDate(item.created_at)} · ${formatBytes(item.size_bytes)}</span><span>上传者:${esc(item.display_name)}</span></div>
<div class="tutorial-actions"><button class="btn primary" data-tutorial-play="${item.id}">▶ 播放教程</button>${item.can_delete ? `<button class="btn danger" data-tutorial-delete="${item.id}">删除</button>` : ''}</div></article>`).join('') : '<div class="empty-state"><p>还没有匹配的设备教程</p><p class="muted">添加一个视频,帮助大家快速上手。</p></div>';
}
$('#center-tutorial-q').addEventListener('input', debounce(loadCenterTutorials, 300));
$('#center-tutorial-refresh').addEventListener('click', loadCenterTutorials);
$('#center-add-tutorial').addEventListener('click', () => {
modal(`<h3>添加设备使用教程</h3><p class="modal-sub muted">视频仅登录成员可见。单个文件不超过 500MB。</p>
<form id="tutorial-form"><label>教室号<input name="classroom" required maxlength="40" placeholder="例如:101" /></label>
<label>设备名<input name="device_name" required maxlength="100" placeholder="例如:多媒体投影机" /></label>
<label>教程视频<input name="video" type="file" required accept="video/mp4,video/webm,video/quicktime,.m4v" /></label>
<div class="upload-progress hidden"><p>正在上传…</p><progress max="100" value="0"></progress></div>
<div class="form-error tutorial-upload-status" role="alert"></div><div class="form-actions"><button type="button" class="btn" id="tutorial-cancel">取消</button><button class="btn primary" type="submit">上传教程</button></div></form>`);
$('#tutorial-cancel').addEventListener('click', closeModal);
$('#tutorial-form').addEventListener('submit', async event => {
event.preventDefault();
const form = event.target; const submit = form.querySelector('[type=submit]');
const error = form.querySelector('.form-error'); const progress = form.querySelector('.upload-progress');
if (!form.reportValidity()) return;
submit.disabled = true; error.textContent = ''; progress.classList.remove('hidden');
try {
const result = await uploadFile('/api/center/tutorials', 'POST', form.video.files[0], (loaded, total) => {
progress.querySelector('progress').value = total ? loaded / total * 100 : 0;
progress.querySelector('p').textContent = `正在上传:${formatBytes(loaded)} / ${formatBytes(total)}`;
}, null, { classroom: form.classroom.value, device_name: form.device_name.value });
if (!result.ok) throw new Error('教程保存失败,请重试');
closeModal(); toast('教程已添加'); await loadCenterTutorials();
} catch (e) { error.textContent = e.message; submit.disabled = false; }
});
});
$('#center-tutorial-list').addEventListener('click', async event => {
const play = event.target.closest('[data-tutorial-play]');
const remove = event.target.closest('[data-tutorial-delete]');
if (play && !play.disabled) {
play.disabled = true;
play.textContent = '加载中…';
try {
const data = await api(`/center/tutorials/${encodeURIComponent(play.dataset.tutorialPlay)}/playback`, { method: 'POST' });
const response = await fetch(data.url, { headers: { Authorization: `Bearer ${getToken()}` } });
if (!response.ok) { const error = await response.json().catch(() => ({})); throw new Error(error.detail || '视频加载失败'); }
const url = URL.createObjectURL(await response.blob());
modal(`<h3>设备使用教程</h3><video class="tutorial-video" src="${url}" controls playsinline preload="metadata"></video><div class="form-actions"><button class="btn" id="tutorial-close">关闭</button></div>`);
$('#tutorial-close').addEventListener('click', closeModal);
modalCleanup = () => { const video = $('#modal-root video'); if (video) video.pause(); URL.revokeObjectURL(url); };
} catch (error) { toast(error.message, true); }
finally { play.disabled = false; play.textContent = '▶ 播放教程'; }
}
if (remove && !remove.disabled && confirm('确认删除这条教程吗?视频文件将一并删除。')) {
remove.disabled = true;
try { await api(`/center/tutorials/${encodeURIComponent(remove.dataset.tutorialDelete)}`, { method: 'DELETE' }); await loadCenterTutorials(); }
catch (error) { toast(error.message, true); remove.disabled = false; }
}
});
$('#center-new').addEventListener('click', () => openActivityForm(null, 'center')); $('#center-new').addEventListener('click', () => openActivityForm(null, 'center'));
$('#center-hall-refresh').addEventListener('click', async () => { $('#center-hall-refresh').addEventListener('click', async () => {
try { await api('/center/hall-log?refresh=true'); } finally { await loadCenter(); } try { await api('/center/hall-log?refresh=true'); } finally { await loadCenter(); }
+3 -102
View File
@@ -11,41 +11,17 @@ from pathlib import PurePosixPath
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from fastapi import Depends, Form, HTTPException, Request, UploadFile from fastapi import Depends, HTTPException, Request
from fastapi.responses import FileResponse, StreamingResponse from fastapi.responses import FileResponse
from PIL.Image import DecompressionBombError from PIL.Image import DecompressionBombError
from pydantic import BaseModel, Field, field_validator from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select, insert, update, delete, func, text, or_ from sqlalchemy import select, insert, update, delete, func, text, or_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_tutorials, 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, activities, users
from .duty import BEIJING from .duty import BEIJING
from .security import now_ms, PHONE_PATTERN from .security import now_ms, PHONE_PATTERN
class RangeResponse(StreamingResponse):
def __init__(self, path: Path, range_header: str | None, media_type: str):
size = path.stat().st_size
match = re.fullmatch(r'bytes=(\d+)-(\d*)', range_header or '')
start, end = (int(match[1]), int(match[2]) if match[2] else size - 1) if match else (0, size - 1)
if (range_header and not match) or start >= size or start > end:
super().__init__(b'', status_code=416, headers={'Content-Range': f'bytes */{size}'})
return
end = min(end, size - 1)
def chunks():
with path.open('rb') as source:
source.seek(start)
remaining = end - start + 1
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk: break
remaining -= len(chunk)
yield chunk
super().__init__(chunks(), status_code=206 if match else 200, media_type=media_type, headers={
'Content-Length': str(end - start + 1), 'Accept-Ranges': 'bytes',
'Content-Range': f'bytes {start}-{end}/{size}',
})
def required_text(value: str, message: str) -> str: def required_text(value: str, message: str) -> str:
value = value.strip() value = value.strip()
if not value: if not value:
@@ -116,8 +92,6 @@ class MaterialIn(BaseModel):
MAX_PHOTOS_PER_UPLOAD = 50 MAX_PHOTOS_PER_UPLOAD = 50
MAX_PHOTO_BYTES = 8 * 1024 * 1024 MAX_PHOTO_BYTES = 8 * 1024 * 1024
MAX_TUTORIAL_BYTES = 500 * 1024 * 1024
TUTORIAL_TYPES = {'.mp4': 'video/mp4', '.m4v': 'video/x-m4v', '.mov': 'video/quicktime', '.webm': 'video/webm'}
MAX_ZIP_BYTES = 100 * 1024 * 1024 MAX_ZIP_BYTES = 100 * 1024 * 1024
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024 MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024 MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024
@@ -346,79 +320,6 @@ def install(app, get_db, current_user, photo_root, visible_clause):
path=photo_root()/(row['id']+'.zip') path=photo_root()/(row['id']+'.zip')
if not path.is_file():raise HTTPException(404,'材料包文件不存在') if not path.is_file():raise HTTPException(404,'材料包文件不存在')
return FileResponse(path,media_type='application/zip',filename='center-materials-'+row['id']+'.zip') return FileResponse(path,media_type='application/zip',filename='center-materials-'+row['id']+'.zip')
@app.get('/api/center/tutorials')
async def tutorials(q: str = '', db=Depends(get_db), viewer=Depends(current_user)):
keyword = q.strip()[:100]
query = select(center_tutorials, users.c.display_name).join(users, users.c.id == center_tutorials.c.owner_id)
if keyword:
query = query.where(or_(center_tutorials.c.classroom.like('%' + keyword + '%'), center_tutorials.c.device_name.like('%' + keyword + '%')))
rows = (await db.execute(query.order_by(center_tutorials.c.created_at.desc()).limit(200))).mappings().all()
return {'items': [dict(row, can_delete=row['owner_id'] == viewer['id']) for row in rows]}
@app.post('/api/center/tutorials')
async def create_tutorial(classroom: str = Form(), device_name: str = Form(), video: UploadFile = Form(), db=Depends(get_db), viewer=Depends(current_user)):
classroom = classroom.strip()
device_name = device_name.strip()
if not classroom or not device_name: raise HTTPException(422, '教室号和设备名不能为空')
if len(classroom) > 40 or len(device_name) > 100: raise HTTPException(422, '教室号最多40字,设备名最多100字')
filename = (video.filename or '').strip()[:180]
extension = Path(filename).suffix.lower()
if extension not in TUTORIAL_TYPES: raise HTTPException(422, '仅支持MP4、WebM、MOV、M4V视频')
folder = photo_root() / 'tutorials'
folder.mkdir(parents=True, exist_ok=True)
video_key = uuid.uuid4().hex
path = folder / (video_key + extension)
size = 0
try:
with path.open('wb') as output:
while chunk := await video.read(1024 * 1024):
size += len(chunk)
if size > MAX_TUTORIAL_BYTES: raise HTTPException(413, '教程视频最大500MB')
await asyncio.to_thread(output.write, chunk)
if not size: raise HTTPException(422, '视频文件不能为空')
await db.execute(insert(center_tutorials).values(
id=uuid.uuid4().hex, classroom=classroom, device_name=device_name,
video_key=video_key, original_name=filename, media_type=TUTORIAL_TYPES[extension],
size_bytes=size, owner_id=viewer['id'], created_at=now_ms(),
))
await db.commit()
except Exception:
await db.rollback()
path.unlink(missing_ok=True)
raise
finally:
await video.close()
return {'ok': True}
@app.post('/api/center/tutorials/{tutorial_id}/playback')
async def tutorial_playback(tutorial_id: str, db=Depends(get_db), viewer=Depends(current_user)):
await tutorial_file(tutorial_id, db)
return {'url': f'/api/center/tutorials/{tutorial_id}/video'}
async def tutorial_file(tutorial_id: str, db):
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, '教程不存在')
extension = next((ext for ext, mime in TUTORIAL_TYPES.items() if mime == row['media_type']), '.mp4')
path = photo_root() / 'tutorials' / (row['video_key'] + extension)
if not path.is_file(): raise HTTPException(404, '教程视频文件不存在')
return path, row
@app.get('/api/center/tutorials/{tutorial_id}/video')
async def tutorial_video(tutorial_id: str, request: Request, db=Depends(get_db), viewer=Depends(current_user)):
path, row = await tutorial_file(tutorial_id, db)
return RangeResponse(path, request.headers.get('Range'), row['media_type'])
@app.delete('/api/center/tutorials/{tutorial_id}')
async def delete_tutorial(tutorial_id: str, db=Depends(get_db), viewer=Depends(current_user)):
path, row = await tutorial_file(tutorial_id, db)
if row['owner_id'] != viewer['id']: raise HTTPException(403, '只能删除自己上传的教程')
await db.execute(delete(center_tutorials).where(center_tutorials.c.id == tutorial_id))
await db.commit()
path.unlink(missing_ok=True)
return {'ok': True}
@app.post('/api/center/photos') @app.post('/api/center/photos')
async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)): async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)):
raw = bytearray() raw = bytearray()
+2 -4
View File
@@ -13,7 +13,7 @@ from fastapi import Depends, HTTPException, Query
from pydantic import BaseModel, Field, field_validator from pydantic import BaseModel, Field, field_validator
from sqlalchemy import insert, select from sqlalchemy import insert, select
from .duty import BEIJING from .duty import BEIJING, week_type_on
from .models import center_duty_leaves, users from .models import center_duty_leaves, users
from .security import now_ms from .security import now_ms
@@ -68,9 +68,7 @@ def _monday_for(value: date) -> date:
def _week_type(schedule: dict, week_start: date) -> str: def _week_type(schedule: dict, week_start: date) -> str:
week_delta = (_monday_for(week_start) - schedule["anchor_day"]).days // 7 return week_type_on(schedule, week_start)
odd = week_delta % 2 == 0
return schedule["anchor_week"] if odd else ("even" if schedule["anchor_week"] == "odd" else "odd")
def _at_ms(day: date, clock: str) -> int: def _at_ms(day: date, clock: str) -> int:
+1 -9
View File
@@ -143,14 +143,6 @@ center_activity_materials = Table('center_activity_materials', metadata,
Column('activity_id', String(36), ForeignKey('activities.id', ondelete='CASCADE'), primary_key=True), Column('activity_id', String(36), ForeignKey('activities.id', ondelete='CASCADE'), primary_key=True),
Column('material_id', String(32), ForeignKey('center_materials.id'), primary_key=True), Column('material_id', String(32), ForeignKey('center_materials.id'), primary_key=True),
Column('created_at', Integer, nullable=False)) Column('created_at', Integer, nullable=False))
center_tutorials = Table('center_tutorials', metadata,
Column('id', String(32), primary_key=True),
Column('classroom', String(40), nullable=False), Column('device_name', String(100), nullable=False),
Column('video_key', String(40), nullable=False, unique=True),
Column('original_name', String(180), nullable=False), Column('media_type', String(40), nullable=False),
Column('size_bytes', Integer, nullable=False), Column('owner_id', String(36), ForeignKey('users.id'), nullable=False),
Column('created_at', Integer, nullable=False))
Index('ix_center_tutorial_created', center_tutorials.c.created_at)
center_items = Table('center_items', metadata, center_items = Table('center_items', metadata,
Column('id', String(32), primary_key=True), Column('name', String(100), nullable=False, unique=True), Column('id', String(32), primary_key=True), Column('name', String(100), nullable=False, unique=True),
Column('quantity', Integer, nullable=False), Column('created_at', Integer, nullable=False)) Column('quantity', Integer, nullable=False), Column('created_at', Integer, nullable=False))
@@ -188,5 +180,5 @@ timetables = Table('timetables', metadata,
TABLES = ( TABLES = (
users, sessions, email_verifications, activities, participations, join_links, users, sessions, email_verifications, activities, participations, join_links,
center_photos, center_materials, center_activity_materials, center_activity_meta, center_photos, center_materials, center_activity_materials, center_activity_meta,
center_tutorials, center_items, center_loans, center_checks, center_duty_leaves, timetables, center_items, center_loans, center_checks, center_duty_leaves, timetables,
) )
-67
View File
@@ -1,67 +0,0 @@
import tempfile
from pathlib import Path
from unittest.mock import patch
from sqlalchemy import select
from test_api import ApiTestCase, auth, register
from server.models import center_tutorials
class CenterTutorialTests(ApiTestCase):
def setUp(self):
super().setUp()
self.files = tempfile.TemporaryDirectory()
self.root = Path(self.files.name)
self.path_patch = patch.object(self.m, '_db_path', self.root / 'test.db')
self.path_patch.start()
def tearDown(self):
self.path_patch.stop()
self.files.cleanup()
super().tearDown()
async def upload(self, user, classroom='101', device='投影机', content=b'0123456789', name='guide.mp4'):
return await self.client.post('/api/center/tutorials', headers=auth(user['token']), data={
'classroom': classroom, 'device_name': device,
}, files={'video': (name, content, 'video/mp4')})
async def test_upload_search_stream_and_owner_delete(self):
owner = await register(self.client, 'tutorialowner')
other = await register(self.client, 'tutorialother')
self.assertEqual((await self.client.get('/api/center/tutorials')).status_code, 401)
response = await self.upload(owner)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual((await self.upload(owner, name='guide.exe')).status_code, 422)
self.assertEqual((await self.upload(owner, classroom=' ', device='')).status_code, 422)
items = (await self.client.get('/api/center/tutorials?q=投影', headers=auth(other['token']))).json()['items']
self.assertEqual(len(items), 1)
tutorial = items[0]
self.assertEqual(tutorial['classroom'], '101')
self.assertEqual(tutorial['device_name'], '投影机')
self.assertTrue(tutorial['can_delete'] is False)
self.assertEqual((await self.client.get('/api/center/tutorials?q=202', headers=auth(other['token']))).json()['items'], [])
self.assertEqual((await self.client.delete('/api/center/tutorials/' + tutorial['id'], headers=auth(other['token']))).status_code, 403)
self.assertEqual((await self.client.get('/api/center/tutorials/' + tutorial['id'] + '/video')).status_code, 401)
playback = await self.client.post('/api/center/tutorials/' + tutorial['id'] + '/playback', headers=auth(other['token']))
self.assertEqual(playback.status_code, 200, playback.text)
url = playback.json()['url']
self.assertNotIn(owner['token'], url)
video = await self.client.get(url, headers={**auth(other['token']), 'Range': 'bytes=2-5'})
self.assertEqual(video.status_code, 206)
self.assertEqual(video.content, b'2345')
self.assertEqual(video.headers['Content-Range'], 'bytes 2-5/10')
self.assertEqual((await self.client.get(url, headers={**auth(other['token']), 'Range': 'bytes=20-25'})).status_code, 416)
async with self.sessions() as db:
row = (await db.execute(select(center_tutorials))).mappings().one()
path = self.root / 'uploads' / 'tutorials' / (row['video_key'] + '.mp4')
self.assertEqual(path.read_bytes(), b'0123456789')
self.assertEqual((await self.client.delete('/api/center/tutorials/' + tutorial['id'], headers=auth(owner['token']))).status_code, 200)
self.assertFalse(path.exists())
self.assertEqual((await self.client.get('/api/center/tutorials/' + tutorial['id'] + '/video', headers=auth(owner['token']))).status_code, 404)
async def test_video_limit_removes_partial_file(self):
user = await register(self.client, 'tutoriallimit')
with patch.object(self.m.center, 'MAX_TUTORIAL_BYTES', 5):
response = await self.upload(user)
self.assertEqual(response.status_code, 413)
self.assertEqual(list((self.root / 'uploads' / 'tutorials').glob('*')), [])