feat: 完善课表档案、课件归档、提醒与客户端更新并发布 1.4.1
- 重写课表档案工作区并合并时间表、课表与完整档案导入导出 - 修复课前/上下课提醒遮罩与通知收回冲突 - 增加课件文件夹分类、教师归档路径和客户端本机归档 - 打通客户端下载/安装/完成状态上报并在管理端展示更新过程 - 修复侧栏折叠裁切、课时多选与上传控件样式 - 统一版本到 1.4.1
This commit is contained in:
1 parent
2612a912ef
commit
6347d1e5aa
59 files changed
+2251
-584
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@classhelper/desktop-client",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"private": true,
|
||||
"description": "ClassHelper EXE 客户端(Electron + Vue 3 + Element Plus + Socket.IO + IndexedDB 离线缓存)",
|
||||
"author": "Class Helper",
|
||||
|
||||
@@ -390,7 +390,7 @@ const islandClass = computed(() => ({
|
||||
mode.value === 'hidden' && !appearance.value.idleSliver && !state.value.lessonReminder,
|
||||
'ci-lesson-card': !!state.value.lessonReminder,
|
||||
'message-surface': !!state.value.active && mode.value !== 'hidden' && !state.value.lessonReminder,
|
||||
sliver: mode.value === 'hidden' && appearance.value.idleSliver,
|
||||
sliver: mode.value === 'hidden' && appearance.value.idleSliver && !state.value.lessonReminder,
|
||||
urgent: isUrgent.value,
|
||||
call: isCall.value,
|
||||
homework: isHomework.value,
|
||||
|
||||
@@ -58,6 +58,7 @@ const time = computed(() =>
|
||||
);
|
||||
const regions = ref([0, 0, 0, 0, 0]);
|
||||
let frame = 0;
|
||||
let fallback: ReturnType<typeof setTimeout> | undefined;
|
||||
// ClassIsland SlantedMaskControl:5 个斜切区域、30°偏移、两侧向中央打开,中央向两侧关闭。
|
||||
const polygons = computed(() => {
|
||||
const offset = Math.tan(Math.PI / 6) * 40;
|
||||
@@ -71,12 +72,21 @@ const polygons = computed(() => {
|
||||
});
|
||||
function animateMask() {
|
||||
cancelAnimationFrame(frame);
|
||||
clearTimeout(fallback);
|
||||
const target = mask.value ? 1 : 0;
|
||||
if (!props.motion) {
|
||||
regions.value = [target, target, target, target, target];
|
||||
return;
|
||||
}
|
||||
const from = [...regions.value];
|
||||
// 隐藏窗口恢复或系统合成暂停时 rAF 可能停住,遮罩仍须在有限时间内成为可见实体。
|
||||
fallback = setTimeout(
|
||||
() => {
|
||||
cancelAnimationFrame(frame);
|
||||
regions.value = [target, target, target, target, target];
|
||||
},
|
||||
600 / Math.max(0.25, props.appearance.speed),
|
||||
);
|
||||
const started = performance.now();
|
||||
const delays = mask.value ? [0, 90, 120, 90, 0] : [120, 90, 0, 90, 120];
|
||||
const update = (at: number) => {
|
||||
@@ -109,6 +119,7 @@ onMounted(() => {
|
||||
onUnmounted(() => {
|
||||
observer?.disconnect();
|
||||
cancelAnimationFrame(frame);
|
||||
clearTimeout(fallback);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -137,7 +148,7 @@ onUnmounted(() => {
|
||||
<strong>{{ leftSeconds }}</strong>
|
||||
秒
|
||||
</span>
|
||||
<span v-else class="ci-countdown">课间休息</span>
|
||||
<span v-else class="ci-countdown">{{ reminder.kind === 'on-class' ? '开始上课' : '课间休息' }}</span>
|
||||
<span class="ci-lesson-course">
|
||||
<span>
|
||||
{{
|
||||
@@ -146,8 +157,8 @@ onUnmounted(() => {
|
||||
: '下节课是:'
|
||||
}}
|
||||
</span>
|
||||
<strong>{{ course }}</strong>
|
||||
<small>{{ time }}</small>
|
||||
<strong>{{ course || '今日课程已结束' }}</strong>
|
||||
<small v-if="course">{{ time }}</small>
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
@@ -194,8 +205,8 @@ onUnmounted(() => {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 24px;
|
||||
padding: 0 28px;
|
||||
gap: 12px;
|
||||
padding: 0 14px;
|
||||
white-space: nowrap;
|
||||
transition: opacity var(--ci-duration) ease-in;
|
||||
}
|
||||
@@ -222,6 +233,7 @@ onUnmounted(() => {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.ci-lesson-course small {
|
||||
flex-shrink: 0;
|
||||
font-size: 14px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,26 @@ import {
|
||||
import { getConfig, saveConfig } from './config.js';
|
||||
import { island } from './island.js';
|
||||
import { logger } from './logger.js';
|
||||
import { connectionEvents } from './config-events.js';
|
||||
|
||||
let updateEpoch = 0;
|
||||
let downloadAbort = new AbortController();
|
||||
connectionEvents.on('changed', () => {
|
||||
updateEpoch++;
|
||||
downloadAbort.abort();
|
||||
downloadAbort = new AbortController();
|
||||
policy = null;
|
||||
installationRetryAt = 0;
|
||||
installResultChecked = false;
|
||||
updateProgress = {
|
||||
version: '',
|
||||
stage: 'idle',
|
||||
downloadedBytes: 0,
|
||||
totalBytes: 0,
|
||||
percent: null,
|
||||
error: '',
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 服务端统一下发的自动更新(下载 + 空闲时静默安装)。
|
||||
@@ -28,15 +48,24 @@ import { logger } from './logger.js';
|
||||
* 否则会与"安装器正在覆盖自己"撞车 —— Windows 上正在运行的程序文件是删不掉的)。
|
||||
*/
|
||||
|
||||
let policy: Pick<ClientHeartbeatResponse, 'updateTargetVersion' | 'updateMode' | 'updateNotBefore'> | null =
|
||||
null;
|
||||
let policy:
|
||||
| (Pick<ClientHeartbeatResponse, 'updateTargetVersion' | 'updateMode' | 'updateNotBefore'> & {
|
||||
serverUrl: string;
|
||||
username: string;
|
||||
})
|
||||
| null = null;
|
||||
function policyPath(): string {
|
||||
return path.join(pendingUpdateDir(), 'policy.json');
|
||||
}
|
||||
function loadPolicy(): typeof policy {
|
||||
if (policy) return policy;
|
||||
if (policy)
|
||||
return policy.serverUrl === getConfig().serverUrl && policy.username === getConfig().username
|
||||
? policy
|
||||
: null;
|
||||
try {
|
||||
policy = JSON.parse(fs.readFileSync(policyPath(), 'utf8'));
|
||||
if (policy?.serverUrl !== getConfig().serverUrl || policy?.username !== getConfig().username)
|
||||
policy = null;
|
||||
} catch {
|
||||
/* 尚无下发策略 */
|
||||
}
|
||||
@@ -58,7 +87,23 @@ function removeManagedInstaller(file: string): void {
|
||||
|
||||
/** 每次成功心跳先同步策略;取消或更换目标后旧包不得自行安装。 */
|
||||
export function syncUpdatePolicy(next: ClientHeartbeatResponse): void {
|
||||
if (policy && policy.updateTargetVersion !== next.updateTargetVersion) {
|
||||
installationRetryAt = 0;
|
||||
updateEpoch++;
|
||||
downloadAbort.abort();
|
||||
downloadAbort = new AbortController();
|
||||
updateProgress = {
|
||||
version: next.updateTargetVersion || '',
|
||||
stage: 'idle',
|
||||
downloadedBytes: 0,
|
||||
totalBytes: 0,
|
||||
percent: null,
|
||||
error: '',
|
||||
};
|
||||
}
|
||||
policy = {
|
||||
serverUrl: getConfig().serverUrl,
|
||||
username: getConfig().username,
|
||||
updateTargetVersion: next.updateTargetVersion,
|
||||
updateMode: next.updateMode ?? 'idle',
|
||||
updateNotBefore: next.updateNotBefore ?? null,
|
||||
@@ -86,6 +131,8 @@ export function pendingUpdateDir(): string {
|
||||
let mainWindowHiddenAt: number | null = null;
|
||||
/** 本进程是否已经发起过安装(防止心跳与 hide 事件重复触发) */
|
||||
let installing = false;
|
||||
let installationRetryAt = 0;
|
||||
let installResultChecked = false;
|
||||
let updateProgress: ContractReleaseProgressDto = {
|
||||
version: '',
|
||||
stage: 'idle',
|
||||
@@ -95,12 +142,69 @@ let updateProgress: ContractReleaseProgressDto = {
|
||||
error: '',
|
||||
};
|
||||
export function getUpdateProgress() {
|
||||
if (!installResultChecked) {
|
||||
installResultChecked = true;
|
||||
const resultFile = path.join(pendingUpdateDir(), 'install-result.json');
|
||||
try {
|
||||
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8').replace(/^\uFEFF/, ''));
|
||||
if (
|
||||
result.serverUrl === getConfig().serverUrl &&
|
||||
result.username === getConfig().username &&
|
||||
typeof result.version === 'string' &&
|
||||
result.version === getConfig().pendingUpdateVersion &&
|
||||
isNewerVersion(app.getVersion(), result.version) &&
|
||||
typeof result.error === 'string' &&
|
||||
result.error
|
||||
) {
|
||||
updateProgress = {
|
||||
...updateProgress,
|
||||
version: result.version,
|
||||
stage: 'failed',
|
||||
error: result.error.slice(0, 1000),
|
||||
};
|
||||
installationRetryAt = Date.now() + 5 * 60_000;
|
||||
fs.rmSync(resultFile, { force: true });
|
||||
}
|
||||
} catch {
|
||||
/* 尚未执行安装助手,或上一次已成功。 */
|
||||
}
|
||||
}
|
||||
return { ...updateProgress };
|
||||
}
|
||||
let progressPublishedAt = 0;
|
||||
let reportAt = 0;
|
||||
let reporting: Promise<boolean> = Promise.resolve(true);
|
||||
/** 与心跳分离,按顺序上报;安装前等待该队列完成再退出。 */
|
||||
function reportProgress(): Promise<boolean> {
|
||||
const config = getConfig(),
|
||||
snapshot = getUpdateProgress(),
|
||||
epoch = updateEpoch;
|
||||
if (!config.token || process.env.ELECTRON_SMOKE_TEST === '1') return Promise.resolve(true);
|
||||
reporting = reporting
|
||||
.catch(() => false)
|
||||
.then(async () => {
|
||||
if (epoch !== updateEpoch) return false;
|
||||
try {
|
||||
const response = await fetch(`${config.serverUrl}/api/clients/update-progress`, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${config.token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ deviceKey: config.deviceKey, progress: snapshot }),
|
||||
signal: AbortSignal.timeout(5000),
|
||||
redirect: 'error',
|
||||
});
|
||||
if (!response.ok) logger.warn(`更新进度上报失败:HTTP ${response.status}`);
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
logger.warn(`更新进度上报失败:${String(error)}`);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return reporting;
|
||||
}
|
||||
function publishProgress(patch: Partial<typeof updateProgress>) {
|
||||
const previousStage = updateProgress.stage;
|
||||
updateProgress = { ...updateProgress, ...patch };
|
||||
updateProgress.error = updateProgress.error.slice(0, 1000);
|
||||
updateProgress.percent = updateProgress.totalBytes
|
||||
? Math.min(100, Math.round((updateProgress.downloadedBytes / updateProgress.totalBytes) * 100))
|
||||
: null;
|
||||
@@ -108,6 +212,10 @@ function publishProgress(patch: Partial<typeof updateProgress>) {
|
||||
progressPublishedAt = Date.now();
|
||||
for (const win of BrowserWindow.getAllWindows())
|
||||
if (!win.isDestroyed()) win.webContents.send('client:update-progress', getUpdateProgress());
|
||||
if (previousStage !== updateProgress.stage || Date.now() - reportAt >= 2000) {
|
||||
reportAt = Date.now();
|
||||
void reportProgress();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 退出本进程的回调(由 index.ts 注册成既有的 `quitApp()`)。
|
||||
@@ -175,6 +283,7 @@ export function shouldConsider(version: string): boolean {
|
||||
* - 同一版本已经下载过(`pendingUpdateVersion` 命中且文件还在):跳过下载,直接尝试安装。
|
||||
*/
|
||||
export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: string): Promise<void> {
|
||||
const epoch = updateEpoch;
|
||||
const version = targetVersion.trim() || info.version.trim();
|
||||
if (!shouldConsider(version)) {
|
||||
logger.info(`忽略服务端下发的更新 ${version || '(未指定版本)'}:自动更新已在设置中关闭`);
|
||||
@@ -189,6 +298,13 @@ export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: s
|
||||
if (config.pendingUpdateVersion === version) {
|
||||
const existing = config.pendingUpdateFile;
|
||||
if (existing && fs.existsSync(existing)) {
|
||||
publishProgress({
|
||||
version,
|
||||
stage: 'waiting',
|
||||
downloadedBytes: info.size,
|
||||
totalBytes: info.size,
|
||||
error: '',
|
||||
});
|
||||
logger.info(`更新 ${version} 早已下载完成,直接尝试安装`);
|
||||
await maybeInstallPendingUpdate();
|
||||
return;
|
||||
@@ -222,7 +338,8 @@ export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: s
|
||||
logger.info(`开始下载更新 ${version}(${info.fileName},${formatSize(info.size)})`);
|
||||
const response = await fetch(url, {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
|
||||
signal: AbortSignal.any([AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), downloadAbort.signal]),
|
||||
redirect: 'error',
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`下载失败:HTTP ${response.status}`);
|
||||
@@ -235,13 +352,20 @@ export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: s
|
||||
const handle = await fsp.open(temp, 'w');
|
||||
try {
|
||||
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
|
||||
await handle.write(chunk);
|
||||
let offset = 0;
|
||||
while (offset < chunk.byteLength) {
|
||||
const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset);
|
||||
if (!bytesWritten) throw new Error('更新包写入失败');
|
||||
offset += bytesWritten;
|
||||
}
|
||||
publishProgress({ downloadedBytes: updateProgress.downloadedBytes + chunk.byteLength });
|
||||
}
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
|
||||
if (epoch !== updateEpoch) return;
|
||||
if (info.size > 0 && updateProgress.downloadedBytes !== info.size) throw new Error('更新包长度不匹配');
|
||||
publishProgress({ stage: 'verifying' });
|
||||
const digest = await sha256File(temp);
|
||||
const expected = info.sha256.trim().toLowerCase();
|
||||
@@ -264,7 +388,7 @@ export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: s
|
||||
await fsp.rm(target, { force: true });
|
||||
await fsp.rename(temp, target);
|
||||
publishProgress({ stage: 'waiting' });
|
||||
if (loadPolicy()?.updateTargetVersion !== version) {
|
||||
if (epoch !== updateEpoch || loadPolicy()?.updateTargetVersion !== version) {
|
||||
removeManagedInstaller(target);
|
||||
return;
|
||||
}
|
||||
@@ -277,6 +401,7 @@ export async function considerUpdate(info: ClientUpdateInfoDto, targetVersion: s
|
||||
await maybeInstallPendingUpdate();
|
||||
} catch (error) {
|
||||
await fsp.rm(temp, { force: true }).catch(() => undefined);
|
||||
if (epoch !== updateEpoch) return;
|
||||
publishProgress({ stage: 'failed', error: String(error) });
|
||||
logger.error(`下载更新 ${version} 失败:${error instanceof Error ? error.message : String(error)}`);
|
||||
} finally {
|
||||
@@ -319,6 +444,7 @@ export async function maybeInstallPendingUpdate(): Promise<void> {
|
||||
const courseware = island.getCoursewareTransfer();
|
||||
if (courseware && ['downloading', 'verifying'].includes(courseware.stage)) return;
|
||||
if (installing) return;
|
||||
if (Date.now() < installationRetryAt) return;
|
||||
if (process.env.ELECTRON_SMOKE_TEST === '1') return;
|
||||
|
||||
const config = getConfig();
|
||||
@@ -375,15 +501,36 @@ export async function maybeInstallPendingUpdate(): Promise<void> {
|
||||
}
|
||||
|
||||
installing = true;
|
||||
publishProgress({ stage: 'installing' });
|
||||
const installEpoch = updateEpoch;
|
||||
publishProgress({ version, stage: 'installing', error: '' });
|
||||
const reported = await reporting;
|
||||
if (!reported) {
|
||||
installing = false;
|
||||
publishProgress({ stage: 'waiting', error: '安装前状态尚未送达服务端,等待网络恢复后重试' });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
installEpoch !== updateEpoch ||
|
||||
loadPolicy()?.updateTargetVersion !== version ||
|
||||
getConfig().autoUpdate === false
|
||||
) {
|
||||
installing = false;
|
||||
return;
|
||||
}
|
||||
logger.info(`开始静默安装更新 ${version}:${installer}`);
|
||||
try {
|
||||
const exe = app.getPath('exe');
|
||||
const exe = process.env.PORTABLE_EXECUTABLE_FILE || app.getPath('exe');
|
||||
const quote = (value: string): string => "'" + value.replaceAll("'", "''") + "'";
|
||||
const config = getConfig();
|
||||
const resultFile = path.join(pendingUpdateDir(), 'install-result.json');
|
||||
// 上一次失败的结果不能冒充这一次:安装开始时先清掉,只有本轮失败才重新写入。
|
||||
fs.rmSync(resultFile, { force: true });
|
||||
const script =
|
||||
`$ErrorActionPreference = 'Stop'; Wait-Process -Id ${process.pid} -ErrorAction SilentlyContinue; ` +
|
||||
`$installer = Start-Process -FilePath ${quote(installer)} -ArgumentList '/S','--updated','--force-run' -Wait -PassThru; ` +
|
||||
`if ($installer.ExitCode -ne 0 -and (Test-Path -LiteralPath ${quote(exe)})) { Start-Process -FilePath ${quote(exe)} }`;
|
||||
`$ErrorActionPreference = 'Stop'; try { Wait-Process -Id ${process.pid} -ErrorAction SilentlyContinue; ` +
|
||||
`$installer = Start-Process -FilePath ${quote(installer)} -ArgumentList '/S','--updated','--force-run' -WindowStyle Hidden -Wait -PassThru; ` +
|
||||
`if ($installer.ExitCode -ne 0) { throw ('安装器退出码:' + $installer.ExitCode) } ` +
|
||||
`} catch { @{ version=${quote(version)}; serverUrl=${quote(config.serverUrl)}; username=${quote(config.username)}; error=$_.Exception.Message } | ConvertTo-Json -Compress | Set-Content -LiteralPath ${quote(resultFile)} -Encoding UTF8; ` +
|
||||
`if (Test-Path -LiteralPath ${quote(exe)}) { Start-Process -FilePath ${quote(exe)} -WindowStyle Hidden } }`;
|
||||
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
||||
const child = spawn(
|
||||
'powershell.exe',
|
||||
@@ -408,6 +555,7 @@ export async function maybeInstallPendingUpdate(): Promise<void> {
|
||||
}
|
||||
} catch (error) {
|
||||
installing = false;
|
||||
publishProgress({ stage: 'failed', error: String(error).slice(0, 1000) });
|
||||
logger.error(
|
||||
`启动更新安装失败(将在下次满足安装条件时重试):${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
|
||||
@@ -15,7 +15,12 @@ import {
|
||||
type ClientHeartbeatResponse,
|
||||
type ClientUpdateInfoDto,
|
||||
} from '@classhelper/shared';
|
||||
import { maybeInstallPendingUpdate, considerUpdate, syncUpdatePolicy } from './auto-update.js';
|
||||
import {
|
||||
maybeInstallPendingUpdate,
|
||||
considerUpdate,
|
||||
syncUpdatePolicy,
|
||||
getUpdateProgress,
|
||||
} from './auto-update.js';
|
||||
import { connectionEvents, type ConnectionEvent } from './config-events.js';
|
||||
import { getConfig } from './config.js';
|
||||
import { island } from './island.js';
|
||||
@@ -178,6 +183,7 @@ async function beat(): Promise<void> {
|
||||
autoUpdate: config.autoUpdate !== false,
|
||||
pendingVersion: pendingVersionOrNull(),
|
||||
stateNote: currentStateNote(),
|
||||
updateProgress: getUpdateProgress(),
|
||||
};
|
||||
const response = await fetch(`${config.serverUrl}/api/clients/heartbeat`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -9,6 +9,8 @@ import { app, BrowserWindow, shell } from 'electron';
|
||||
import {
|
||||
COURSEWARE_MAX_BYTES,
|
||||
COURSEWARE_TRANSFER_TIMEOUT_MS,
|
||||
coursewareArchivePath,
|
||||
coursewarePathSegment,
|
||||
type ApiResponse,
|
||||
type CoursewareDto,
|
||||
type CoursewarePushDto,
|
||||
@@ -74,6 +76,34 @@ async function digest(file: string) {
|
||||
for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
interface LocalCourseware {
|
||||
item: CoursewareDto;
|
||||
relativePath: string;
|
||||
}
|
||||
function localFile(root: string, relative: string) {
|
||||
const file = path.resolve(root, relative);
|
||||
if (!file.startsWith(path.resolve(root) + path.sep)) throw new Error('课件路径无效');
|
||||
return file;
|
||||
}
|
||||
async function localRecord(id: string, root = scopeDirectory()): Promise<LocalCourseware | null> {
|
||||
try {
|
||||
return JSON.parse(await fsp.readFile(path.join(root, '.index', `${id}.json`), 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export async function listLocalCourseware(): Promise<CoursewareDto[]> {
|
||||
if (!getConfig().token) return [];
|
||||
const root = scopeDirectory();
|
||||
const startedEpoch = epoch;
|
||||
const names = await fsp.readdir(path.join(root, '.index')).catch(() => []);
|
||||
const result: CoursewareDto[] = [];
|
||||
for (const name of names.filter((name) => /^[a-z0-9-]+\.json$/i.test(name))) {
|
||||
const record = await localRecord(name.slice(0, -5), root);
|
||||
if (record && fs.existsSync(localFile(root, record.relativePath))) result.push(record.item);
|
||||
}
|
||||
return startedEpoch === epoch ? result.sort((a, b) => b.createdAt.localeCompare(a.createdAt)) : [];
|
||||
}
|
||||
export function downloadCourseware(id: string): Promise<void> {
|
||||
checkId(id);
|
||||
const startedEpoch = epoch,
|
||||
@@ -99,10 +129,22 @@ export function downloadCourseware(id: string): Promise<void> {
|
||||
!/^[a-f0-9]{64}$/.test(item.sha256)
|
||||
)
|
||||
throw new Error('课件文件信息无效');
|
||||
const safeName =
|
||||
`_${item.name.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').replace(/[. ]+$/, '')}`.slice(0, 182);
|
||||
const dir = path.join(scopeDirectory(), id),
|
||||
file = path.join(dir, safeName);
|
||||
const root = scopeDirectory();
|
||||
const stored = await localRecord(id, root);
|
||||
let relativePath =
|
||||
stored?.relativePath ||
|
||||
(item.archivePath || coursewareArchivePath(item.teacher.name, new Date(item.createdAt), item.name))
|
||||
.split('/')
|
||||
.map(coursewarePathSegment)
|
||||
.join(path.sep);
|
||||
let file = localFile(root, relativePath);
|
||||
// 同秒、同名文件不得覆盖先前课件;重试通过本地索引始终定位同一文件。
|
||||
if (!stored && fs.existsSync(file)) {
|
||||
const ext = path.extname(file);
|
||||
relativePath = relativePath.slice(0, relativePath.length - ext.length) + ` (${id})` + ext;
|
||||
file = localFile(root, relativePath);
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
partial = `${file}.part`;
|
||||
const base: CoursewareTransfer = {
|
||||
id,
|
||||
@@ -164,6 +206,17 @@ export function downloadCourseware(id: string): Promise<void> {
|
||||
await fsp.rename(partial, file);
|
||||
}
|
||||
if (startedEpoch !== epoch) throw new Error('登录会话已切换');
|
||||
await fsp.mkdir(path.join(root, '.index'), { recursive: true });
|
||||
const indexFile = path.join(root, '.index', `${id}.json`);
|
||||
await fsp.writeFile(
|
||||
`${indexFile}.part`,
|
||||
JSON.stringify({
|
||||
item: { ...item, archivePath: relativePath.split(path.sep).join('/') },
|
||||
relativePath,
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
await fsp.rename(`${indexFile}.part`, indexFile);
|
||||
publish({ ...base, receivedBytes: item.size, progress: 100, stage: 'completed' });
|
||||
} catch (error) {
|
||||
if (partial) await fsp.rm(partial, { force: true }).catch(() => undefined);
|
||||
@@ -232,6 +285,15 @@ export async function pollCourseware() {
|
||||
}
|
||||
export async function revealCourseware(id: string) {
|
||||
checkId(id);
|
||||
if (!getConfig().token) throw new Error('请先登录班级账号');
|
||||
const stored = await localRecord(id);
|
||||
if (stored) {
|
||||
const file = localFile(scopeDirectory(), stored.relativePath);
|
||||
if (fs.existsSync(file)) {
|
||||
shell.showItemInFolder(file);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const dir = path.join(scopeDirectory(), id);
|
||||
const names = await fsp.readdir(dir).catch(() => []);
|
||||
const file = names.find((name) => !name.endsWith('.part'));
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { downloadCourseware, getCoursewareTransfer, pollCourseware, revealCourseware } from './courseware.js';
|
||||
import {
|
||||
downloadCourseware,
|
||||
getCoursewareTransfer,
|
||||
pollCourseware,
|
||||
revealCourseware,
|
||||
listLocalCourseware,
|
||||
} from './courseware.js';
|
||||
import { island } from './island.js';
|
||||
import { getUpdateProgress } from './auto-update.js';
|
||||
import { app, BrowserWindow, ipcMain, shell } from 'electron';
|
||||
@@ -17,7 +23,10 @@ export { IPC_CHANNELS };
|
||||
export function registerIpcHandlers(): void {
|
||||
ipcMain.handle('courseware:download', (_event, id: string) => downloadCourseware(id));
|
||||
ipcMain.handle('courseware:reveal', (_event, id: string) => revealCourseware(id));
|
||||
ipcMain.handle('courseware:sync', () => { void pollCourseware(); });
|
||||
ipcMain.handle('courseware:local-list', () => listLocalCourseware());
|
||||
ipcMain.handle('courseware:sync', () => {
|
||||
void pollCourseware();
|
||||
});
|
||||
ipcMain.handle('courseware:get-progress', () => getCoursewareTransfer());
|
||||
ipcMain.handle('client:get-update-progress', () => getUpdateProgress());
|
||||
ipcMain.handle(IPC_CHANNELS.getConfig, (): DesktopStoredConfig => getConfig());
|
||||
|
||||
@@ -195,7 +195,14 @@ class IslandController {
|
||||
if (JSON.stringify(next) === JSON.stringify(this.lessonCue)) return;
|
||||
this.lessonCue = next;
|
||||
// 触摸窗口先放得下新横条,再下发内容;混合宽高变化也只能增大画布。
|
||||
if (this.lessonShowing) this.syncTouchLayout();
|
||||
if (this.lessonShowing) {
|
||||
// 通知收回的延迟回调不能在课表提醒出现后再隐藏同一扇原生窗口。
|
||||
if (this.closeTimer) clearTimeout(this.closeTimer);
|
||||
this.closeTimer = null;
|
||||
this.cancelFade();
|
||||
this.syncResidentShape(true);
|
||||
this.syncTouchLayout();
|
||||
}
|
||||
this.emit();
|
||||
this.syncWindow();
|
||||
}
|
||||
@@ -1106,6 +1113,10 @@ class IslandController {
|
||||
* 所以"窗口最终会隐藏"的既有断言(含轮询写法)不受影响。
|
||||
*/
|
||||
private finishClose(): void {
|
||||
if (this.lessonShowing || this.coursewareShowing) {
|
||||
this.setState({ mode: 'hidden', reason: null });
|
||||
return;
|
||||
}
|
||||
// 动画期间又来了新消息 / 被显式唤起:这次收回归属于旧的一批,放弃收尾
|
||||
if (this.state.mode !== 'pill' || this.state.reason !== 'closing') return;
|
||||
if (this.state.active || this.state.queued.length > 0) return;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
dayKeyLocal,
|
||||
resolveClassStatus,
|
||||
DEFAULT_LESSON_REMINDERS,
|
||||
type LessonReminderSettings,
|
||||
type IslandLessonReminder,
|
||||
@@ -23,16 +22,18 @@ export class LessonReminderTracker {
|
||||
const at = now.getTime();
|
||||
const keyOf = (s: ScheduleDto, kind: IslandLessonReminder['kind']) =>
|
||||
`${dayKeyLocal(now)}:${s.id}:${s.startTime}:${s.endTime}:${kind}`;
|
||||
const status = resolveClassStatus(schedules, now);
|
||||
const timeAt = (time: string) => {
|
||||
const d = new Date(now);
|
||||
const [h, m] = time.split(':').map(Number);
|
||||
d.setHours(h!, m!, 0, 0);
|
||||
const [h, m, s = 0] = time.split(':').map(Number);
|
||||
d.setHours(h!, m!, s, 0);
|
||||
return d.getTime();
|
||||
};
|
||||
const today = schedules.filter((s) => s.dayOfWeek === (now.getDay() || 7));
|
||||
const current = today.find((s) => s.id === status.current?.scheduleId);
|
||||
const next = today.find((s) => s.id === status.next?.scheduleId);
|
||||
const today = schedules
|
||||
.filter((s) => s.dayOfWeek === (now.getDay() || 7))
|
||||
.sort((a, b) => timeAt(a.startTime) - timeAt(b.startTime));
|
||||
// 已解析日课表只按准确时间比较,避免带秒的课时提前触发或错过上课遮罩。
|
||||
const current = today.find((s) => at >= timeAt(s.startTime) && at < timeAt(s.endTime));
|
||||
const next = today.find((s) => timeAt(s.startTime) > at);
|
||||
const ended = today
|
||||
.filter((s) => at >= timeAt(s.endTime) && at - timeAt(s.endTime) < 12_000)
|
||||
.sort((a, b) => b.endTime.localeCompare(a.endTime))[0];
|
||||
@@ -74,12 +75,14 @@ export class LessonReminderTracker {
|
||||
const entered = this.current?.id === id && at >= this.current.startedAt ? this.current.startedAt : at;
|
||||
const start = timeAt(lesson.startTime);
|
||||
const end = timeAt(lesson.endTime);
|
||||
// 导入的 ClassIsland 时间点可能带秒;提醒条只显示到分钟,宽度保持稳定。
|
||||
const clock = (value: string) => value.slice(0, 5);
|
||||
return (this.current = {
|
||||
id,
|
||||
kind,
|
||||
courseName: lesson.course?.name || '课程',
|
||||
startTime: lesson.startTime,
|
||||
endTime: lesson.endTime,
|
||||
startTime: clock(lesson.startTime),
|
||||
endTime: clock(lesson.endTime),
|
||||
startedAt: entered,
|
||||
maskUntil:
|
||||
kind === 'ending' || kind === 'in-class'
|
||||
@@ -100,8 +103,8 @@ export class LessonReminderTracker {
|
||||
lessonStartsAt: start,
|
||||
lessonEndsAt: end,
|
||||
nextCourseName: kind === 'break' ? next?.course?.name : undefined,
|
||||
nextStartTime: kind === 'break' ? next?.startTime : undefined,
|
||||
nextEndTime: kind === 'break' ? next?.endTime : undefined,
|
||||
nextStartTime: kind === 'break' && next ? clock(next.startTime) : undefined,
|
||||
nextEndTime: kind === 'break' && next ? clock(next.endTime) : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { app } from 'electron';
|
||||
import type { CoursewareDto } from '@classhelper/shared';
|
||||
import { defaultIslandLayouts } from '@classhelper/shared';
|
||||
import { getConfig, saveConfig } from './config.js';
|
||||
import { downloadCourseware, getCoursewareTransfer } from './courseware.js';
|
||||
import { downloadCourseware, getCoursewareTransfer, listLocalCourseware } from './courseware.js';
|
||||
import { island } from './island.js';
|
||||
export async function verifyCoursewareSmoke(
|
||||
check: (name: string, action: () => Promise<boolean | string> | boolean) => Promise<void>,
|
||||
@@ -93,7 +93,7 @@ export async function verifyCoursewareSmoke(
|
||||
});
|
||||
await job;
|
||||
await check('课件校验完成后保存正式文件并显示完成', async () => {
|
||||
const files = await localFiles();
|
||||
const files = (await localFiles()).filter((file) => file.endsWith('.pptx'));
|
||||
return (
|
||||
getCoursewareTransfer()?.stage === 'completed' &&
|
||||
getCoursewareTransfer()?.progress === 100 &&
|
||||
@@ -101,6 +101,18 @@ export async function verifyCoursewareSmoke(
|
||||
(await fs.readFile(files[0]!)).equals(bytes)
|
||||
);
|
||||
});
|
||||
await check('本机归档索引支持离线浏览且路径按教师年月日时间分类', async () => {
|
||||
const saved = await listLocalCourseware();
|
||||
const files = (await localFiles()).filter((file) => file.endsWith('.pptx'));
|
||||
return (
|
||||
saved.some((local) => local.id === item.id) &&
|
||||
files.some((file) =>
|
||||
/Teachers[\\/]临时课件教师[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/]\d{2}-\d{2}-\d{2}[\\/]课件接收验证\.pptx$/.test(
|
||||
file,
|
||||
),
|
||||
)
|
||||
);
|
||||
});
|
||||
await check('已完整接收的相同课件不重复传输', async () => {
|
||||
await downloadCourseware(item.id);
|
||||
return downloads === 1;
|
||||
|
||||
@@ -558,7 +558,15 @@ export async function verifyResidentSmoke(
|
||||
await pause(800);
|
||||
if (island.getState().lessonReminder?.kind !== 'prepare') return false;
|
||||
const mask = await win.webContents.executeJavaScript(
|
||||
`(() => {const cue=document.querySelector('${layout === 'custom' ? '.resident-lesson-page' : '.ci-fixed-lesson'} .ci-mask')||document.querySelector('.ci-fixed-lesson .ci-mask');return Boolean(cue&&cue.querySelectorAll('polygon').length===5);})()`,
|
||||
`(() => {
|
||||
const cue=document.querySelector('${layout === 'custom' ? '.resident-lesson-page' : '.ci-fixed-lesson'} .ci-mask')||document.querySelector('.ci-fixed-lesson .ci-mask');
|
||||
if (!cue || cue.querySelectorAll('polygon').length !== 5) return false;
|
||||
const card=cue.closest('.ci-lesson'), title=card?.querySelector('.ci-mask-title');
|
||||
const bounds=card?.getBoundingClientRect(), painted=cue.getBBox();
|
||||
let opacity=1, node=card;
|
||||
while(node&&node!==document.body){const style=getComputedStyle(node);if(style.visibility==='hidden'||style.display==='none')return false;opacity*=Number(style.opacity);node=node.parentElement;}
|
||||
return Boolean(bounds&&bounds.width>=290&&bounds.height>=39&&painted.width>=bounds.width*.9&&title&&Number(getComputedStyle(title).opacity)>.8&&opacity>.8);
|
||||
})()`,
|
||||
);
|
||||
if (!mask) return false;
|
||||
await shot('lesson-prepare-mask-' + layout);
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { ReleaseProgressDto as ContractReleaseProgressDto, CoursewareTransfer } from '@classhelper/shared';
|
||||
import type {
|
||||
ReleaseProgressDto as ContractReleaseProgressDto,
|
||||
CoursewareTransfer,
|
||||
} from '@classhelper/shared';
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
import { IPC_CHANNELS, UPDATE_AVAILABLE_CHANNEL } from '../main/channels.js';
|
||||
import type { ClientAgentStatus } from '../main/client-agent.js';
|
||||
@@ -22,6 +25,7 @@ import type { IslandNotification, UpdateInfo } from '@classhelper/shared';
|
||||
const bridge: DesktopBridge = {
|
||||
downloadCourseware: (id) => ipcRenderer.invoke('courseware:download', id),
|
||||
revealCourseware: (id) => ipcRenderer.invoke('courseware:reveal', id),
|
||||
listLocalCourseware: () => ipcRenderer.invoke('courseware:local-list'),
|
||||
syncCourseware: () => ipcRenderer.invoke('courseware:sync'),
|
||||
getCoursewareTransfer: () => ipcRenderer.invoke('courseware:get-progress'),
|
||||
onCoursewareTransfer: (handler) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue';
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import {
|
||||
COURSEWARE_CATEGORIES,
|
||||
@@ -12,6 +12,27 @@ import { fetchWithCache } from '../cache/index.js';
|
||||
import { getCacheScope } from '../cache/scope.js';
|
||||
import { useRealtimeStore } from '../stores/realtime.js';
|
||||
const realtime = useRealtimeStore();
|
||||
const localItems = ref<CoursewareDto[]>([]),
|
||||
library = ref<'shared' | 'local'>('shared'),
|
||||
teacher = ref(''),
|
||||
archive = ref('');
|
||||
const source = computed(() => (library.value === 'local' ? localItems.value : items.value));
|
||||
const teachers = computed(() => [...new Set(source.value.map((item) => item.teacher.name))]);
|
||||
const archiveFolders = computed(() => [
|
||||
...new Set(
|
||||
source.value
|
||||
.filter((item) => !teacher.value || item.teacher.name === teacher.value)
|
||||
.map((item) => item.archivePath?.split('/').slice(0, -1).join('/') || item.archiveDate),
|
||||
),
|
||||
]);
|
||||
async function refreshLocal() {
|
||||
localItems.value = (await window.desktop?.listLocalCourseware()) || [];
|
||||
}
|
||||
// 两个来源的教师与目录不通用,切换时清空,避免看到空列表却找不到原因。
|
||||
watch(library, () => {
|
||||
teacher.value = '';
|
||||
archive.value = '';
|
||||
});
|
||||
const items = ref<CoursewareDto[]>([]),
|
||||
loading = ref(false),
|
||||
offline = ref(false),
|
||||
@@ -22,15 +43,19 @@ const query = ref(''),
|
||||
busy = ref<string[]>([]),
|
||||
transfer = ref<CoursewareTransfer | null>(null);
|
||||
const filtered = computed(() =>
|
||||
items.value.filter(
|
||||
source.value.filter(
|
||||
(item) =>
|
||||
(!query.value || `${item.name} ${item.teacher.name}`.includes(query.value)) &&
|
||||
(!category.value || item.category === category.value) &&
|
||||
(!teacher.value || item.teacher.name === teacher.value) &&
|
||||
(!archive.value ||
|
||||
(item.archivePath?.startsWith(archive.value + '/') ?? item.archiveDate === archive.value)) &&
|
||||
(!date.value || item.archiveDate === date.value),
|
||||
),
|
||||
);
|
||||
let disposed = false;
|
||||
async function refresh() {
|
||||
await refreshLocal();
|
||||
const scope = getCacheScope();
|
||||
loading.value = true;
|
||||
try {
|
||||
@@ -53,6 +78,7 @@ async function download(item: CoursewareDto) {
|
||||
busy.value.push(item.id);
|
||||
try {
|
||||
await window.desktop.downloadCourseware(item.id);
|
||||
await refreshLocal();
|
||||
ElMessage.success('课件已下载,可打开所在文件夹');
|
||||
} catch (e) {
|
||||
ElMessage.error(e instanceof Error ? e.message : String(e));
|
||||
@@ -77,6 +103,7 @@ onMounted(() => {
|
||||
timer = setInterval(() => void refresh(), 30000);
|
||||
offProgress = window.desktop?.onCoursewareTransfer((value) => {
|
||||
transfer.value = value;
|
||||
if (value?.stage === 'completed') void refreshLocal();
|
||||
});
|
||||
void window.desktop?.getCoursewareTransfer().then((value) => {
|
||||
if (!disposed) transfer.value = value;
|
||||
@@ -122,6 +149,16 @@ onUnmounted(() => {
|
||||
<p v-if="transfer.error">{{ transfer.error }}</p>
|
||||
</el-card>
|
||||
<div class="filters">
|
||||
<el-radio-group v-model="library">
|
||||
<el-radio-button value="shared">班级共享</el-radio-button>
|
||||
<el-radio-button value="local">本机归档</el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-select v-model="teacher" clearable placeholder="全部教师" @change="archive = ''">
|
||||
<el-option v-for="name in teachers" :key="name" :label="name" :value="name" />
|
||||
</el-select>
|
||||
<el-select v-model="archive" clearable filterable placeholder="年 / 月 / 日 / 时间">
|
||||
<el-option v-for="folder in archiveFolders" :key="folder" :label="folder" :value="folder" />
|
||||
</el-select>
|
||||
<el-input v-model="query" clearable placeholder="搜索课件或教师" />
|
||||
<el-select v-model="category" clearable placeholder="全部类型">
|
||||
<el-option v-for="(label, key) in COURSEWARE_CATEGORIES" :key="key" :label="label" :value="key" />
|
||||
@@ -129,8 +166,12 @@ onUnmounted(() => {
|
||||
<el-date-picker v-model="date" value-format="YYYY-MM-DD" placeholder="归档日期" />
|
||||
</div>
|
||||
<el-card shadow="never" class="table-card" v-loading="loading">
|
||||
<el-table :data="filtered" empty-text="老师还没有向本班共享课件">
|
||||
<el-table
|
||||
:data="filtered"
|
||||
:empty-text="library === 'local' ? '本机还没有已归档的课件' : '老师还没有向本班共享课件'"
|
||||
>
|
||||
<el-table-column prop="name" label="课件名称" min-width="200" show-overflow-tooltip />
|
||||
<el-table-column prop="archivePath" label="归档路径" min-width="250" show-overflow-tooltip />
|
||||
<el-table-column label="类型" min-width="110">
|
||||
<template #default="{ row }">
|
||||
{{ COURSEWARE_CATEGORIES[(row as CoursewareDto).category] }} · {{ row.extension || '无扩展名' }}
|
||||
@@ -143,7 +184,13 @@ onUnmounted(() => {
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" :loading="busy.includes(row.id)" @click="download(row)">
|
||||
<el-button
|
||||
v-if="library === 'shared'"
|
||||
link
|
||||
type="primary"
|
||||
:loading="busy.includes(row.id)"
|
||||
@click="download(row)"
|
||||
>
|
||||
下载
|
||||
</el-button>
|
||||
<el-button link @click="reveal(row.id)">打开文件夹</el-button>
|
||||
|
||||
@@ -119,6 +119,7 @@ export interface IslandClassStatePayload {
|
||||
export interface DesktopBridge {
|
||||
downloadCourseware(id: string): Promise<void>;
|
||||
revealCourseware(id: string): Promise<void>;
|
||||
listLocalCourseware(): Promise<import('@classhelper/shared').CoursewareDto[]>;
|
||||
syncCourseware(): Promise<void>;
|
||||
getCoursewareTransfer(): Promise<import('@classhelper/shared').CoursewareTransfer | null>;
|
||||
onCoursewareTransfer(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@classhelper/server",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"private": true,
|
||||
"description": "ClassHelper后端服务:REST API + Socket.IO 实时推送 + Prisma 数据访问",
|
||||
"type": "module",
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
ALTER TABLE "Courseware" ADD COLUMN "archivePath" TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE "Courseware" ADD COLUMN "folderPath" TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE "ClientDevice" ADD COLUMN "updateProgress" TEXT NOT NULL DEFAULT '';
|
||||
CREATE TABLE "CoursewareFolder" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"ownerId" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
CREATE UNIQUE INDEX "CoursewareFolder_ownerId_path_key" ON "CoursewareFolder"("ownerId", "path");
|
||||
@@ -35,6 +35,7 @@ datasource db {
|
||||
/// 账号:管理员 / 教师 / ClassHelper 班级端。**学生不在这里**(见 Student)。
|
||||
model User {
|
||||
coursewares Courseware[]
|
||||
coursewareFolders CoursewareFolder[]
|
||||
id String @id @default(cuid())
|
||||
/// 登录名:教师即**工号**,班级端即班级码
|
||||
username String @unique
|
||||
@@ -530,6 +531,7 @@ model ClientDevice {
|
||||
lastIp String @default("")
|
||||
/// 客户端上报的当前状态说明(如"上课中/已隐藏",仅展示用)
|
||||
stateNote String @default("")
|
||||
updateProgress String @default("")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -730,6 +732,8 @@ model Courseware {
|
||||
category String
|
||||
extension String
|
||||
archiveDate String
|
||||
archivePath String @default("")
|
||||
folderPath String @default("")
|
||||
storagePath String @unique
|
||||
sha256 String
|
||||
createdAt DateTime @default(now())
|
||||
@@ -739,6 +743,15 @@ model Courseware {
|
||||
@@index([ownerId, createdAt])
|
||||
}
|
||||
|
||||
/// 教师自建目录与文件可见权限分开;目录本身不授予班级访问权。
|
||||
model CoursewareFolder {
|
||||
id String @id @default(cuid())
|
||||
ownerId String
|
||||
path String
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
@@unique([ownerId, path])
|
||||
}
|
||||
|
||||
model CoursewareVisibility {
|
||||
coursewareId String
|
||||
classId String
|
||||
|
||||
@@ -25,6 +25,24 @@ if (!dbEntry) {
|
||||
|
||||
/** 需要保证存在的列(新增迁移时在这里追加一行) */
|
||||
const COLUMNS = [
|
||||
{
|
||||
table: 'Courseware',
|
||||
column: 'archivePath',
|
||||
sql: `ALTER TABLE "Courseware" ADD COLUMN "archivePath" TEXT NOT NULL DEFAULT ''`,
|
||||
note: '上传日期归档路径',
|
||||
},
|
||||
{
|
||||
table: 'Courseware',
|
||||
column: 'folderPath',
|
||||
sql: `ALTER TABLE "Courseware" ADD COLUMN "folderPath" TEXT NOT NULL DEFAULT ''`,
|
||||
note: '自建分类目录',
|
||||
},
|
||||
{
|
||||
table: 'ClientDevice',
|
||||
column: 'updateProgress',
|
||||
sql: `ALTER TABLE "ClientDevice" ADD COLUMN "updateProgress" TEXT NOT NULL DEFAULT ''`,
|
||||
note: '设备更新进度',
|
||||
},
|
||||
{
|
||||
table: 'Schedule',
|
||||
column: 'weekParity',
|
||||
|
||||
@@ -91,7 +91,7 @@ async function request(route: string, token = tokens[0], body?: unknown, method
|
||||
}
|
||||
const bytes = Buffer.from('ClassHelper 课件流式上传验收\n'.repeat(3000));
|
||||
async function upload(
|
||||
options: Partial<{ name: string; size: number; classIds: string[]; mode: string }> = {},
|
||||
options: Partial<{ name: string; size: number; classIds: string[]; mode: string; folderPath: string }> = {},
|
||||
token = tokens[0],
|
||||
data = bytes,
|
||||
) {
|
||||
@@ -166,10 +166,42 @@ try {
|
||||
check('API 不暴露服务端路径', !('storagePath' in item));
|
||||
const stored = await prisma.courseware.findUniqueOrThrow({ where: { id: item.id } });
|
||||
check(
|
||||
'文件按日期和类型保存',
|
||||
stored.storagePath.startsWith(path.join(item.archiveDate, 'presentation')) &&
|
||||
'文件按教师、年、月、日、上传时间保存',
|
||||
/^Teachers\/课件教师甲\/\d{4}\/\d{2}\/\d{2}\/\d{2}-\d{2}-\d{2}\/第1课 演示\.pptx$/.test(
|
||||
item.archivePath || '',
|
||||
) &&
|
||||
stored.storagePath.endsWith(path.join(...item.archivePath!.split('/'))) &&
|
||||
(await fs.readFile(path.join(process.env.COURSEWARE_DIR!, stored.storagePath))).equals(bytes),
|
||||
);
|
||||
const folder = await request('/courseware/folders', tokens[0], { path: '地理/必修一' });
|
||||
check('教师可创建多层分类文件夹', folder.status === 201 && folder.data.path === '地理/必修一');
|
||||
check('文件夹按教师隔离', (await request('/courseware/folders', tokens[1])).data.length === 0);
|
||||
check(
|
||||
'拒绝目录穿越文件夹',
|
||||
(await request('/courseware/folders', tokens[0], { path: '../越界' })).status === 422,
|
||||
);
|
||||
check(
|
||||
'班级不能创建文件夹',
|
||||
(await request('/courseware/folders', classTokens[0], { path: '越权' })).status === 403,
|
||||
);
|
||||
const moved = await request(
|
||||
`/courseware/${item.id}/folder`,
|
||||
tokens[0],
|
||||
{ folderPath: folder.data.path },
|
||||
'PATCH',
|
||||
);
|
||||
check(
|
||||
'课件可分类到自建文件夹且日期归档保持稳定',
|
||||
moved.data.folderPath === folder.data.path && moved.data.archivePath === item.archivePath,
|
||||
);
|
||||
check(
|
||||
'不能借用其他教师文件夹上传',
|
||||
(await upload({ folderPath: folder.data.path, classIds: [] }, tokens[1])).status === 400,
|
||||
);
|
||||
check(
|
||||
'不能移动其他教师课件',
|
||||
(await request(`/courseware/${item.id}/folder`, tokens[1], { folderPath: '' }, 'PATCH')).status === 403,
|
||||
);
|
||||
check(
|
||||
'班级仅看到自己可见的课件',
|
||||
(await list(classTokens[0]!)).length === 1 && (await list(classTokens[1]!)).length === 0,
|
||||
@@ -266,6 +298,83 @@ try {
|
||||
});
|
||||
check('收回写权限立即禁止上传', (await upload()).status === 403);
|
||||
await prisma.permissionGroupItem.create({ data: { groupId: defaultGroup.id, key: 'courseware:write' } });
|
||||
const device = await prisma.clientDevice.findUniqueOrThrow({ where: { deviceKey: 'courseware-device-1' } });
|
||||
await prisma.clientDevice.update({ where: { id: device.id }, data: { updateTargetVersion: '2.0.0' } });
|
||||
const updateProgress = {
|
||||
version: '2.0.0',
|
||||
stage: 'downloading',
|
||||
downloadedBytes: 50,
|
||||
totalBytes: 100,
|
||||
percent: 50,
|
||||
error: '',
|
||||
};
|
||||
check(
|
||||
'客户端可上报更新下载进度',
|
||||
(
|
||||
await request('/clients/update-progress', classTokens[0], {
|
||||
deviceKey: device.deviceKey,
|
||||
progress: updateProgress,
|
||||
})
|
||||
).status === 200,
|
||||
);
|
||||
check(
|
||||
'其他班级不能冒报设备更新进度',
|
||||
(
|
||||
await request('/clients/update-progress', classTokens[1], {
|
||||
deviceKey: device.deviceKey,
|
||||
progress: updateProgress,
|
||||
})
|
||||
).status === 403,
|
||||
);
|
||||
await request('/clients/update-progress', classTokens[0], {
|
||||
deviceKey: device.deviceKey,
|
||||
progress: { ...updateProgress, stage: 'installing', percent: 100 },
|
||||
});
|
||||
await request('/clients/update-progress', classTokens[0], {
|
||||
deviceKey: device.deviceKey,
|
||||
progress: updateProgress,
|
||||
});
|
||||
let state = await prisma.clientDevice.findUniqueOrThrow({ where: { id: device.id } });
|
||||
check('迟到的下载状态不覆盖安装中状态', JSON.parse(state.updateProgress).stage === 'installing');
|
||||
await request('/clients/heartbeat', classTokens[0], {
|
||||
deviceKey: device.deviceKey,
|
||||
clientVersion: '2.0.0',
|
||||
});
|
||||
state = await prisma.clientDevice.findUniqueOrThrow({ where: { id: device.id } });
|
||||
check(
|
||||
'新版上线心跳确认完成并记录实际版本',
|
||||
JSON.parse(state.updateProgress).stage === 'completed' &&
|
||||
JSON.parse(state.updateProgress).version === '2.0.0',
|
||||
);
|
||||
await prisma.clientDevice.update({
|
||||
where: { id: device.id },
|
||||
data: { updateTargetVersion: '', updateProgress: '' },
|
||||
});
|
||||
await request('/clients/update-progress', classTokens[0], {
|
||||
deviceKey: device.deviceKey,
|
||||
progress: updateProgress,
|
||||
});
|
||||
state = await prisma.clientDevice.findUniqueOrThrow({ where: { id: device.id } });
|
||||
check('取消目标后忽略旧任务进度', state.updateProgress === '');
|
||||
const teacherDeviceKey = 'courseware-teacher-device';
|
||||
await request('/clients/heartbeat', tokens[0], { deviceKey: teacherDeviceKey, clientVersion: '1.0.0' });
|
||||
let teacherDevice = await prisma.clientDevice.findUniqueOrThrow({ where: { deviceKey: teacherDeviceKey } });
|
||||
check('教师电脑设备不绑定班级', teacherDevice.classId === null);
|
||||
await prisma.clientDevice.update({
|
||||
where: { id: teacherDevice.id },
|
||||
data: { updateTargetVersion: '2.0.0' },
|
||||
});
|
||||
check(
|
||||
'教师电脑可上报自己的更新进度',
|
||||
(
|
||||
await request('/clients/update-progress', tokens[0], {
|
||||
deviceKey: teacherDeviceKey,
|
||||
progress: { ...updateProgress, version: '2.0.0' },
|
||||
})
|
||||
).status === 200,
|
||||
);
|
||||
teacherDevice = await prisma.clientDevice.findUniqueOrThrow({ where: { deviceKey: teacherDeviceKey } });
|
||||
check('教师电脑更新进度已记录', JSON.parse(teacherDevice.updateProgress).stage === 'downloading');
|
||||
const snapshot = await exportSnapshot(prisma, 'sqlite');
|
||||
check(
|
||||
'备份包含课件、可见范围、推送和回执',
|
||||
@@ -275,7 +384,13 @@ try {
|
||||
snapshot.data.CoursewareVisibility.length > 0,
|
||||
);
|
||||
const oldSnapshot = structuredClone(snapshot);
|
||||
for (const key of ['Courseware', 'CoursewarePush', 'CoursewareReceipt', 'CoursewareVisibility'])
|
||||
for (const key of [
|
||||
'Courseware',
|
||||
'CoursewareFolder',
|
||||
'CoursewarePush',
|
||||
'CoursewareReceipt',
|
||||
'CoursewareVisibility',
|
||||
])
|
||||
delete (oldSnapshot.data as Record<string, unknown>)[key];
|
||||
assertValidSnapshot(oldSnapshot);
|
||||
check('允许读取升级前的旧版快照', true);
|
||||
@@ -319,7 +434,9 @@ try {
|
||||
await restoreSnapshot(prisma, 'sqlite', snapshot);
|
||||
check(
|
||||
'恢复数据库后保留课件共享和回执数据',
|
||||
(await prisma.courseware.count()) === 3 && (await prisma.coursewareReceipt.count()) === 1,
|
||||
(await prisma.courseware.count()) === 3 &&
|
||||
(await prisma.coursewareReceipt.count()) === 1 &&
|
||||
(await prisma.coursewareFolder.count()) === 1,
|
||||
);
|
||||
console.log(`=== 课件隔离验收:${count}/${count} 项通过 ===`);
|
||||
} finally {
|
||||
|
||||
@@ -3223,6 +3223,7 @@ async function main() {
|
||||
'AppSetting',
|
||||
'ClientDevice',
|
||||
'Courseware',
|
||||
'CoursewareFolder',
|
||||
'CoursewareVisibility',
|
||||
'CoursewarePush',
|
||||
'CoursewareReceipt',
|
||||
|
||||
@@ -421,6 +421,27 @@ try {
|
||||
assert.equal(rows[0].weekCountDivTotal, 4);
|
||||
assert.equal(rows[0].layout.points.length, 4);
|
||||
});
|
||||
const archive = await request(`/class-plans/profile?classId=${cls.id}`);
|
||||
const beforeArchive = imported.find((p: { name: string }) => p.name === '上游四周');
|
||||
const exportedPlan = archive.ClassPlans[beforeArchive.id];
|
||||
check('完整档案导出保留四种时间点、空课位置与轮换规则', () => {
|
||||
assert.equal(archive.TimeLayouts[exportedPlan.TimeLayoutId].Layouts.length, 4);
|
||||
assert.equal(exportedPlan.TimeRule.WeekCountDivTotal, 4);
|
||||
assert.equal(
|
||||
exportedPlan.Classes.length,
|
||||
beforeArchive.layout.points.filter((p: { timeType: string }) => p.timeType === 'LESSON').length,
|
||||
);
|
||||
});
|
||||
await request('/class-plans/import/profile', 'POST', { classId: cls.id, payload: archive }, undefined, 201);
|
||||
const afterArchive = await request(`/class-plans?classId=${cls.id}`);
|
||||
check('导出档案可重新导入且保留课程与周次范围', () => {
|
||||
const restored = afterArchive.find(
|
||||
(p: { id: string; name: string }) => p.name === '上游四周' && p.id !== beforeArchive.id,
|
||||
);
|
||||
assert.equal(restored.weekStart, beforeArchive.weekStart);
|
||||
assert.equal(restored.weekEnd, beforeArchive.weekEnd);
|
||||
assert.equal(restored.entries.length, beforeArchive.entries.length);
|
||||
});
|
||||
let enabled = false;
|
||||
const os = {
|
||||
platform: 'win32',
|
||||
|
||||
@@ -60,6 +60,7 @@ export const SNAPSHOT_TABLES = [
|
||||
'Grade',
|
||||
'ClientDevice',
|
||||
'Courseware',
|
||||
'CoursewareFolder',
|
||||
'CoursewareVisibility',
|
||||
'CoursewarePush',
|
||||
'CoursewareReceipt',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { importProfile } from './profile-import.service.js';
|
||||
import { exportProfile } from './profile-export.service.js';
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
@@ -82,6 +83,9 @@ layouts.delete(
|
||||
|
||||
const plans = Router();
|
||||
plans.use(authenticate());
|
||||
plans.get('/profile', validate({ query: z.object({ classId: z.string().min(1) }) }), async (req, res) =>
|
||||
sendOk(res, await exportProfile(getAuthUser(req), validatedQuery<{ classId: string }>(req).classId)),
|
||||
);
|
||||
plans.post(
|
||||
'/import/profile',
|
||||
requirePermission('schedule:write'),
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { assertClassAccess } from '../../lib/access.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
|
||||
/** 按时间点外键生成完整档案,空课、停用课程与非上课时间点均保留。 */
|
||||
export async function exportProfile(user: TokenPayload, classId: string) {
|
||||
await assertClassAccess(user, classId);
|
||||
const [cls, layouts, plans, subjects, groups, scheduled, setting] = await Promise.all([
|
||||
prisma.class.findUniqueOrThrow({ where: { id: classId } }),
|
||||
prisma.timeLayout.findMany({
|
||||
where: { OR: [{ classId }, { classId: null }] },
|
||||
include: { points: { orderBy: { position: 'asc' } } },
|
||||
}),
|
||||
prisma.classPlan.findMany({ where: { classId }, include: { entries: true } }),
|
||||
prisma.course.findMany({ where: { classId } }),
|
||||
prisma.classPlanGroup.findMany({ where: { classId } }),
|
||||
prisma.scheduledClassPlan.findMany({ where: { classId } }),
|
||||
prisma.appSetting.findUnique({ where: { key: `schedule.group.${classId}` } }),
|
||||
]);
|
||||
let selection: {
|
||||
selected?: string;
|
||||
temporary?: string;
|
||||
expireTime?: string;
|
||||
temporaryPlan?: string;
|
||||
temporaryPlanDate?: string;
|
||||
} = {};
|
||||
try {
|
||||
selection = JSON.parse(setting?.value || '{}');
|
||||
} catch {
|
||||
/* 使用默认群组 */
|
||||
}
|
||||
const types = ['LESSON', 'BREAK', 'DIVIDER', 'ACTION'];
|
||||
const actions = (value: string) => {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
return {
|
||||
Name: cls.name,
|
||||
Subjects: Object.fromEntries(
|
||||
subjects.map((s) => [s.id, { Name: s.name, Initial: s.initial, IsOutDoor: s.isOutDoor }]),
|
||||
),
|
||||
TimeLayouts: Object.fromEntries(
|
||||
layouts.map((l) => [
|
||||
l.id,
|
||||
{
|
||||
Name: l.name,
|
||||
IsOverlay: l.isOverlay,
|
||||
OverlaySourceId: l.overlaySourceId,
|
||||
Layouts: l.points.map((p) => ({
|
||||
Name: p.name,
|
||||
StartTime: p.startTime,
|
||||
EndTime: p.endTime,
|
||||
TimeType: types.indexOf(p.timeType),
|
||||
IsHideDefault: p.isHideDefault,
|
||||
DefaultClassId: p.defaultClassId,
|
||||
BreakName: p.breakName,
|
||||
ActionSet: actions(p.actionSet),
|
||||
})),
|
||||
},
|
||||
]),
|
||||
),
|
||||
ClassPlans: Object.fromEntries(
|
||||
plans.map((p) => [
|
||||
p.id,
|
||||
{
|
||||
Name: p.name,
|
||||
TimeLayoutId: p.timeLayoutId,
|
||||
AssociatedGroup: p.associatedGroup,
|
||||
TimeRule: {
|
||||
WeekDay: p.weekday,
|
||||
WeekCountDiv: p.weekCountDiv,
|
||||
WeekCountDivTotal: p.weekCountDivTotal,
|
||||
},
|
||||
WeekStart: p.weekStart,
|
||||
WeekEnd: p.weekEnd,
|
||||
IsEnabled: p.isEnabled,
|
||||
IsOverlay: p.isOverlay,
|
||||
OverlaySourceId: p.overlaySourceId,
|
||||
OverlayDate: p.overlayDate,
|
||||
Classes: (layouts.find((l) => l.id === p.timeLayoutId)?.points || [])
|
||||
.filter((point) => point.timeType === 'LESSON')
|
||||
.map((point) => {
|
||||
const e = p.entries.find((entry) => entry.timeLayoutItemId === point.id);
|
||||
return {
|
||||
SubjectId: e?.courseId || '',
|
||||
IsEnabled: e?.isEnabled ?? true,
|
||||
IsChangedClass: e?.isChangedClass ?? false,
|
||||
Location: e?.location || '',
|
||||
};
|
||||
}),
|
||||
},
|
||||
]),
|
||||
),
|
||||
ClassPlanGroups: Object.fromEntries(groups.map((g) => [g.id, { Name: g.name, IsGlobal: g.isGlobal }])),
|
||||
SelectedClassPlanGroupId: selection.selected || groups.find((g) => g.isDefault)?.id || '',
|
||||
TempClassPlanGroupId: selection.temporary || '',
|
||||
IsTempClassPlanGroupEnabled: !!selection.temporary,
|
||||
TempClassPlanGroupExpireTime: selection.expireTime,
|
||||
TempClassPlanId: selection.temporaryPlan,
|
||||
TempClassPlanSetupTime: selection.temporaryPlanDate,
|
||||
OrderedSchedules: Object.fromEntries(scheduled.map((s) => [s.date, { ClassPlanId: s.classPlanId }])),
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { assertCanManageSchedule } from '../../lib/access.js';
|
||||
import { ApiError } from '../../lib/http.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
import { notifyScheduleChanged } from './class-plans.service.js';
|
||||
import { getMaxTermWeeks } from '../../lib/term.js';
|
||||
const record = z.record(z.string(), z.unknown());
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
const parsed = record.safeParse(value);
|
||||
@@ -39,6 +40,7 @@ export async function importProfile(user: TokenPayload, classId: string, payload
|
||||
if (Object.keys(plans).length > 500 || Object.keys(layouts).length > 100)
|
||||
throw ApiError.badRequest('导入课表过多');
|
||||
const cls = await prisma.class.findUniqueOrThrow({ where: { id: classId } });
|
||||
const maxWeeks = await getMaxTermWeeks();
|
||||
const warnings: string[] = [];
|
||||
const stable = (kind: string, id: string) =>
|
||||
`profile-${kind}-${createHash('sha256')
|
||||
@@ -183,6 +185,14 @@ export async function importProfile(user: TokenPayload, classId: string, payload
|
||||
)
|
||||
throw ApiError.badRequest('导入启用规则不合法(支持1–9周轮换)');
|
||||
const previous = await tx.classPlan.findUnique({ where: { id: stable('plan', id) } });
|
||||
const range = z
|
||||
.object({
|
||||
start: z.number().int().min(1).max(maxWeeks),
|
||||
end: z.number().int().min(1).max(maxWeeks),
|
||||
})
|
||||
.refine((r) => r.start <= r.end)
|
||||
.safeParse({ start: p.WeekStart ?? 1, end: Math.min(Number(p.WeekEnd ?? maxWeeks), maxWeeks) });
|
||||
if (!range.success) throw ApiError.badRequest('导入课表生效周次无效');
|
||||
const data = {
|
||||
classId,
|
||||
name: String(p.Name || '导入课表').slice(0, 64),
|
||||
@@ -191,8 +201,11 @@ export async function importProfile(user: TokenPayload, classId: string, payload
|
||||
weekday,
|
||||
weekCountDiv,
|
||||
weekCountDivTotal,
|
||||
weekStart: range.data.start,
|
||||
weekEnd: range.data.end,
|
||||
isEnabled: p.IsEnabled !== false,
|
||||
isOverlay: p.IsOverlay === true,
|
||||
overlayDate: typeof p.OverlayDate === 'string' && isDayKey(p.OverlayDate) ? p.OverlayDate : null,
|
||||
};
|
||||
const plan = await tx.classPlan.upsert({
|
||||
where: { id: stable('plan', id) },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Router } from 'express';
|
||||
import type { ClientUpdateProgressDto } from '@classhelper/shared';
|
||||
import { sendCreated, sendOk } from '../../lib/http.js';
|
||||
import { idParamSchema } from '../../lib/schemas.js';
|
||||
import { authenticate, getAuthUser, requireAnyPermission, requirePermission } from '../../middleware/auth.js';
|
||||
@@ -7,6 +8,7 @@ import { defineModule } from '../module.types.js';
|
||||
import {
|
||||
clientCommandAckSchema,
|
||||
clientHeartbeatSchema,
|
||||
clientProgressSchema,
|
||||
createClientCommandSchema,
|
||||
listClientDevicesQuerySchema,
|
||||
pushClientUpdateSchema,
|
||||
@@ -20,6 +22,14 @@ import * as clientService from './clients.service.js';
|
||||
|
||||
const router = Router();
|
||||
router.use(authenticate());
|
||||
router.post('/update-progress', validate({ body: clientProgressSchema }), async (req, res) => {
|
||||
const input = validatedBody<{
|
||||
deviceKey: string;
|
||||
progress: ClientUpdateProgressDto;
|
||||
}>(req);
|
||||
await clientService.reportUpdateProgress(getAuthUser(req), input.deviceKey, input.progress);
|
||||
sendOk(res, null);
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/clients/heartbeat - 客户端每 30 秒上报一次
|
||||
|
||||
@@ -11,6 +11,24 @@ const clientCommandKindSchema = z.enum(
|
||||
|
||||
/** 设备标识(客户端主进程生成并持久化的 UUID) */
|
||||
const deviceKeySchema = z.string().trim().min(8, '设备标识不合法').max(80, '设备标识不合法');
|
||||
export const updateProgressSchema = z.object({
|
||||
version: z.string().trim().max(40),
|
||||
stage: z.enum([
|
||||
'idle',
|
||||
'downloading',
|
||||
'verifying',
|
||||
'ready',
|
||||
'waiting',
|
||||
'installing',
|
||||
'failed',
|
||||
'completed',
|
||||
]),
|
||||
downloadedBytes: z.number().int().min(0),
|
||||
totalBytes: z.number().int().min(0),
|
||||
percent: z.number().min(0).max(100).nullable(),
|
||||
error: z.string().max(1000),
|
||||
});
|
||||
export const clientProgressSchema = z.object({ deviceKey: deviceKeySchema, progress: updateProgressSchema });
|
||||
|
||||
/** `POST /api/clients/heartbeat`:客户端每 30 秒一次的上报 */
|
||||
export const clientHeartbeatSchema = z.object({
|
||||
@@ -22,6 +40,7 @@ export const clientHeartbeatSchema = z.object({
|
||||
autoUpdate: z.boolean().optional(),
|
||||
pendingVersion: z.string().trim().max(40).nullable().optional(),
|
||||
stateNote: z.string().trim().max(120).optional(),
|
||||
updateProgress: updateProgressSchema.optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
CLIENT_COMMAND_EXPIRE_MS,
|
||||
CLIENT_COMMAND_LABELS,
|
||||
CLIENT_ONLINE_WINDOW_MS,
|
||||
compareVersions,
|
||||
type ClientUpdateProgressDto,
|
||||
type ClientUpdateMode,
|
||||
type ClientCommandAckRequest,
|
||||
type ClientCommandDto,
|
||||
@@ -47,6 +49,7 @@ type DeviceRow = {
|
||||
lastHeartbeatAt: Date | null;
|
||||
lastIp: string;
|
||||
stateNote: string;
|
||||
updateProgress: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
class?: { id: string; name: string } | null;
|
||||
@@ -153,6 +156,25 @@ export async function heartbeat(
|
||||
})) as unknown as DeviceRow;
|
||||
|
||||
const targetVersion = device.updateTargetVersion.trim();
|
||||
if (targetVersion && input.clientVersion && compareVersions(input.clientVersion, targetVersion) >= 0) {
|
||||
await prisma.clientDevice.updateMany({
|
||||
where: { id: device.id, updateTargetVersion: targetVersion },
|
||||
data: {
|
||||
pendingVersion: '',
|
||||
updateProgress: JSON.stringify({
|
||||
version: input.clientVersion,
|
||||
stage: 'completed',
|
||||
downloadedBytes: 0,
|
||||
totalBytes: 0,
|
||||
percent: 100,
|
||||
error: '',
|
||||
updatedAt: now.toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
} else if (input.updateProgress && input.updateProgress.stage !== 'idle') {
|
||||
await reportUpdateProgress(user, input.deviceKey, input.updateProgress);
|
||||
}
|
||||
const [command, update] = await Promise.all([
|
||||
findPendingCommand(device.id, now),
|
||||
targetVersion ? clientReleases.resolveUpdateInfo(targetVersion) : Promise.resolve(null),
|
||||
@@ -176,6 +198,46 @@ export async function heartbeat(
|
||||
};
|
||||
}
|
||||
|
||||
export async function reportUpdateProgress(
|
||||
user: TokenPayload,
|
||||
deviceKey: string,
|
||||
progress: ClientUpdateProgressDto,
|
||||
) {
|
||||
const device = await prisma.clientDevice.findUnique({ where: { deviceKey } });
|
||||
// 教师/管理员电脑不绑定班级(会话与设备两侧都是 null),同样允许上报自己的进度。
|
||||
if (!device || device.classId !== resolveClassId(user)) throw ApiError.forbidden('设备不属于当前班级');
|
||||
// 已取消或更换目标的迟到进度不得覆盖当前任务。
|
||||
if (progress.version !== device.updateTargetVersion || progress.stage === 'completed') return;
|
||||
const previous = readUpdateProgress(device.updateProgress);
|
||||
if (previous?.version === progress.version && previous.stage === 'completed') return;
|
||||
const stages = ['idle', 'downloading', 'verifying', 'ready', 'waiting', 'installing', 'completed'];
|
||||
if (
|
||||
previous?.version === progress.version &&
|
||||
previous.stage !== 'failed' &&
|
||||
progress.stage !== 'failed' &&
|
||||
!progress.error &&
|
||||
stages.indexOf(progress.stage) < stages.indexOf(previous.stage)
|
||||
)
|
||||
return;
|
||||
await prisma.clientDevice.updateMany({
|
||||
where: {
|
||||
id: device.id,
|
||||
updateTargetVersion: progress.version,
|
||||
updateProgress: device.updateProgress,
|
||||
},
|
||||
data: {
|
||||
updateProgress: JSON.stringify({ ...progress, updatedAt: new Date().toISOString() }),
|
||||
},
|
||||
});
|
||||
}
|
||||
function readUpdateProgress(raw: string): ClientUpdateProgressDto | null {
|
||||
try {
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** POST /api/clients/commands/:id/ack - 客户端执行完远控命令后的回执 */
|
||||
export async function ackCommand(
|
||||
commandId: string,
|
||||
@@ -263,6 +325,7 @@ export async function listDevices(
|
||||
lastHeartbeatAt: heartbeat ? heartbeat.toISOString() : null,
|
||||
lastIp: row.lastIp,
|
||||
stateNote: row.stateNote,
|
||||
updateProgress: readUpdateProgress(row.updateProgress),
|
||||
online: Boolean(heartbeat && now.getTime() - heartbeat.getTime() < CLIENT_ONLINE_WINDOW_MS),
|
||||
pendingCommand: pending ? toCommandDto(pending) : null,
|
||||
lastCommand: last ? toCommandDto(last) : null,
|
||||
@@ -390,6 +453,7 @@ export async function pushUpdate(
|
||||
where: { id: device.id },
|
||||
data: {
|
||||
updateTargetVersion: target,
|
||||
updateProgress: '',
|
||||
updateMode: clear ? 'idle' : input.mode,
|
||||
updateNotBefore:
|
||||
!clear && input.mode === 'after-school'
|
||||
|
||||
@@ -10,7 +10,13 @@ import {
|
||||
} from '../../middleware/auth.js';
|
||||
import { validate, validatedBody, validatedQuery, validatedParams } from '../../middleware/validate.js';
|
||||
import { defineModule } from '../module.types.js';
|
||||
import { coursewareDeviceQuery, coursewareScopeSchema, coursewareUploadQuery } from './courseware.schemas.js';
|
||||
import {
|
||||
coursewareDeviceQuery,
|
||||
coursewareScopeSchema,
|
||||
coursewareUploadQuery,
|
||||
coursewareFolderSchema,
|
||||
coursewareMoveSchema,
|
||||
} from './courseware.schemas.js';
|
||||
import type { CoursewareUploadRequest } from '@classhelper/shared';
|
||||
import * as service from './courseware.service.js';
|
||||
const router = Router();
|
||||
@@ -22,6 +28,26 @@ router.get('/', requireStaffPermission('courseware:read'), async (req, res) =>
|
||||
router.get('/classes', ...staff, async (req, res) =>
|
||||
sendOk(res, await service.teachingClasses(getAuthUser(req))),
|
||||
);
|
||||
router.get('/folders', ...staff, async (req, res) =>
|
||||
sendOk(res, await service.listFolders(getAuthUser(req))),
|
||||
);
|
||||
router.post('/folders', ...staff, validate({ body: coursewareFolderSchema }), async (req, res) =>
|
||||
sendCreated(res, await service.createFolder(getAuthUser(req), validatedBody<{ path: string }>(req).path)),
|
||||
);
|
||||
router.patch(
|
||||
'/:id/folder',
|
||||
...staff,
|
||||
validate({ params: idParamSchema, body: coursewareMoveSchema }),
|
||||
async (req, res) =>
|
||||
sendOk(
|
||||
res,
|
||||
await service.moveCourseware(
|
||||
getAuthUser(req),
|
||||
validatedParams<{ id: string }>(req).id,
|
||||
validatedBody<{ folderPath: string }>(req).folderPath,
|
||||
),
|
||||
),
|
||||
);
|
||||
router.get(
|
||||
'/transfers',
|
||||
requireRole('CLASS_DEVICE'),
|
||||
|
||||
@@ -2,6 +2,27 @@ import { z } from 'zod';
|
||||
import { COURSEWARE_MAX_BYTES } from '@classhelper/shared';
|
||||
|
||||
export const coursewareScopeSchema = z.object({ classIds: z.array(z.string().min(1).max(100)).max(100) });
|
||||
const folderPath = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(240)
|
||||
.refine(
|
||||
(value) =>
|
||||
value
|
||||
.split('/')
|
||||
.every(
|
||||
(part) =>
|
||||
part.length > 0 &&
|
||||
part.length <= 60 &&
|
||||
!/[<>:"\\|?*\u0000-\u001f]/.test(part) &&
|
||||
!/[. ]$/.test(part) &&
|
||||
!/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part),
|
||||
),
|
||||
'文件夹名称无效,请使用 / 分隔子文件夹',
|
||||
);
|
||||
export const coursewareFolderSchema = z.object({ path: folderPath });
|
||||
export const coursewareMoveSchema = z.object({ folderPath: folderPath.or(z.literal('')) });
|
||||
export const coursewareUploadSchema = coursewareScopeSchema
|
||||
.extend({
|
||||
name: z
|
||||
@@ -15,6 +36,7 @@ export const coursewareUploadSchema = coursewareScopeSchema
|
||||
),
|
||||
size: z.number().int().min(1).max(COURSEWARE_MAX_BYTES),
|
||||
mode: z.enum(['cloud', 'push']),
|
||||
folderPath: folderPath.or(z.literal('')).optional(),
|
||||
})
|
||||
.refine((input) => input.mode !== 'push' || input.classIds.length > 0, '推送时请选择授课班级');
|
||||
export const coursewareUploadQuery = z.object({
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { Request } from 'express';
|
||||
import {
|
||||
COURSEWARE_MAX_BYTES,
|
||||
coursewareCategory,
|
||||
coursewareArchivePath,
|
||||
dayKeyLocal,
|
||||
SOCKET_EVENTS,
|
||||
type CoursewareDto,
|
||||
@@ -37,6 +38,8 @@ function dto(row: RecordWithRelations): CoursewareDto {
|
||||
category: row.category as CoursewareDto['category'],
|
||||
extension: row.extension,
|
||||
archiveDate: row.archiveDate,
|
||||
archivePath: row.archivePath || coursewareArchivePath(row.owner.name, row.createdAt, row.name),
|
||||
folderPath: row.folderPath,
|
||||
sha256: row.sha256,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
teacher: row.owner,
|
||||
@@ -104,13 +107,18 @@ export async function listCourseware(user: TokenPayload) {
|
||||
}
|
||||
export async function uploadCourseware(user: TokenPayload, input: CoursewareUploadRequest, req: Request) {
|
||||
const classIds = await validateClasses(user, input.classIds);
|
||||
await assertFolder(user, input.folderPath || '');
|
||||
if (!req.is('application/octet-stream')) throw ApiError.badRequest('请使用二进制文件上传');
|
||||
if (req.headers['content-length'] && Number(req.headers['content-length']) !== input.size)
|
||||
throw ApiError.badRequest('文件长度与上传信息不符');
|
||||
const uploadedAt = new Date();
|
||||
const owner = await prisma.user.findUniqueOrThrow({ where: { id: user.sub }, select: { name: true } });
|
||||
const archivePath = coursewareArchivePath(owner.name, uploadedAt, input.name);
|
||||
const category = coursewareCategory(input.name),
|
||||
archiveDate = dayKeyLocal(new Date());
|
||||
archiveDate = dayKeyLocal(uploadedAt);
|
||||
const extension = path.extname(input.name).slice(1).toLowerCase();
|
||||
const relative = path.join(archiveDate, category, randomUUID());
|
||||
// UUID 隔离同名教师或同秒上传;对外归档路径始终使用上传时的教师名和时间。
|
||||
const relative = path.join(randomUUID(), archivePath);
|
||||
const file = path.join(coursewareRoot, relative),
|
||||
partial = `${file}.part`;
|
||||
await fsp.mkdir(path.dirname(file), { recursive: true });
|
||||
@@ -142,6 +150,9 @@ export async function uploadCourseware(user: TokenPayload, input: CoursewareUplo
|
||||
category,
|
||||
extension,
|
||||
archiveDate,
|
||||
archivePath,
|
||||
folderPath: input.folderPath || '',
|
||||
createdAt: uploadedAt,
|
||||
storagePath: relative,
|
||||
sha256: hash.digest('hex'),
|
||||
visibility: { create: classIds.map((classId) => ({ classId })) },
|
||||
@@ -156,6 +167,35 @@ export async function uploadCourseware(user: TokenPayload, input: CoursewareUplo
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function assertFolder(user: TokenPayload, folderPath: string) {
|
||||
if (
|
||||
folderPath &&
|
||||
!(await prisma.coursewareFolder.findUnique({
|
||||
where: { ownerId_path: { ownerId: user.sub, path: folderPath } },
|
||||
}))
|
||||
)
|
||||
throw ApiError.badRequest('请选择自己创建的文件夹');
|
||||
}
|
||||
export async function listFolders(user: TokenPayload) {
|
||||
const rows = await prisma.coursewareFolder.findMany({
|
||||
where: { ownerId: user.sub },
|
||||
orderBy: { path: 'asc' },
|
||||
});
|
||||
return rows.map((row) => ({ id: row.id, path: row.path }));
|
||||
}
|
||||
export async function createFolder(user: TokenPayload, folderPath: string) {
|
||||
const row = await prisma.coursewareFolder.upsert({
|
||||
where: { ownerId_path: { ownerId: user.sub, path: folderPath } },
|
||||
create: { ownerId: user.sub, path: folderPath },
|
||||
update: {},
|
||||
});
|
||||
return { id: row.id, path: row.path };
|
||||
}
|
||||
export async function moveCourseware(user: TokenPayload, id: string, folderPath: string) {
|
||||
await owned(user, id);
|
||||
await assertFolder(user, folderPath);
|
||||
return dto(await prisma.courseware.update({ where: { id }, data: { folderPath }, include }));
|
||||
}
|
||||
export async function setVisibility(user: TokenPayload, id: string, ids: string[]) {
|
||||
await owned(user, id);
|
||||
const classIds = await validateClasses(user, ids);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@classhelper/shared",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"private": true,
|
||||
"description": "ClassHelper - 三端共享的类型、常量与工具函数",
|
||||
"type": "module",
|
||||
|
||||
@@ -75,6 +75,11 @@ export interface ReleaseProgressDto {
|
||||
percent: number | null;
|
||||
error: string;
|
||||
}
|
||||
/** 设备上报状态与服务端缓存安装包的下载状态分开。 */
|
||||
export interface ClientUpdateProgressDto extends Omit<ReleaseProgressDto, 'stage'> {
|
||||
stage: ReleaseProgressDto['stage'] | 'completed';
|
||||
updatedAt?: string;
|
||||
}
|
||||
export interface CollectiveGradeAnalysisDto {
|
||||
mode: 'collective';
|
||||
classId: string;
|
||||
|
||||
@@ -37,6 +37,9 @@ export interface CoursewareDto {
|
||||
archiveDate: string;
|
||||
sha256: string;
|
||||
createdAt: string;
|
||||
/** 上传时固定的归档相对路径,不含服务端磁盘根目录。 */
|
||||
archivePath?: string;
|
||||
folderPath?: string;
|
||||
teacher: { id: string; name: string };
|
||||
classes: CoursewareClassDto[];
|
||||
}
|
||||
@@ -45,6 +48,34 @@ export interface CoursewareUploadRequest {
|
||||
size: number;
|
||||
classIds: string[];
|
||||
mode: 'cloud' | 'push';
|
||||
folderPath?: string;
|
||||
}
|
||||
export interface CoursewareFolderDto {
|
||||
id: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** 跨平台目录名;保留中文,处理 Windows 保留名与路径分隔符。 */
|
||||
export function coursewarePathSegment(value: string): string {
|
||||
const safe =
|
||||
value
|
||||
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
|
||||
.replace(/[. ]+$/, '')
|
||||
.slice(0, 180) || '_';
|
||||
return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(safe) ? `_${safe}` : safe;
|
||||
}
|
||||
|
||||
export function coursewareArchivePath(teacher: string, uploadedAt: Date, name: string): string {
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return [
|
||||
'Teachers',
|
||||
coursewarePathSegment(teacher),
|
||||
String(uploadedAt.getFullYear()),
|
||||
pad(uploadedAt.getMonth() + 1),
|
||||
pad(uploadedAt.getDate()),
|
||||
[uploadedAt.getHours(), uploadedAt.getMinutes(), uploadedAt.getSeconds()].map(pad).join('-'),
|
||||
coursewarePathSegment(name),
|
||||
].join('/');
|
||||
}
|
||||
export interface CoursewarePushDto {
|
||||
id: string;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { CoursewareTransfer } from './courseware.js';
|
||||
import type {
|
||||
ClientUpdateProgressDto,
|
||||
PermissionScope as ContractPermissionScope,
|
||||
ReleaseProgressDto as ContractReleaseProgressDto,
|
||||
} from './class-plan.js';
|
||||
@@ -1552,6 +1553,7 @@ export interface ClientCommandDto {
|
||||
|
||||
/** Web 端「客户端设备」列表里的一台机器 */
|
||||
export interface ClientDeviceDto {
|
||||
updateProgress?: ClientUpdateProgressDto | null;
|
||||
id: string;
|
||||
classId: string | null;
|
||||
className: string | null;
|
||||
@@ -1590,6 +1592,7 @@ export interface ClientDeviceDto {
|
||||
|
||||
/** `POST /api/clients/heartbeat`:客户端每 30 秒一次的上报 */
|
||||
export interface ClientHeartbeatRequest {
|
||||
updateProgress?: ClientUpdateProgressDto;
|
||||
/** 旧版缺省为 1;第二版正确解析统一响应并支持安装时机。 */
|
||||
agentProtocol?: number;
|
||||
deviceKey: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@classhelper/web-admin",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"private": true,
|
||||
"description": "ClassHelper Web 管理端(Vue 3 + Vite + Element Plus)",
|
||||
"type": "module",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import type { ClientDeviceDto } from '@classhelper/shared';
|
||||
const props = defineProps<{ device: ClientDeviceDto }>();
|
||||
const progress = computed(() => props.device.updateProgress);
|
||||
const labels = {
|
||||
idle: '等待客户端接收',
|
||||
downloading: '当前客户端正在下载更新包',
|
||||
verifying: '正在校验更新包',
|
||||
ready: '更新包已就绪',
|
||||
waiting: '已下载,等待安装时机',
|
||||
installing: '当前客户端正在更新,将会短暂离线',
|
||||
completed: '客户端已完成更新',
|
||||
failed: '客户端更新失败',
|
||||
};
|
||||
const waiting = computed(() =>
|
||||
props.device.updateMode === 'immediate'
|
||||
? '立即安装'
|
||||
: props.device.updateMode === 'after-school'
|
||||
? `放学后安装${props.device.updateNotBefore ? ' · ' + new Date(props.device.updateNotBefore).toLocaleString() : ''}`
|
||||
: '课间且主窗口隐藏满五分钟后安装',
|
||||
);
|
||||
const mb = (bytes: number) => `${(bytes / 1048576).toFixed(1)} MB`;
|
||||
</script>
|
||||
<template>
|
||||
<div class="update-status">
|
||||
<template v-if="progress">
|
||||
<strong>
|
||||
{{ labels[progress.stage] }}
|
||||
<template v-if="progress.stage === 'completed'">,版本 {{ progress.version }}</template>
|
||||
</strong>
|
||||
<el-progress
|
||||
v-if="['downloading', 'verifying', 'waiting'].includes(progress.stage)"
|
||||
:percentage="progress.percent || 0"
|
||||
:indeterminate="progress.percent === null"
|
||||
/>
|
||||
<small v-if="progress.totalBytes">
|
||||
{{ mb(progress.downloadedBytes) }} / {{ mb(progress.totalBytes) }}
|
||||
</small>
|
||||
<small v-if="progress.stage === 'waiting'">{{ waiting }}</small>
|
||||
<el-text v-if="progress.error" type="danger">{{ progress.error }}</el-text>
|
||||
<small v-if="progress.updatedAt">上次报告:{{ new Date(progress.updatedAt).toLocaleString() }}</small>
|
||||
<el-text v-if="progress.stage === 'installing' && !device.online" type="warning">
|
||||
正在等待新版上线确认
|
||||
</el-text>
|
||||
</template>
|
||||
<template v-else-if="device.updateTargetVersion">
|
||||
<strong>已下发 {{ device.updateTargetVersion }},等待客户端接收</strong>
|
||||
<small>{{ waiting }}</small>
|
||||
</template>
|
||||
<span v-else>暂无更新任务</span>
|
||||
<el-text
|
||||
v-if="device.updateTargetVersion && !device.autoUpdate && progress?.stage !== 'completed'"
|
||||
type="warning"
|
||||
>
|
||||
客户端已关闭自动更新,请在客户端开启后重试
|
||||
</el-text>
|
||||
</div>
|
||||
</template>
|
||||
<style scoped>
|
||||
.update-status {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding-block: 6px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
small {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
@@ -103,7 +103,23 @@ watch(
|
||||
width: 0;
|
||||
}
|
||||
.management-menu.menu-rail :deep(.el-sub-menu__title) {
|
||||
padding: 0 14px !important;
|
||||
padding: 0 !important;
|
||||
margin: 4px 0 !important;
|
||||
width: 48px;
|
||||
height: 44px;
|
||||
justify-content: center;
|
||||
}
|
||||
.management-menu.menu-rail .management-group-title {
|
||||
justify-content: center;
|
||||
gap: 0;
|
||||
min-width: 20px;
|
||||
}
|
||||
.management-menu.menu-rail .management-group-title span {
|
||||
flex: 0 0 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.management-menu.menu-rail :deep(.el-sub-menu__icon-arrow) {
|
||||
visibility: hidden;
|
||||
}
|
||||
.management-menu.menu-rail {
|
||||
overflow-x: hidden;
|
||||
|
||||
@@ -5,7 +5,7 @@ export const MANAGEMENT_GROUPS = [
|
||||
id: 'teaching',
|
||||
title: '教学事务',
|
||||
icon: 'Notebook',
|
||||
paths: ['/schedules', '/plan-editor', '/homeworks', '/notifications', '/courseware', '/grades'],
|
||||
paths: ['/plan-editor', '/homeworks', '/notifications', '/courseware', '/grades'],
|
||||
},
|
||||
{
|
||||
id: 'school',
|
||||
|
||||
@@ -14,13 +14,23 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import('@/layouts/AdminLayout.vue'),
|
||||
redirect: '/dashboard',
|
||||
children: [
|
||||
{ path: 'courseware', name: 'courseware', component: () => import('@/views/CoursewareView.vue'), meta: { title: '课件', icon: 'FolderOpened', roles: ['ADMIN', 'TEACHER'], permission: 'courseware:read' } },
|
||||
{
|
||||
path: 'courseware',
|
||||
name: 'courseware',
|
||||
component: () => import('@/views/CoursewareView.vue'),
|
||||
meta: {
|
||||
title: '课件',
|
||||
icon: 'FolderOpened',
|
||||
roles: ['ADMIN', 'TEACHER'],
|
||||
permission: 'courseware:read',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'plan-editor',
|
||||
name: 'plan-editor',
|
||||
component: () => import('@/views/PlanEditorView.vue'),
|
||||
meta: {
|
||||
title: '时间表与课表编辑',
|
||||
title: '课表档案',
|
||||
icon: 'Calendar',
|
||||
roles: ['ADMIN', 'TEACHER'],
|
||||
permission: 'schedule:read',
|
||||
@@ -79,7 +89,7 @@ const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: 'schedules',
|
||||
name: 'schedules',
|
||||
component: () => import('@/views/SchedulesView.vue'),
|
||||
redirect: '/plan-editor',
|
||||
meta: { title: '课表管理', icon: 'Calendar' },
|
||||
},
|
||||
{
|
||||
|
||||
@@ -907,6 +907,36 @@ body {
|
||||
}
|
||||
}
|
||||
|
||||
/* 原生文件选择保留键盘与读屏能力,按钮外观与管理端控件保持一致。 */
|
||||
input[type='file']:not([hidden]) {
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
font: inherit;
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
input[type='file']::file-selector-button {
|
||||
padding: 8px 16px;
|
||||
margin-right: 12px;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
color: var(--el-color-primary);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.toolbar {
|
||||
row-gap: 12px;
|
||||
}
|
||||
.toolbar > .el-button + .el-button {
|
||||
margin-left: 0;
|
||||
}
|
||||
.el-form--inline .el-form-item {
|
||||
max-width: 100%;
|
||||
}
|
||||
.el-form-item__content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* 抽屉(el-drawer)。和弹窗不同,抽屉的位移由 `.el-drawer` **自身**的
|
||||
* `transition: all var(--el-transition-duration)` 承载(`.el-drawer-fade-*` 那组类
|
||||
|
||||
@@ -18,13 +18,13 @@
|
||||
* **禁用 + tooltip 说明**而不是直接隐藏:让老师知道"有这件事、需要权限",而不是以为系统没有。
|
||||
*/
|
||||
import ReleaseProgress from '@/components/ReleaseProgress.vue';
|
||||
import ClientUpdateStatus from '@/components/ClientUpdateStatus.vue';
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import {
|
||||
CLIENT_COMMAND_EXPIRE_MS,
|
||||
CLIENT_COMMAND_KINDS,
|
||||
CLIENT_COMMAND_LABELS,
|
||||
CLIENT_HEARTBEAT_INTERVAL_MS,
|
||||
clientReleaseFileName,
|
||||
compareVersions,
|
||||
normalizeVersion,
|
||||
@@ -47,7 +47,7 @@ const { isMobile } = useResponsive();
|
||||
const auth = useAuthStore();
|
||||
|
||||
/** 自动刷新间隔:跟客户端心跳同频,刷太快没有新数据 */
|
||||
const AUTO_REFRESH_MS = CLIENT_HEARTBEAT_INTERVAL_MS;
|
||||
const AUTO_REFRESH_MS = 3000;
|
||||
|
||||
function can(key: PermissionKey): boolean {
|
||||
return auth.can(key);
|
||||
@@ -214,9 +214,6 @@ function classLabel(device: ClientDeviceDto): string {
|
||||
}
|
||||
|
||||
/** 「已指定 <版本>」:只显示版本号,避免与「已下载待安装」挤在一起 */
|
||||
function targetVersionLabel(device: ClientDeviceDto): string {
|
||||
return normalizeVersion(device.updateTargetVersion) || device.updateTargetVersion;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- 下发更新 */
|
||||
|
||||
@@ -814,20 +811,8 @@ const deviceEmptyText = computed(() =>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="更新" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<template v-if="row.pendingVersion">
|
||||
<el-tag class="client-tag" size="small" type="success" effect="plain">
|
||||
已下载待安装 v{{ normalizeVersion(row.pendingVersion) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
<template v-if="row.updateTargetVersion">
|
||||
<el-tag class="client-tag" size="small" type="primary" effect="plain">
|
||||
已指定 v{{ targetVersionLabel(row) }}
|
||||
</el-tag>
|
||||
</template>
|
||||
<span v-if="!row.pendingVersion && !row.updateTargetVersion" class="text-muted">—</span>
|
||||
</template>
|
||||
<el-table-column label="更新过程" min-width="290">
|
||||
<template #default="{ row }"><ClientUpdateStatus :device="row" /></template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type CoursewareDto,
|
||||
type CoursewareClassDto,
|
||||
type CoursewareUploadRequest,
|
||||
type CoursewareFolderDto,
|
||||
} from '@classhelper/shared';
|
||||
import { api } from '@/api/http';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
@@ -19,6 +20,7 @@ const items = ref<CoursewareDto[]>([]),
|
||||
const file = ref<File | null>(null),
|
||||
classIds = ref<string[]>([]),
|
||||
mode = ref<'cloud' | 'push'>('cloud');
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const loading = ref(false),
|
||||
uploading = ref(false),
|
||||
progress = ref(0),
|
||||
@@ -30,11 +32,51 @@ const scopeItem = ref<CoursewareDto | null>(null),
|
||||
scopeMode = ref<'visibility' | 'push'>('visibility'),
|
||||
saving = ref(false);
|
||||
const canWrite = computed(() => auth.can('courseware:write'));
|
||||
const folders = ref<CoursewareFolderDto[]>([]),
|
||||
folderPath = ref(''),
|
||||
folderFilter = ref('');
|
||||
const grouping = ref<'date' | 'folder'>('date');
|
||||
const dateFolder = ref('');
|
||||
const dateFolders = computed(() =>
|
||||
[
|
||||
...new Set(
|
||||
items.value.map((item) => item.archivePath?.split('/').slice(0, -1).join('/') || item.archiveDate),
|
||||
),
|
||||
]
|
||||
.sort()
|
||||
.reverse(),
|
||||
);
|
||||
async function newFolder() {
|
||||
try {
|
||||
const { value } = await ElMessageBox.prompt(
|
||||
'输入文件夹名称,可用 / 创建多层分类,如 地理/必修一',
|
||||
'新建文件夹',
|
||||
);
|
||||
const path = String(value ?? '').trim();
|
||||
if (!path) return;
|
||||
await api.post('/courseware/folders', { path });
|
||||
await refresh();
|
||||
folderPath.value = path;
|
||||
} catch (error) {
|
||||
if (error !== 'cancel' && error !== 'close') throw error;
|
||||
}
|
||||
}
|
||||
async function move(item: CoursewareDto, target: string) {
|
||||
await api.patch(`/courseware/${item.id}/folder`, { folderPath: target });
|
||||
await refresh();
|
||||
}
|
||||
const filtered = computed(() =>
|
||||
items.value.filter(
|
||||
(item) =>
|
||||
(!query.value || `${item.name} ${item.teacher.name}`.includes(query.value)) &&
|
||||
(!category.value || item.category === category.value) &&
|
||||
(grouping.value !== 'folder' ||
|
||||
!folderFilter.value ||
|
||||
item.folderPath === folderFilter.value ||
|
||||
item.folderPath?.startsWith(folderFilter.value + '/')) &&
|
||||
(grouping.value !== 'date' ||
|
||||
!dateFolder.value ||
|
||||
(item.archivePath?.startsWith(dateFolder.value + '/') ?? item.archiveDate === dateFolder.value)) &&
|
||||
(!date.value || item.archiveDate === date.value),
|
||||
),
|
||||
);
|
||||
@@ -42,13 +84,25 @@ function size(bytes: number) {
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
function choose(event: Event) {
|
||||
file.value = (event.target as HTMLInputElement).files?.[0] ?? null;
|
||||
const picked = (event.target as HTMLInputElement).files?.[0];
|
||||
// 取消选择时不丢掉上一次选中的文件。
|
||||
if (picked) file.value = picked;
|
||||
}
|
||||
function pickFile() {
|
||||
if (!fileInput.value) return;
|
||||
// 允许重新选择同一个文件:清空后再打开选择器。
|
||||
fileInput.value.value = '';
|
||||
fileInput.value.click();
|
||||
}
|
||||
async function refresh() {
|
||||
loading.value = true;
|
||||
try {
|
||||
items.value = await api.get<CoursewareDto[]>('/courseware');
|
||||
if (canWrite.value) classes.value = await api.get<CoursewareClassDto[]>('/courseware/classes');
|
||||
if (canWrite.value)
|
||||
[classes.value, folders.value] = await Promise.all([
|
||||
api.get<CoursewareClassDto[]>('/courseware/classes'),
|
||||
api.get<CoursewareFolderDto[]>('/courseware/folders'),
|
||||
]);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -64,6 +118,7 @@ async function upload() {
|
||||
size: file.value.size,
|
||||
classIds: [...classIds.value],
|
||||
mode: mode.value,
|
||||
folderPath: folderPath.value,
|
||||
};
|
||||
uploading.value = true;
|
||||
progress.value = 0;
|
||||
@@ -133,7 +188,7 @@ onMounted(() => void refresh());
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h2 class="page-title">课件</h2>
|
||||
<p>保存教学文件,按日期与类型归档,发送到自己的授课班级。</p>
|
||||
<p>创建文件夹分类,或按教师、上传年份、月、日、时间浏览课件。</p>
|
||||
</div>
|
||||
<el-button :loading="loading" @click="refresh">刷新</el-button>
|
||||
</header>
|
||||
@@ -141,7 +196,34 @@ onMounted(() => void refresh());
|
||||
<h3>上传课件</h3>
|
||||
<el-form label-position="top" :disabled="uploading">
|
||||
<el-form-item label="文件(最大 512 MB)">
|
||||
<input aria-label="选择课件文件" type="file" @change="choose" />
|
||||
<div class="file-picker">
|
||||
<el-button :disabled="uploading" @click="pickFile">
|
||||
{{ file ? '重新选择文件' : '选择文件' }}
|
||||
</el-button>
|
||||
<span v-if="file" class="file-name">{{ file.name }} · {{ size(file.size) }}</span>
|
||||
<span v-else class="file-placeholder">未选择文件</span>
|
||||
<input
|
||||
ref="fileInput"
|
||||
aria-label="选择课件文件"
|
||||
type="file"
|
||||
:disabled="uploading"
|
||||
class="hidden-input"
|
||||
@change="choose"
|
||||
/>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="分类文件夹">
|
||||
<div class="folder-picker">
|
||||
<el-select v-model="folderPath" clearable placeholder="按上传日期自动归档">
|
||||
<el-option
|
||||
v-for="folder in folders"
|
||||
:key="folder.id"
|
||||
:value="folder.path"
|
||||
:label="folder.path"
|
||||
/>
|
||||
</el-select>
|
||||
<el-button @click="newFolder">新建文件夹</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="可见范围">
|
||||
<el-select
|
||||
@@ -176,6 +258,16 @@ onMounted(() => void refresh());
|
||||
</el-card>
|
||||
<el-card shadow="never" class="table-card" v-loading="loading">
|
||||
<div class="filters">
|
||||
<el-radio-group v-model="grouping">
|
||||
<el-radio-button value="date">日期归档</el-radio-button>
|
||||
<el-radio-button value="folder">文件夹分类</el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-select v-if="grouping === 'folder'" v-model="folderFilter" clearable placeholder="全部文件夹">
|
||||
<el-option v-for="folder in folders" :key="folder.id" :value="folder.path" :label="folder.path" />
|
||||
</el-select>
|
||||
<el-select v-else v-model="dateFolder" filterable clearable placeholder="教师 / 年 / 月 / 日 / 时间">
|
||||
<el-option v-for="folder in dateFolders" :key="folder" :value="folder" :label="folder" />
|
||||
</el-select>
|
||||
<el-input v-model="query" clearable placeholder="搜索文件名、教师" />
|
||||
<el-select v-model="category" clearable placeholder="全部类型">
|
||||
<el-option v-for="(label, key) in COURSEWARE_CATEGORIES" :key="key" :label="label" :value="key" />
|
||||
@@ -184,6 +276,26 @@ onMounted(() => void refresh());
|
||||
</div>
|
||||
<el-table :data="filtered" empty-text="暂无课件">
|
||||
<el-table-column prop="name" label="文件名称" min-width="220" show-overflow-tooltip />
|
||||
<el-table-column label="分类 / 归档位置" min-width="230">
|
||||
<template #default="{ row }">
|
||||
<el-select
|
||||
v-if="canWrite && row.teacher.id === auth.user?.id"
|
||||
:model-value="row.folderPath || ''"
|
||||
clearable
|
||||
size="small"
|
||||
placeholder="自动日期归档"
|
||||
@change="move(row, $event || '')"
|
||||
>
|
||||
<el-option
|
||||
v-for="folder in folders"
|
||||
:key="folder.id"
|
||||
:value="folder.path"
|
||||
:label="folder.path"
|
||||
/>
|
||||
</el-select>
|
||||
<small class="archive-path">{{ row.archivePath }}</small>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="类型" width="110">
|
||||
<template #default="{ row }">
|
||||
{{ COURSEWARE_CATEGORIES[(row as CoursewareDto).category] }} · {{ row.extension || '无扩展名' }}
|
||||
@@ -277,4 +389,38 @@ p,
|
||||
.el-progress {
|
||||
margin-top: 16px;
|
||||
}
|
||||
.folder-picker {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
}
|
||||
.folder-picker .el-select {
|
||||
flex: 1 1 220px;
|
||||
}
|
||||
.archive-path {
|
||||
display: block;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--el-text-color-secondary);
|
||||
margin-top: 6px;
|
||||
}
|
||||
.file-picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
}
|
||||
.file-name,
|
||||
.file-placeholder {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
.file-placeholder {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.hidden-input {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user