feat(storage): embed local file previews for managed servers
This commit is contained in:
1 parent
c2f16a5c56
commit
b477737b0f
31 files changed
+5182
-8
No files matched your search
@@ -40,7 +40,9 @@
|
||||
## 存储服务器与业务通知
|
||||
|
||||
- **存储服务器**:管理员配置 SMB 主机、共享名称、归档子目录及独立账号密码。密码加密保存在部署机,留空编辑保留原值;更换主机、共享或账号需重新录入。保存配置不连接服务器,点击“检查读写”会创建、读取并清理一个随机探测文件。账号维护要求部署机回环地址或可信 HTTPS。
|
||||
- **文件管理**:管理员与操作员可浏览归档目录、创建子目录、下载 PDF,将已有成功导出的 PDF 归档。目标存在相同内容时幂等完成;不同内容保留新文件,原件不覆盖。只读成员查看服务器和归档记录。启用自动归档后仅处理新导出的 PDF,历史文件由人选择归档;失败记录可通过重新选择同一任务重试。
|
||||
- **文件管理**:管理员与操作员可浏览归档目录、创建子目录、下载文件和内嵌预览,将已有成功导出的 PDF 归档。目标存在相同内容时幂等完成;不同内容保留新文件,原件不覆盖。只读成员查看服务器和归档记录。启用自动归档后仅处理新导出的 PDF,历史文件由人选择归档;失败记录可通过重新选择同一任务重试。
|
||||
- **文件预览**:在已托管服务器的目录中点击“预览”,支持 PDF、PNG/JPEG/GIF/WebP/BMP、文本(含 UTF-8、UTF-16 与 GB18030)、DOCX 和 XLSX。支持全屏、图片缩放与工作表切换;文本仅按原文显示。单文件预览及下载上限 64 MiB,文本预览上限 2 MiB;Office 展开内容最多 64 MiB、4096 个条目,Excel 每张表最多预览前 500 行、50 列。旧 DOC/XLS 与其他未支持格式可下载原文件。Office 预览以内容阅读为主,不保证与桌面 Office 排版完全一致,Excel 数值按原始值展示,不执行宏或重新计算公式。PDF 已关闭公网补充字体,缺少内嵌字体的文档可能出现字体替代。
|
||||
- **开源预览组件**:适配 [OpenList Frontend](https://github.com/OpenListTeam/OpenList-Frontend/tree/v4.2.7) 的 DOCX/XLSX 预览思路,采用 EmbedPDF、docx-preview、ExcelJS 与 PhotoSwipe;脚本和 PDFium WASM 由本机提供,界面使用系统字体,不调用公网 Office 在线服务。文件经现有登录权限读取,在独立沙箱中渲染。选型及许可见 [预览选型记录](docs/storage-preview-open-source-research-2026-10-17.md) 和 [第三方许可](licenses/storage-preview-NOTICES.md)。
|
||||
- **Windows SMB**:使用原生协议,不映射盘符、不强行断开已有共享连接。同一主机已有其他账号连接而产生 1219 冲突时,由部署机管理员处理。共享及所配置归档根目录需已存在并授予读写权限。PDF 上限 64 MiB,单层浏览最多 500 项。
|
||||
- **业务通知**:配置来源名称、JSON 字段路径、托管发件邮箱及尝试上限,产业接口人维护在现有“模板与收件群组”。通知 ID、产业、简要说明必填;正文复制简要说明原文,**不附带 PDF,也不因 PDF 存档而触发邮件**。可粘贴样本预览字段及收件人,预览不入队、不发信。
|
||||
- **自动发送**:默认暂停。开启前需要 SMTP 检查通过及产业收件组;开启后每 30 秒检查既有的两个北京时间时段及业务日历,逐项或按产业汇总。错过时段保留待发数据至下个正常时段;空队列不发信。SMTP 检查失败受尝试次数限制,发送结果不明确或部分收件人未接受则停在“待核实”,管理员填写核验依据后才能确认成功或重新入队。
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# 存储文件预览开源选型
|
||||
|
||||
核实日期:2026-10-17。需求:为当前已经托管的 SMB 服务器增加 PDF、图片、文本及 Word/Excel 文件预览,保持服务器、账号与目录可配置。
|
||||
|
||||
## 已核实的候选
|
||||
|
||||
| 项目 | 当前状态与许可 | 与本项目的关系 |
|
||||
|---|---|---|
|
||||
| [OpenList](https://github.com/OpenListTeam/OpenList) | 最新稳定版 v4.2.7(2026-10-15),后端 AGPL-3.0 | 原生 SMB 驱动,完整目录管理及文件预览;作为完整服务接入会增加一个 Go 服务及权限对接 |
|
||||
| [OpenList Frontend](https://github.com/OpenListTeam/OpenList-Frontend/tree/v4.2.7) | v4.2.7,前端独立 MIT 许可 | 可复用其开源预览组件与依赖,适配当前存储 API,保留现有 SMB 托管与工作台账号 |
|
||||
| [FileBrowser Quantum](https://github.com/gtsteffaniak/filebrowser) | v2.0.1-stable(2026-10-13),Apache-2.0 | 完整文件管理服务,提供多种预览;另有用户与存储源管理,需要额外对接 |
|
||||
| [kkFileView](https://github.com/kekingcn/kkFileView) | v5.0.3(2026-10-08),LICENSE 为 Apache-2.0 | 适合需要 doc/xls/ppt 等旧格式及高保真办公预览的场景,依赖 Java 与 LibreOffice/OpenOffice |
|
||||
| [经典 File Browser](https://github.com/filebrowser/filebrowser) | GitHub API 显示仓库已归档 | 本次不作为新增集成的首选 |
|
||||
|
||||
版本、归档状态及发行时间来自 GitHub 官方仓库 API;许可同时核对实际 LICENSE。kkFileView 的 GitHub 元数据未识别 SPDX,但仓库 LICENSE 原文为 Apache License 2.0。
|
||||
|
||||
## 已采用的内嵌路线
|
||||
|
||||
现有项目已有 SMB 加密托管、逐段目录校验、工作台权限和归档记录;可以将 OpenList Frontend 的预览逻辑适配到现有文件列表,在文件旁加入“预览”。无需让同事再次维护一套 SMB 账号。适配时保留 OpenList Frontend MIT 版权文本,明确上游版本及修改。
|
||||
|
||||
已核实 OpenList Frontend v4.2.7 的实际实现:
|
||||
|
||||
- [PDF 组件](https://github.com/OpenListTeam/OpenList-Frontend/blob/v4.2.7/src/pages/home/previews/pdf.tsx):采用 MIT 许可的 `@embedpdf/snippet` 2.15.1,提供完整 PDF 阅读界面和 PDFium WASM;支持普通 HTML 页面,不要求整个工作台迁移前端框架。
|
||||
- [Word 组件](https://github.com/OpenListTeam/OpenList-Frontend/blob/v4.2.7/src/pages/home/previews/doc.tsx):采用 `docx-preview` 与 JSZip;npm 当前 docx-preview 为 0.4.1、Apache-2.0。对应现代 DOCX,不应据此声称已支持旧 DOC 格式。
|
||||
- [Excel 组件](https://github.com/OpenListTeam/OpenList-Frontend/blob/v4.2.7/src/pages/home/previews/xls.tsx):采用 MIT 许可的 ExcelJS,实际调用 `workbook.xlsx.load`。npm ExcelJS 为 4.4.0;不能把组件文件名 xls.tsx 当作旧 XLS 格式已经支持的证据。
|
||||
- 图片、文本可在当前页面的受限预览容器内展示;图片缩放可采用 MIT 许可的 PhotoSwipe 5.4.4。
|
||||
|
||||
上游 [useCDN.ts](https://github.com/OpenListTeam/OpenList-Frontend/blob/v4.2.7/src/hooks/useCDN.ts) 的 Office 预览依赖默认从资源 CDN 加载。本项目接入时应将选用的脚本和 WASM 固定版本并在本机提供;读取文件仍经受工作台认证的存储 API。
|
||||
|
||||
## 接入行为
|
||||
|
||||
1. 已启用托管服务器的目录中,支持的文件显示“预览”;继续复用原服务器 ID 和共享根目录限制。
|
||||
2. PDF 提供翻页、搜索与缩放;图片可缩放;文本保留换行;DOCX 和 XLSX 使用相应开源组件读取。
|
||||
3. 预览使用工作台登录态,SMB 密码不进入浏览器;预览文件不发送至公网 Office 在线服务。
|
||||
4. 图片和文档在独立预览区域渲染,文本文字不作为 HTML 执行;未知格式明确显示无法预览并保留原有可用下载能力。
|
||||
5. DOC/XLS 等旧格式若为后续实际必需,可通过配置内网 kkFileView 等转换服务扩展,单独完成部署和实际格式验收。
|
||||
|
||||
已实现本地组件接入、工作台鉴权传递文件字节、独立 opaque-origin iframe 沙箱与目录内预览/下载入口;服务器地址、共享目录与凭据继续使用现有配置。不部署第二套文件服务。PDF 采用组件官方支持的 direct engine 模式(`worker:false`),在 opaque-origin 沙箱中本地初始化 PDFium;避免该环境下 Blob Worker 初始化停滞,主工作台 CSP 不变。
|
||||
|
||||
限制:单文件 64 MiB;文本预览 2 MiB;Office 包最多 4096 条目和 64 MiB 展开内容,同时校验实际受限解压结果,拒绝伪造展开大小。XLSX 每张表预览前 500 行、50 列,明确显示原始数值及保存的公式结果,不重新计算公式或模拟 Office 全部格式。PDF 界面使用系统字体,不访问公网补充字体/印章库;未内嵌字体的 PDF 可能有字体替代。
|
||||
|
||||
验证使用本地临时目录模拟 SMB 文件边界;真实服务器地址、账号及网络条件尚未提供,不能据此宣称完成真实 SMB 联调。完整许可及适配范围见 `licenses/storage-preview-NOTICES.md`。
|
||||
@@ -0,0 +1,34 @@
|
||||
# 存储文件预览验证
|
||||
|
||||
日期:2026-10-17;分支:codex/smb-storage。环境:Windows、Node 24.11.1、本机 Chrome。
|
||||
|
||||
## 功能验证
|
||||
|
||||
- 新增 metadata/content API 复用工作台登录、角色、服务器启用状态及目录根限制;viewer 无文件读取权限。
|
||||
- 本地 HTTP 测试覆盖未登录、角色限制、父目录/目录链接拒绝、MIME 与下载响应、206/416 字节范围及静态资源白名单。
|
||||
- 文件测试覆盖 GB18030 中文、保留换行、非法图片/Office、超限文本、Office 声明过大及伪造过小展开大小;受限实际解压校验成功。
|
||||
- 实际浏览器验证 TXT 脚本文字不执行且无法访问父页面;DOCX 原文;XLSX 原文、42 数值、工作表切换与 HTML 字面内容;PhotoSwipe 图片缩放;PDF 页面图像实际解码;旧 DOC 不支持提示;关闭与移动端无横向溢出。
|
||||
- 浏览器测试无公网 HTTP 请求、无未捕获页面异常;所有组件由本机提供。
|
||||
|
||||
## 执行记录
|
||||
|
||||
```powershell
|
||||
node --test --test-concurrency=2 tests/storage-preview.test.cjs tests/storage-preview-http.test.cjs tests/storage.test.cjs tests/storage-http.test.cjs tests/dashboard-http.test.cjs tests/assets.test.cjs
|
||||
# 14 / 14 通过
|
||||
node --test --test-timeout=260000 tests/storage-preview-ui.test.cjs
|
||||
# 1 / 1 通过
|
||||
node --test --test-concurrency=1 tests/storage-ui.test.cjs tests/server.test.cjs
|
||||
# 4 / 4 通过
|
||||
```
|
||||
|
||||
共 19 项相关测试通过,未运行全量测试集。较早的并行回归中原有 HTTP 导出因 60 秒截止仍处于 running 而失败;上述顺序复跑在约 34 秒内成功,归档浏览器回归亦通过。
|
||||
|
||||
语法检查及 `git diff --check` 通过。独立只读审查发现的 ZIP 实际解压上限、组件公网默认字体/印章、Excel 数值格式说明已修复并复核。
|
||||
|
||||
PDF 原先的 Worker 模式在 opaque-origin iframe 中未完成初始化;使用组件支持的 `worker:false` 后,PDFium 加载和页面解码通过,未放宽主页面 CSP 或添加 allow-same-origin。
|
||||
|
||||
截图保存在本地 `output/verification/storage-preview-xlsx.png` 和 `storage-preview-pdf.png`,不提交测试业务文件。
|
||||
|
||||
## 范围限制
|
||||
|
||||
测试使用真实文件及本地临时目录模拟服务器文件边界,没有连接真实 SMB 或发送邮件。公司实际 SMB 网络、账号权限及业务文件仍需后续联调。旧 DOC/XLS 不支持内嵌;Office 格式与未内嵌字体 PDF 的显示限制见 README。
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 CloudPDF
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2019 Guyon Roche
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,651 @@
|
||||
JSZip is dual licensed. At your choice you may use it under the MIT license *or* the GPLv3
|
||||
license.
|
||||
|
||||
The MIT License
|
||||
===============
|
||||
|
||||
Copyright (c) 2009-2016 Stuart Knightley, David Duponchel, Franz Buchinger, António Afonso
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
GPL version 3
|
||||
=============
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 The OpenList Projects Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,196 @@
|
||||
// Copyright 2014 PDFium Authors. All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
1. Definitions.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
END OF TERMS AND CONDITIONS
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2022 Dmitry Semenov, https://dimsemenov.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright (c) 2016-2023 Volodymyr Baydalka
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,15 @@
|
||||
# 存储预览第三方组件
|
||||
|
||||
固定版本见 package.json 与 package-lock.json。发行时保留本目录许可原文;传递依赖许可保留在安装包中。
|
||||
|
||||
| 组件 | 版本 | 许可文件 | 使用方式 |
|
||||
|---|---|---|---|
|
||||
| OpenList Frontend | v4.2.7 | OpenList-Frontend-MIT.txt | 适配 doc.tsx / xls.tsx 思路;保留在 web/storage-preview-office.js 中的上游声明 |
|
||||
| @embedpdf/snippet | 2.15.1 | EmbedPDF-MIT.txt | PDF 阅读界面 |
|
||||
| PDFium | 随 EmbedPDF 发行 | PDFium-BSD.txt | 本地 PDF WASM 引擎 |
|
||||
| docx-preview | 0.4.1 | docx-preview-Apache-2.0.txt | DOCX 渲染 |
|
||||
| ExcelJS | 4.4.0 | ExcelJS-MIT.txt | XLSX 只读展示 |
|
||||
| JSZip | 3.10.1 | JSZip-LICENSE.txt | Office ZIP 解析(使用 MIT 许可选项) |
|
||||
| PhotoSwipe | 5.4.4 | PhotoSwipe-MIT.txt | 图片缩放 |
|
||||
|
||||
未引入 OpenList 后端或其 AGPL 代码,未部署独立 OpenList/kkFileView 服务。
|
||||
Generated
+3637
File diff suppressed because it is too large.
Load diff
@@ -12,11 +12,16 @@
|
||||
"node": ">=22.13"
|
||||
},
|
||||
"dependencies": {
|
||||
"@embedpdf/snippet": "2.15.1",
|
||||
"@tabler/core": "1.6.1",
|
||||
"@whyour/qinglong-cli": "0.1.2",
|
||||
"docx-preview": "0.4.1",
|
||||
"exceljs": "4.4.0",
|
||||
"imapflow": "2.4.3",
|
||||
"jszip": "3.10.1",
|
||||
"mailparser": "3.9.39",
|
||||
"nodemailer": "10.1.1",
|
||||
"photoswipe": "5.4.4",
|
||||
"playwright-core": "1.62.1",
|
||||
"sanitize-html": "2.18.1"
|
||||
},
|
||||
|
||||
+11
-2
@@ -6,6 +6,7 @@ const {mailApi}=require('./mail-api.cjs');
|
||||
const {bpmScanApi}=require('./bpm-scan-api.cjs');
|
||||
const {storageApi}=require('./storage-api.cjs');
|
||||
const {notificationApi}=require('./notification-api.cjs');
|
||||
const {previewAsset,PREVIEW_CSP}=require('./storage-preview-assets.cjs');
|
||||
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
|
||||
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
|
||||
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
|
||||
@@ -23,6 +24,11 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
'/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'},
|
||||
'/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'},
|
||||
'/storage.js':{path:path.join(webRoot,'storage.js'),type:'text/javascript'},
|
||||
'/storage-preview.html':{path:path.join(webRoot,'storage-preview.html'),type:'text/html',preview:true},
|
||||
'/storage-preview.js':{path:path.join(webRoot,'storage-preview.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-office.js':{path:path.join(webRoot,'storage-preview-office.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-host.js':{path:path.join(webRoot,'storage-preview-host.js'),type:'text/javascript'},
|
||||
'/storage-preview.css':{path:path.join(webRoot,'storage-preview.css'),type:'text/css',preview:true},
|
||||
'/notifications.js':{path:path.join(webRoot,'notifications.js'),type:'text/javascript'},
|
||||
'/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'},
|
||||
'/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'},
|
||||
@@ -37,9 +43,12 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
|
||||
try {
|
||||
const url=new URL(request.url,'http://localhost');const route=url.pathname;
|
||||
const asset=assets[route];
|
||||
const asset=assets[route]||previewAsset(route);
|
||||
if(/^\/vendor\/(embedpdf|photoswipe|docx|jszip|exceljs)\//.test(route)&&!asset)fail(404,'资源不存在。');
|
||||
if(request.method==='GET' && asset) {
|
||||
const bytes=await fs.promises.readFile(asset.path);response.writeHead(200,{'Content-Type':asset.type+'; charset=utf-8'});response.end(bytes);return;
|
||||
let bytes;try{bytes=await fs.promises.readFile(asset.path);}catch(error){if(error.code==='ENOENT')fail(404,'资源不存在。');throw error;}
|
||||
if(asset.preview){response.setHeader('Content-Security-Policy',PREVIEW_CSP);response.setHeader('Access-Control-Allow-Origin','*');}
|
||||
response.writeHead(200,{'Content-Type':asset.type+(asset.binary?'':'; charset=utf-8')});response.end(bytes);return;
|
||||
}
|
||||
const sameOrigin=request.headers.origin===`http://${request.headers.host}` || request.headers.origin===`https://${request.headers.host}`;
|
||||
if(!['GET','HEAD'].includes(request.method) && !sameOrigin)fail(403,'请在看板页面中执行操作。');
|
||||
|
||||
+12
-2
@@ -13,13 +13,23 @@ async function storageApi({storage,workspace,user,url,route,method,body,request,
|
||||
const saved=storage.saveServer(body);audit('保存存储服务器',saved.name);reply(body.id?200:201,saved);return true;
|
||||
}
|
||||
if(route==='/api/storage/settings'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以修改自动归档设置。',403);payload(body,['serverId','enabled']);const saved=storage.saveSettings(body);audit('保存自动归档设置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
|
||||
const match=/^\/api\/storage\/servers\/([\w-]+)\/(check|files|folders|archive|file)$/.exec(route);
|
||||
const match=/^\/api\/storage\/servers\/([\w-]+)\/(check|files|folders|archive|file|preview-info|content)$/.exec(route);
|
||||
if(match){const [,id,action]=match;
|
||||
if(action==='check'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以检查存储服务器。',403);payload(body,[]);const checked=await storage.check(id);audit('检查存储服务器',checked.name);reply(200,checked);return true;}
|
||||
if(action==='files'&&method==='GET'){reply(200,await storage.list(id,url.searchParams.get('path')||''));return true;}
|
||||
if(action==='folders'&&method==='POST'){payload(body,['path']);const result=await storage.mkdir(id,body.path);audit('创建归档目录',result.path);reply(201,result);return true;}
|
||||
if(action==='archive'&&method==='POST'){payload(body,['jobId','directory']);const result=await storage.archive(id,body.jobId,body.directory??'',user.username);audit('PDF 归档完成',result.relativePath);reply(200,result);return true;}
|
||||
if(action==='file'&&method==='GET'){const file=await storage.readPdf(id,url.searchParams.get('path')||'');response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(file.filename)});response.end(file.bytes);return true;}
|
||||
if(action==='preview-info'&&method==='GET'){reply(200,await storage.previewInfo(id,url.searchParams.get('path')||''));return true;}
|
||||
if((action==='file'||action==='content')&&method==='GET'){
|
||||
const preview=action==='content',file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||''),total=file.bytes.length;
|
||||
response.setHeader('Content-Type',preview?file.contentType:'application/octet-stream');response.setHeader('Content-Disposition',(preview?'inline':'attachment')+"; filename*=UTF-8''"+encodeURIComponent(file.filename));response.setHeader('Content-Security-Policy',"default-src 'none'; sandbox");response.setHeader('Cross-Origin-Resource-Policy','same-origin');response.setHeader('Accept-Ranges','bytes');
|
||||
let start=0,end=total-1,status=200;
|
||||
if(request.headers.range){const range=/^bytes=(\d*)-(\d*)$/.exec(request.headers.range);if(!range||(!range[1]&&!range[2])){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
|
||||
if(range[1]){start=Number(range[1]);if(range[2])end=Math.min(Number(range[2]),end);}else start=Math.max(0,total-Number(range[2]));
|
||||
if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start>end||start>=total){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}status=206;response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
|
||||
}
|
||||
const bytes=file.bytes.subarray(start,end+1);response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
|
||||
}
|
||||
}
|
||||
fail('没有找到此存储操作。',404);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const native=require('./smb-native.cjs');
|
||||
const {describePreview,validatePreview}=require('./storage-preview.cjs');
|
||||
const MAX_FILE=64*1024*1024;
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
||||
function segments(relative=''){
|
||||
@@ -43,6 +44,17 @@ class FileArea{
|
||||
return {readable:true,writable:true};
|
||||
}
|
||||
async readPdf(relative){if(path.extname(relative).toLowerCase()!=='.pdf')throw fail('仅支持下载归档 PDF。');const file=await this.resolve(relative);return {bytes:await pdf(file),filename:path.basename(file)};}
|
||||
async previewInfo(relative){const file=await this.resolve(relative),stat=await fs.stat(file);if(!stat.isFile())throw fail('请选择文件进行预览。');return describePreview(path.basename(file),stat.size);}
|
||||
async readFile(relative,limit=MAX_FILE){
|
||||
const file=await this.resolve(relative),handle=await fs.open(file,'r');
|
||||
try{const stat=await handle.stat();if(!stat.isFile())throw fail('请选择要读取的文件。');if(stat.size>limit)throw fail('文件超过工作台读取上限。',413);
|
||||
const buffer=Buffer.alloc(stat.size+1);let length=0;
|
||||
while(length<buffer.length){const result=await handle.read(buffer,length,buffer.length-length,null);if(!result.bytesRead)break;length+=result.bytesRead;}
|
||||
if(length>stat.size)throw fail('文件正在更新,请稍后重试。',409);
|
||||
return {filename:path.basename(file),bytes:buffer.subarray(0,length)};
|
||||
}finally{await handle.close();}
|
||||
}
|
||||
async readPreview(relative){const info=await this.previewInfo(relative);if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);const file=await this.readFile(relative,info.limit);return {...info,bytes:await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes)};}
|
||||
async archive(source,filename,relative=''){
|
||||
if(segments(filename).length!==1||path.extname(filename).toLowerCase()!=='.pdf')throw fail('归档文件名必须为 PDF 文件名。');
|
||||
const bytes=await pdf(source),sha256=digest(bytes),directory=await this.resolve(relative,true);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
// Public renderer assets only; managed files never pass through this resolver.
|
||||
const embedRoot=path.dirname(require.resolve('@embedpdf/snippet'));
|
||||
const photoRoot=path.dirname(require.resolve('photoswipe'));
|
||||
const fixed={
|
||||
'/vendor/docx/docx-preview.js':require.resolve('docx-preview'),
|
||||
'/vendor/jszip/jszip.min.js':require.resolve('jszip/dist/jszip.min.js'),
|
||||
'/vendor/exceljs/exceljs.min.js':require.resolve('exceljs/dist/exceljs.min.js')
|
||||
};
|
||||
function previewAsset(route){
|
||||
let file=fixed[route];
|
||||
const embed=/^\/vendor\/embedpdf\/([\w.-]+\.(?:js|wasm))$/.exec(route),photo=/^\/vendor\/photoswipe\/(photoswipe(?:-lightbox)?\.esm\.js|photoswipe\.css)$/.exec(route);
|
||||
if(embed)file=path.join(embedRoot,embed[1]);if(photo)file=path.join(photoRoot,photo[1]);if(!file)return null;
|
||||
return {path:file,type:file.endsWith('.wasm')?'application/wasm':file.endsWith('.css')?'text/css':'text/javascript',binary:file.endsWith('.wasm'),preview:true};
|
||||
}
|
||||
const PREVIEW_CSP="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data: blob:; connect-src 'self' blob:; worker-src 'self' blob:; frame-ancestors 'self'; base-uri 'none'; form-action 'none'; object-src 'none'";
|
||||
module.exports={previewAsset,PREVIEW_CSP};
|
||||
@@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const JSZip=require('jszip');
|
||||
const inflateRaw=require('node:util').promisify(require('node:zlib').inflateRaw);
|
||||
const MAX_PREVIEW=64*1024*1024,MAX_TEXT=2*1024*1024;
|
||||
const imageTypes={'.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.gif':'image/gif','.webp':'image/webp','.bmp':'image/bmp'};
|
||||
const textTypes=new Set(['.txt','.md','.log','.csv','.tsv','.json','.xml','.yaml','.yml','.ini','.cfg','.conf','.js','.cjs','.mjs','.ts','.css','.html','.htm','.sql','.py','.c','.h','.cpp']);
|
||||
const fail=(message,status)=>Object.assign(new Error(message),{status});
|
||||
function describePreview(filename,bytes){
|
||||
const ext=path.extname(filename).toLowerCase();let kind='unsupported',contentType='application/octet-stream';
|
||||
if(ext==='.pdf'){kind='pdf';contentType='application/pdf';}
|
||||
else if(imageTypes[ext]){kind='image';contentType=imageTypes[ext];}
|
||||
else if(textTypes.has(ext)){kind='text';contentType='text/plain; charset=utf-8';}
|
||||
else if(ext==='.docx'){kind='docx';contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document';}
|
||||
else if(ext==='.xlsx'){kind='xlsx';contentType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';}
|
||||
const limit=kind==='text'?MAX_TEXT:MAX_PREVIEW,canPreview=kind!=='unsupported'&&bytes<=limit;
|
||||
let reason='';if(kind==='unsupported')reason=['.doc','.xls','.ppt'].includes(ext)?'此旧版 Office 格式暂不支持内嵌预览,可下载原文件。':'此格式暂不支持预览,可下载原文件。';else if(bytes>limit)reason=`文件超过 ${limit/1024/1024} MiB 预览上限。`;
|
||||
return {filename,bytes,kind,contentType,canPreview,canDownload:bytes<=MAX_PREVIEW,limit,reason};
|
||||
}
|
||||
function decodeText(bytes){
|
||||
if(bytes[0]===0xff&&bytes[1]===0xfe)return new TextDecoder('utf-16le').decode(bytes);
|
||||
if(bytes[0]===0xfe&&bytes[1]===0xff)return new TextDecoder('utf-16be').decode(bytes);
|
||||
try{return new TextDecoder('utf-8',{fatal:true}).decode(bytes);}catch{return new TextDecoder('gb18030').decode(bytes);}
|
||||
}
|
||||
async function validatePreview(info,bytes){
|
||||
if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);
|
||||
let valid=true;
|
||||
if(info.kind==='pdf')valid=bytes.subarray(0,5).toString()==='%PDF-';
|
||||
if(info.kind==='image'){
|
||||
const type=info.contentType;
|
||||
valid=type==='image/png'?bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])):
|
||||
type==='image/jpeg'?bytes[0]===255&&bytes[1]===216&&bytes[2]===255:
|
||||
type==='image/gif'?/^GIF8[79]a/.test(bytes.subarray(0,6).toString()):
|
||||
type==='image/webp'?bytes.subarray(0,4).toString()==='RIFF'&&bytes.subarray(8,12).toString()==='WEBP':bytes.subarray(0,2).toString()==='BM';
|
||||
}
|
||||
if(info.kind==='docx'||info.kind==='xlsx'){
|
||||
let zip;try{zip=await JSZip.loadAsync(bytes,{createFolders:false});}catch{throw fail('Office 文件内容无效,无法预览。',415);}
|
||||
const files=Object.values(zip.files);let total=0;
|
||||
if(files.length>4096)throw fail('Office 文件包含过多内容,无法预览。',413);
|
||||
for(const file of files){const size=file.dir?0:file._data?.uncompressedSize;if(!Number.isSafeInteger(size)||size<0)throw fail('Office 文件内容无效,无法预览。',415);total+=size;if(total>MAX_PREVIEW)throw fail('Office 文件展开内容超过预览上限。',413);}
|
||||
// Do not trust ZIP sizes: stop inflation at the declared size (and global cap).
|
||||
for(const file of files){if(file.dir)continue;const data=file._data,expected=data.uncompressedSize;let expanded;
|
||||
try{if(data.compression.magic==='\x08\x00')expanded=await inflateRaw(data.compressedContent,{maxOutputLength:Math.min(expected+1,MAX_PREVIEW+1)});
|
||||
else if(data.compression.magic==='\x00\x00')expanded=data.compressedContent;
|
||||
else throw new Error('Unsupported compression');
|
||||
}catch(error){throw fail(error.code==='ERR_BUFFER_TOO_LARGE'?'Office 文件展开内容超过预览上限。':'Office 文件压缩内容无效。',error.code==='ERR_BUFFER_TOO_LARGE'?413:415);}
|
||||
if(expanded.length!==expected)throw fail('Office 文件展开大小与声明不符。',415);
|
||||
}
|
||||
valid=!!zip.file('[Content_Types].xml')&&!!zip.file(info.kind==='docx'?'word/document.xml':'xl/workbook.xml');
|
||||
}
|
||||
if(!valid)throw fail('文件内容与扩展名不匹配,无法预览。',415);
|
||||
return info.kind==='text'?Buffer.from(decodeText(bytes),'utf8'):bytes;
|
||||
}
|
||||
module.exports={describePreview,validatePreview,MAX_PREVIEW};
|
||||
@@ -18,6 +18,9 @@ class StorageService{
|
||||
list(id,relative){return this.run(id,async server=>(await this.client.area(server)).list(relative));}
|
||||
mkdir(id,relative){return this.run(id,async server=>(await this.client.area(server)).mkdir(relative));}
|
||||
readPdf(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPdf(relative));}
|
||||
previewInfo(id,relative){return this.run(id,async server=>(await this.client.area(server)).previewInfo(relative));}
|
||||
readPreview(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPreview(relative));}
|
||||
readFile(id,relative){return this.run(id,async server=>(await this.client.area(server)).readFile(relative));}
|
||||
archive(id,jobId,directory='',actor='自动归档'){
|
||||
return this.run(id,async server=>{
|
||||
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
const JSZip=require('jszip');
|
||||
async function makePreviewFiles(root){
|
||||
await fs.writeFile(path.join(root,'说明.txt'),'<script>window.previewExecuted=true</script>\n第二行原文');
|
||||
await fs.writeFile(path.join(root,'gbk.txt'),Buffer.from([0xd6,0xd0,0xce,0xc4]));
|
||||
await fs.writeFile(path.join(root,'sample.png'),Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+cZ/0AAAAASUVORK5CYII=','base64'));
|
||||
await fs.writeFile(path.join(root,'bad.png'),'<html>this is not an image</html>');
|
||||
await fs.writeFile(path.join(root,'old.doc'),'legacy office document');
|
||||
await fs.writeFile(path.join(root,'unknown.bin'),Buffer.from([0,1,2,3]));
|
||||
const doc=new JSZip();doc.file('[Content_Types].xml','<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>');doc.file('_rels/.rels','<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>');doc.file('word/document.xml','<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>DOCX preview original text</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:bottom="1440" w:left="1440" w:right="1440"/></w:sectPr></w:body></w:document>');
|
||||
await fs.writeFile(path.join(root,'sample.docx'),await doc.generateAsync({type:'nodebuffer',compression:'DEFLATE'}));
|
||||
const ExcelJS=require('exceljs'),book=new ExcelJS.Workbook(),sheet=book.addWorksheet('原始数据');sheet.getCell('A1').value='Item';sheet.getCell('B1').value='Quantity';sheet.getCell('A2').value='<img src=x onerror=alert(1)>';sheet.getCell('B2').value=42;book.addWorksheet('第二页').getCell('A1').value='Second sheet';await book.xlsx.writeFile(path.join(root,'sample.xlsx'));
|
||||
return {doc};
|
||||
}
|
||||
module.exports={makePreviewFiles};
|
||||
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {makePreviewFiles}=require('./fixtures/storage-preview-files.cjs');
|
||||
|
||||
async function setup(t){
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-preview-http-')),remote=path.join(dir,'remote');await fs.mkdir(remote);await makePreviewFiles(remote);
|
||||
const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');
|
||||
const storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:dir,client:{area:async()=>new FileArea(remote)}}),managed=storage.saveServer({name:'托管服务器',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Fixture-storage-password',enabled:true});
|
||||
const server=createDashboard({store,storage,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
|
||||
t.after(async()=>{await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
const request=(route,cookie,extra={})=>fetch(base+route,{headers:{...(cookie?{Cookie:cookie}:{}),...extra}}),login=async username=>(await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password:'Test-password-123'})})).headers.get('set-cookie').split(';')[0];
|
||||
return {request,login,storage,managed,remote};
|
||||
}
|
||||
test('preview endpoints reuse authentication and root restrictions, with correct content and byte ranges',async t=>{
|
||||
const {request,login,managed,storage,remote}=await setup(t),prefix='/api/storage/servers/'+managed.id;
|
||||
const url=action=>prefix+'/'+action+'?path='+encodeURIComponent('说明.txt');assert.equal((await request(url('preview-info'))).status,401);const operator=await login('operator'),viewer=await login('viewer');assert.equal((await request(url('preview-info'),viewer)).status,403);
|
||||
const info=await request(url('preview-info'),operator);assert.equal(info.status,200);assert.equal((await info.json()).kind,'text');
|
||||
const text=await request(url('content'),operator);assert.equal(text.status,200);assert.match(text.headers.get('content-type'),/^text\/plain/);assert.match(await text.text(),/^<script>/);
|
||||
const imageURL=prefix+'/content?path=sample.png',image=await request(imageURL,operator,{Range:'bytes=0-7'});assert.equal(image.status,206);assert.match(image.headers.get('content-range'),/^bytes 0-7\//);assert.deepEqual([...new Uint8Array(await image.arrayBuffer())],[137,80,78,71,13,10,26,10]);
|
||||
assert.equal((await request(imageURL,operator,{Range:'bytes=999999-'})).status,416);
|
||||
assert.equal((await request(prefix+'/content?path=bad.png',operator)).status,415);assert.equal((await request(prefix+'/preview-info?path=..%2Foutside.txt',operator)).status,400);
|
||||
const outside=path.join(remote,'..','outside');await fs.mkdir(outside);await fs.writeFile(path.join(outside,'secret.txt'),'secret');await fs.symlink(outside,path.join(remote,'redirect'),'junction');assert.equal((await request(prefix+'/content?path=redirect%2Fsecret.txt',operator)).status,400);
|
||||
const file=await request(prefix+'/file?path=unknown.bin',operator);assert.equal(file.status,200);assert.match(file.headers.get('content-disposition'),/^attachment/);assert.equal((await file.arrayBuffer()).byteLength,4);
|
||||
const saved=storage.store.publicServer(managed.id);storage.saveServer({...saved,password:'',enabled:false});assert.equal((await request(url('preview-info'),operator)).status,409);
|
||||
});
|
||||
|
||||
test('preview shell isolates renderer permissions and serves all open-source assets locally',async t=>{
|
||||
const {request}=await setup(t),page=await request('/storage-preview.html');assert.equal(page.status,200);const csp=page.headers.get('content-security-policy');assert.match(csp,/frame-ancestors 'self'/);assert.match(csp,/connect-src 'self'/);assert.doesNotMatch(csp,/https:/);
|
||||
for(const route of ['/storage-preview.js','/storage-preview-office.js','/vendor/embedpdf/embedpdf.js','/vendor/embedpdf/pdfium.wasm','/vendor/docx/docx-preview.js','/vendor/jszip/jszip.min.js','/vendor/exceljs/exceljs.min.js','/vendor/photoswipe/photoswipe.esm.js','/vendor/photoswipe/photoswipe.css']){const asset=await request(route);assert.equal(asset.status,200,route);assert.ok((await asset.arrayBuffer()).byteLength>0);}
|
||||
assert.equal((await request('/vendor/embedpdf/package.json')).status,404);assert.ok([401,404].includes((await request('/vendor/docx/../../package.json')).status));
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');const {makePreviewFiles}=require('./fixtures/storage-preview-files.cjs');
|
||||
|
||||
test('already-managed storage previews real files locally in an isolated frame',{timeout:240000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-preview-ui-')),remote=path.join(dir,'remote');await fs.mkdir(remote);await makePreviewFiles(remote);
|
||||
const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:dir,client:{area:async()=>new FileArea(remote)}});storage.saveServer({name:'已托管服务器',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Fixture-storage-password',enabled:true});
|
||||
const server=createDashboard({store,storage,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;
|
||||
t.after(async()=>{await browser?.close();await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(15000);const errors=[],external=[],failed=[],consoleErrors=[],previewRequests=[];page.on('console',m=>{if(m.type()==='error'||m.type()==='warning')consoleErrors.push(m.text());});page.on('response',r=>{if(r.url().includes('/vendor/embedpdf/'))previewRequests.push({url:r.url(),status:r.status()});});page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(/^https?:/.test(r.url())&&!r.url().startsWith(base+'/'))external.push(r.url());});page.on('requestfailed',r=>failed.push({url:r.url(),error:r.failure()?.errorText}));const base='http://127.0.0.1:'+server.address().port;
|
||||
const documentPage=await browser.newPage();await documentPage.setContent('<html><body><h1>PDF preview sample</h1><p>Original PDF content.</p></body></html>');await fs.writeFile(path.join(remote,'sample.pdf'),await documentPage.pdf({format:'A4'}));await documentPage.close();
|
||||
await page.goto(base+'/#storage');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'浏览目录',exact:true}).click();
|
||||
const frame=()=>page.frameLocator('iframe[title="文件内容预览"]');
|
||||
async function open(filename){await page.locator('#storage-browser .list-group-item').filter({has:page.getByText(filename,{exact:true})}).getByRole('button',{name:'预览',exact:true}).click();}
|
||||
await open('说明.txt');await frame().locator('#preview-text').waitFor();assert.equal(await frame().locator('#preview-text').textContent(),'<script>window.previewExecuted=true</script>\n第二行原文');assert.equal(await frame().locator('body').evaluate(()=>{try{void parent.document.body;return false;}catch{return window.previewExecuted!==true;}}),true);
|
||||
await open('sample.docx');await frame().getByText('DOCX preview original text',{exact:true}).waitFor();
|
||||
await open('sample.xlsx');await frame().getByRole('cell',{name:'42',exact:true}).waitFor();assert.equal(await frame().locator('img[src=x]').count(),0);await frame().getByLabel('工作表',{exact:true}).selectOption('1');await frame().getByRole('cell',{name:'Second sheet',exact:true}).waitFor();
|
||||
await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.screenshot({path:path.resolve('output/verification/storage-preview-xlsx.png'),fullPage:true});
|
||||
await open('sample.png');await frame().getByRole('button',{name:'放大图片',exact:true}).click();await frame().locator('.pswp--open').waitFor();
|
||||
await open('sample.pdf');try{await frame().locator('#preview-pdf img[src^="blob:"]').first().waitFor({timeout:60000});}catch(error){t.diagnostic(JSON.stringify({failed,errors,external,consoleErrors,previewRequests,body:await frame().locator('body').evaluate(body=>{function read(node){return [...node.childNodes].map(n=>n.nodeType===3?n.textContent:n.nodeType===1&&!['STYLE','SCRIPT'].includes(n.tagName)?read(n.shadowRoot||n):'').join(' ');}return read(body);})}));throw error;}
|
||||
assert.equal(await frame().locator('#preview-pdf img[src^="blob:"]').first().evaluate(async image=>{await image.decode();return image.naturalWidth>10&&image.naturalHeight>10;}),true);await page.screenshot({path:path.resolve('output/verification/storage-preview-pdf.png'),fullPage:true});
|
||||
await open('old.doc');await frame().getByText(/旧版 Office 格式/).waitFor();await page.getByRole('button',{name:'关闭预览',exact:true}).click();assert.equal(await page.locator('iframe[title="文件内容预览"]').count(),0);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(external,[]);assert.deepEqual(errors,[]);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {FileArea}=require('../src/storage-files.cjs');
|
||||
const {makePreviewFiles}=require('./fixtures/storage-preview-files.cjs');
|
||||
async function fixture(t){const root=await fs.mkdtemp(path.join(os.tmpdir(),'order-preview-files-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));await makePreviewFiles(root);return {root,area:new FileArea(root)};}
|
||||
|
||||
test('managed file metadata distinguishes local preview formats and generic downloads',async t=>{
|
||||
const {area}=await fixture(t);
|
||||
for(const [file,kind] of [['说明.txt','text'],['sample.png','image'],['sample.docx','docx'],['sample.xlsx','xlsx']]){const info=await area.previewInfo(file);assert.equal(info.kind,kind);assert.equal(info.canPreview,true);assert.equal(info.filename,file);assert.ok(info.bytes>0);}
|
||||
for(const file of ['sample.docx','sample.xlsx'])assert.ok((await area.readPreview(file)).bytes.length>0);
|
||||
const legacy=await area.previewInfo('old.doc');assert.equal(legacy.canPreview,false);assert.equal(legacy.kind,'unsupported');assert.equal((await area.readFile('unknown.bin')).bytes.length,4);
|
||||
});
|
||||
|
||||
test('previews validate bytes, preserve Chinese text and reject invalid or oversized documents',async t=>{
|
||||
const {area,root}=await fixture(t);assert.equal((await area.readPreview('gbk.txt')).bytes.toString(),'中文');assert.match((await area.readPreview('说明.txt')).bytes.toString(),/\n第二行原文$/);
|
||||
await assert.rejects(area.readPreview('bad.png'),e=>e.status===415);await assert.rejects(area.readPreview('unknown.bin'),e=>e.status===415);
|
||||
await fs.writeFile(path.join(root,'fake.docx'),'not a zip');await assert.rejects(area.readPreview('fake.docx'),e=>e.status===415);
|
||||
await fs.writeFile(path.join(root,'large.txt'),'');await fs.truncate(path.join(root,'large.txt'),2*1024*1024+1);assert.equal((await area.previewInfo('large.txt')).canPreview,false);await assert.rejects(area.readPreview('large.txt'),e=>e.status===413);
|
||||
await assert.rejects(area.readPreview('../secret.txt'),e=>e.status===400);
|
||||
});
|
||||
|
||||
test('Office preview refuses oversized ZIP expansion metadata',async t=>{
|
||||
const {root,area}=await fixture(t),buffer=await fs.readFile(path.join(root,'sample.docx'));let position=buffer.indexOf(Buffer.from([0x50,0x4b,0x01,0x02]));assert.ok(position>=0);buffer.writeUInt32LE(70*1024*1024,position+24);await fs.writeFile(path.join(root,'bomb.docx'),buffer);await assert.rejects(area.readPreview('bomb.docx'),e=>e.status===413);
|
||||
});
|
||||
|
||||
test('Office preview rejects forged understated ZIP expansion sizes before browser parsing',async t=>{
|
||||
const {root,area}=await fixture(t),JSZip=require('jszip'),zip=new JSZip();zip.file('[Content_Types].xml','types');zip.file('word/document.xml','x'.repeat(1024*1024));
|
||||
const bytes=await zip.generateAsync({type:'nodebuffer',compression:'DEFLATE'});
|
||||
for(let offset=0;offset<bytes.length-28;offset++)if(bytes.readUInt32LE(offset)===0x02014b50)bytes.writeUInt32LE(1,offset+24);
|
||||
await fs.writeFile(path.join(root,'understated.docx'),bytes);await assert.rejects(area.readPreview('understated.docx'),e=>[413,415].includes(e.status));
|
||||
});
|
||||
@@ -15,3 +15,5 @@
|
||||
.scan-interval{width:6rem}.arrival-date{font-weight:700;font-size:1.05rem;font-variant-numeric:tabular-nums}.arrival-day>summary{cursor:pointer;list-style:none}.arrival-day>summary::-webkit-details-marker{display:none}.arrival-day>summary:before{content:"▾";margin-right:.8rem;color:#64748b}.arrival-day:not([open])>summary:before{content:"▸"}.arrival-table th:first-child{min-width:175px}.arrival-table th:nth-child(2){min-width:170px}.arrival-subject{min-width:250px;white-space:normal;overflow-wrap:anywhere;max-width:600px}.arrival-table td:last-child{min-width:115px}
|
||||
|
||||
.notification-brief{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;color:inherit;background:transparent;padding:0;border:0;margin:0}
|
||||
|
||||
.storage-file-preview{min-width:0;max-width:100%}.storage-preview-frame{display:block;width:100%;height:70vh;min-height:420px;border:1px solid var(--tblr-border-color,#ddd);border-radius:6px;background:#fff}.storage-preview-frame:fullscreen{width:100vw;height:100vh;border:0}.storage-file-preview strong{min-width:0}
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"></head>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage-preview-host.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
@@ -0,0 +1,21 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
function open({container,serverId,path,isActive=()=>true}){
|
||||
const nonce=crypto.randomUUID(),controller=new AbortController(),frame=document.createElement('iframe');let disposed=false,ready=false,payload;
|
||||
frame.className='storage-preview-frame';frame.title='文件内容预览';frame.setAttribute('sandbox','allow-scripts allow-downloads');frame.setAttribute('allowfullscreen','');frame.src='/storage-preview.html?nonce='+encodeURIComponent(nonce);container.replaceChildren(frame);
|
||||
function dispose(){if(disposed)return;disposed=true;controller.abort();window.removeEventListener('message',onMessage);observer.disconnect();}
|
||||
function deliver(){if(!ready||!payload||disposed||!isActive()||!frame.isConnected)return;const transfer=payload.buffer?[payload.buffer]:[];frame.contentWindow.postMessage({kind:'order-storage-preview',nonce,...payload},'*',transfer);payload=null;}
|
||||
function onMessage(event){if(event.source===frame.contentWindow&&event.data?.nonce===nonce&&event.data?.kind==='order-storage-preview-ready'){ready=true;deliver();}}
|
||||
window.addEventListener('message',onMessage);const observer=new MutationObserver(()=>{if(!frame.isConnected)dispose();});observer.observe(document.body,{childList:true,subtree:true});
|
||||
const prefix='/api/storage/servers/'+encodeURIComponent(serverId),query='?path='+encodeURIComponent(path);
|
||||
(async()=>{
|
||||
const get=async route=>{const result=await fetch(route,{credentials:'same-origin',signal:controller.signal});if(!result.ok){const body=await result.json().catch(()=>({}));throw new Error(body.error||'文件读取失败,请稍后重试。');}return result;};
|
||||
const info=await(await get(prefix+'/preview-info'+query)).json();
|
||||
if(!info.canPreview)payload={error:info.reason||'此文件暂不支持预览。'};
|
||||
else {const buffer=await(await get(prefix+'/content'+query)).arrayBuffer();payload={info,buffer};}
|
||||
deliver();
|
||||
})().catch(error=>{if(!disposed){payload={error:error.message||'文件预览失败。'};deliver();}});
|
||||
return {dispose,fullscreen:()=>frame.requestFullscreen()};
|
||||
}
|
||||
window.StoragePreview={open};
|
||||
})();
|
||||
@@ -0,0 +1,32 @@
|
||||
/* Adapted from OpenList Frontend v4.2.7 doc.tsx and xls.tsx (MIT).
|
||||
* Copyright (c) 2025 The OpenList Projects Contributors.
|
||||
* Changes: local assets, read-only sandbox, bounded worksheet rendering,
|
||||
* plain DOM integration and cancellation handling. See licenses/OpenList-Frontend-MIT.txt.
|
||||
*/
|
||||
function script(src){return new Promise((resolve,reject)=>{const node=document.createElement('script');node.src=src;node.onload=resolve;node.onerror=()=>reject(new Error('预览组件加载失败。'));document.head.append(node);});}
|
||||
|
||||
export async function renderWord(bytes,container){
|
||||
await script('/vendor/jszip/jszip.min.js');await script('/vendor/docx/docx-preview.js');
|
||||
const toolbar=document.createElement('div');toolbar.className='preview-toolbar';const label=document.createElement('span');label.textContent='Word 文档';toolbar.append(label);
|
||||
const pages=document.createElement('div');pages.className='word-pages';container.append(toolbar,pages);
|
||||
await window.docx.renderAsync(bytes,pages,undefined,{className:'word-document',inWrapper:true,ignoreWidth:false,ignoreHeight:false,breakPages:true,ignoreLastRenderedPageBreak:true,renderHeaders:true,renderFooters:true,renderFootnotes:true,renderEndnotes:true,renderAltChunks:false,useBase64URL:false});
|
||||
}
|
||||
|
||||
export async function renderExcel(bytes,container){
|
||||
await script('/vendor/exceljs/exceljs.min.js');const book=new window.ExcelJS.Workbook();await book.xlsx.load(bytes);
|
||||
const toolbar=document.createElement('div');toolbar.className='preview-toolbar';const label=document.createElement('label');label.textContent='工作表';label.htmlFor='preview-sheet';const select=document.createElement('select');select.id='preview-sheet';
|
||||
book.worksheets.forEach((sheet,index)=>{const option=document.createElement('option');option.value=String(index);option.textContent=sheet.name;select.append(option);});
|
||||
toolbar.append(label,select);const note=document.createElement('p');note.className='preview-note';const viewport=document.createElement('div');viewport.className='sheet-viewport';container.append(toolbar,note,viewport);
|
||||
function showSheet(){const sheet=book.worksheets[Number(select.value)];viewport.replaceChildren();if(!sheet){note.textContent='此文件没有可显示的工作表。';return;}
|
||||
const rows=Math.min(sheet.rowCount,500),cols=Math.min(sheet.columnCount,50);note.textContent=(sheet.rowCount>500||sheet.columnCount>50?'仅预览前 500 行、50 列,可下载原文件查看完整内容。':`${sheet.name} · ${sheet.rowCount} 行、${sheet.columnCount} 列`)+'。数值按原始值展示,未应用单元格数字格式;公式显示文件中保存的结果。';
|
||||
const table=document.createElement('table');table.className='preview-sheet';const body=document.createElement('tbody');
|
||||
for(let row=1;row<=rows;row++){const tr=document.createElement('tr'),number=document.createElement('th');number.scope='row';number.textContent=String(row);tr.append(number);
|
||||
for(let col=1;col<=cols;col++){const cell=sheet.getCell(row,col),td=document.createElement('td');td.textContent=cell.text;
|
||||
if(cell.font?.bold)td.classList.add('cell-bold');if(cell.font?.italic)td.classList.add('cell-italic');
|
||||
const fill=cell.fill?.fgColor?.argb,color=cell.font?.color?.argb;if(/^[A-Fa-f0-9]{8}$/.test(fill||''))td.style.backgroundColor='#'+fill.slice(2);if(/^[A-Fa-f0-9]{8}$/.test(color||''))td.style.color='#'+color.slice(2);
|
||||
tr.append(td);
|
||||
}body.append(tr);
|
||||
}table.append(body);viewport.append(table);
|
||||
}
|
||||
select.addEventListener('change',showSheet);showSheet();
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;font:14px/1.6 system-ui,"Microsoft YaHei",sans-serif;color:#182433;background:#f5f7fa}#preview-status{padding:24px;color:#687787}.preview-error{white-space:pre-wrap}#preview-content{min-height:100%;width:100%;padding:16px}#preview-content[hidden]{display:none}#preview-text{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;font:14px/1.7 ui-monospace,Consolas,monospace;background:#fff;padding:16px;border-radius:8px}#preview-pdf{height:calc(100vh - 32px);min-height:360px}.preview-image{display:block;max-width:100%;max-height:calc(100vh - 80px);margin:12px auto;object-fit:contain}.preview-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:8px 0 16px}.preview-toolbar select,.image-zoom{padding:7px 12px;border:1px solid #dce1e7;border-radius:6px;background:white;color:inherit}.preview-note{margin:0 0 12px;color:#687787}.sheet-viewport{overflow:auto;max-height:calc(100vh - 110px);border:1px solid #dce1e7;background:white}.preview-sheet{border-collapse:collapse;min-width:100%}.preview-sheet td,.preview-sheet th{border:1px solid #dce1e7;padding:6px 10px;min-width:90px;max-width:480px;white-space:pre-wrap;overflow-wrap:anywhere}.preview-sheet th{min-width:48px;background:#edf1f5;font-weight:500}.cell-bold{font-weight:700}.cell-italic{font-style:italic}.word-pages{overflow:auto;max-width:100%;min-width:0}.word-document-wrapper{padding:8px!important}@media(max-width:640px){#preview-content{padding:8px}#preview-pdf{height:calc(100vh - 16px)}.word-document-wrapper{padding:0!important}.preview-sheet td{padding:5px 8px}}
|
||||
@@ -0,0 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>文件预览</title><link rel="stylesheet" href="/storage-preview.css"><link rel="stylesheet" href="/vendor/photoswipe/photoswipe.css"></head>
|
||||
<body><div id="preview-status" role="status">正在加载文件…</div><main id="preview-content" hidden></main><script type="module" src="/storage-preview.js"></script></body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
// Runs in an opaque-origin sandbox. Only the owning workbench may supply file bytes.
|
||||
import {renderWord,renderExcel} from './storage-preview-office.js';
|
||||
const nonce=new URLSearchParams(location.search).get('nonce'),parentOrigin=new URL(location.href).origin;
|
||||
const status=document.querySelector('#preview-status'),content=document.querySelector('#preview-content');let accepted=false,viewer;
|
||||
function error(message){status.hidden=false;status.textContent=message;status.className='preview-error';content.hidden=true;}
|
||||
async function render(info,buffer){
|
||||
if(info.kind==='text'){const text=document.createElement('pre');text.id='preview-text';text.textContent=new TextDecoder().decode(buffer);content.append(text);}
|
||||
else if(info.kind==='image'){
|
||||
const url=URL.createObjectURL(new Blob([buffer],{type:info.contentType})),image=document.createElement('img');image.alt=info.filename;image.src=url;image.className='preview-image';const button=document.createElement('button');button.type='button';button.textContent='放大图片';button.className='image-zoom';content.append(button,image);await image.decode();
|
||||
button.onclick=async()=>{const {default:PhotoSwipe}=await import('/vendor/photoswipe/photoswipe.esm.js');const gallery=new PhotoSwipe({dataSource:[{src:url,width:image.naturalWidth,height:image.naturalHeight,alt:info.filename}],bgOpacity:0.92});gallery.init();};
|
||||
}
|
||||
else if(info.kind==='docx')await renderWord(buffer,content);
|
||||
else if(info.kind==='xlsx')await renderExcel(buffer,content);
|
||||
else if(info.kind==='pdf'){
|
||||
const {default:EmbedPDF}=await import('/vendor/embedpdf/embedpdf.js');const url=URL.createObjectURL(new Blob([buffer],{type:'application/pdf'}));const target=document.createElement('div');target.id='preview-pdf';content.append(target);
|
||||
// Blob workers cannot initialize reliably under an opaque sandbox origin.
|
||||
// Keep PDFium in this isolated frame using the viewer's supported direct engine.
|
||||
viewer=EmbedPDF.init({type:'container',worker:false,target,src:url,wasmUrl:new URL('/vendor/embedpdf/pdfium.wasm',location.href).href,stamp:{manifests:[],libraries:[],defaultLibrary:false},fonts:{ui:null,signature:null},fontFallback:null,theme:{preference:'light'},i18n:{defaultLocale:'zh-CN',fallbackLocale:'en'}});
|
||||
}else throw new Error('此格式暂不支持预览。');
|
||||
status.hidden=true;content.hidden=false;
|
||||
}
|
||||
window.addEventListener('message',async event=>{
|
||||
if(event.source!==window.parent||event.origin!==parentOrigin||event.data?.nonce!==nonce||event.data?.kind!=='order-storage-preview'||accepted)return;
|
||||
accepted=true;const message=event.data;if(message.error){error(message.error);return;}
|
||||
try{if(!(message.buffer instanceof ArrayBuffer))throw new Error('文件数据不可用。');await render(message.info,message.buffer);}catch(cause){error(cause.message||'文件预览失败,请下载原文件查看。');}
|
||||
});
|
||||
window.addEventListener('pagehide',()=>viewer?.destroy?.());
|
||||
window.parent.postMessage({kind:'order-storage-preview-ready',nonce},parentOrigin);
|
||||
+11
-2
@@ -13,10 +13,19 @@
|
||||
host.querySelector('#storage-cancel').onclick=()=>host.replaceChildren();host.querySelector('form').onsubmit=async e=>{e.preventDefault();await action(e.submitter,async()=>{const input={...(s.id?{id:s.id,version:s.version}:{}),enabled:host.querySelector('#storage-active').checked};for(const key of ['name','host','share','directory','username','password'])input[key]=host.querySelector('#storage-'+key).value;try{await api('/storage/servers',input);if(isActive()){notify('存储服务器已保存。');await render(container,isActive);}}catch(error){if(isActive())host.querySelector('#storage-error').textContent=error.message;}});};host.scrollIntoView({block:'start',behavior:'smooth'});
|
||||
}
|
||||
if(admin){container.querySelector('#storage-add').onclick=()=>editor();container.querySelectorAll('[data-storage-edit]').forEach(b=>b.onclick=()=>editor(data.servers.find(s=>s.id===b.dataset.storageEdit)));container.querySelectorAll('[data-storage-check]').forEach(b=>b.onclick=()=>action(b,async()=>{await api('/storage/servers/'+b.dataset.storageCheck+'/check',{});if(isActive()){notify('存储服务器读写检查成功。');await render(container,isActive);}}));container.querySelector('#storage-auto').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/storage/settings',{serverId:container.querySelector('#storage-default').value,enabled:container.querySelector('#storage-enabled').checked});if(isActive()){notify('自动归档设置已保存。');await render(container,isActive);}});};}
|
||||
let preview;
|
||||
const closePreview=()=>{preview?.dispose();preview=null;container.querySelector('#storage-file-preview')?.replaceChildren();};
|
||||
async function browse(id,directory=''){
|
||||
const listing=await api('/storage/servers/'+id+'/files?path='+encodeURIComponent(directory));if(!isActive())return;const host=container.querySelector('#storage-browser'),server=data.servers.find(s=>s.id===id);
|
||||
host.innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title">${esc(server.name)} · 目录浏览</h3><button class="btn btn-sm ms-auto" id="storage-browser-close">关闭目录</button></div><div class="card-body"><div class="d-flex gap-2 align-items-center mb-3"><button class="btn btn-sm" id="storage-up" ${directory?'':'disabled'}>上一级</button><span class="text-break">/${esc(directory)}</span></div><div class="list-group mb-3">${listing.entries.map((entry,index)=>`<div class="list-group-item d-flex gap-2 align-items-center"><span class="text-break flex-fill">${esc(entry.name)}</span>${entry.type==='directory'?`<button class="btn btn-sm" data-storage-dir="${index}">打开目录</button>`:entry.type==='file'&&/\.pdf$/i.test(entry.name)?`<a class="btn btn-sm" href="/api/storage/servers/${id}/file?path=${encodeURIComponent(join(directory,entry.name))}" download>下载 PDF</a>`:''}</div>`).join('')||'<div class="text-secondary p-3">当前目录为空</div>'}</div>${listing.truncated?'<div class="text-secondary small mb-3">仅显示前 500 项</div>':''}<form id="storage-folder-form" class="d-flex flex-wrap gap-2 mb-4"><label class="visually-hidden" for="storage-folder">新目录名称</label><input class="form-control flex-fill" id="storage-folder" placeholder="新目录名称" required maxlength="200"><button class="btn" type="submit">创建目录</button></form><form id="storage-archive-form"><label class="form-label" for="storage-job">归档 PDF</label><select class="form-select" id="storage-job" required><option value="">请选择已完成的 PDF</option>${jobs.jobs.filter(j=>j.downloadable).map(j=>`<option value="${esc(j.jobId)}">${esc(j.filename||j.metadata?.order||j.jobId)}</option>`).join('')}</select><div class="text-end mt-3"><button class="btn btn-primary" type="submit">归档到当前目录</button></div></form></div></section>`;
|
||||
host.querySelector('#storage-browser-close').onclick=()=>host.replaceChildren();host.querySelector('#storage-up').onclick=e=>action(e.currentTarget,()=>browse(id,directory.split('/').slice(0,-1).join('/')));host.querySelectorAll('[data-storage-dir]').forEach(b=>b.onclick=()=>action(b,()=>browse(id,join(directory,listing.entries[Number(b.dataset.storageDir)].name))));host.querySelector('#storage-folder-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{const name=host.querySelector('#storage-folder').value;if(/[\\/]/.test(name))throw new Error('请输入单个目录名称。');await api('/storage/servers/'+id+'/folders',{path:join(directory,name)});await browse(id,directory);});};host.querySelector('#storage-archive-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/storage/servers/'+id+'/archive',{jobId:host.querySelector('#storage-job').value,directory});if(isActive()){notify('PDF 已归档。');await render(container,isActive);await browse(id,directory);}});};
|
||||
closePreview();
|
||||
host.innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title">${esc(server.name)} · 目录浏览</h3><button class="btn btn-sm ms-auto" id="storage-browser-close">关闭目录</button></div><div class="card-body"><div class="d-flex gap-2 align-items-center mb-3"><button class="btn btn-sm" id="storage-up" ${directory?'':'disabled'}>上一级</button><span class="text-break">/${esc(directory)}</span></div><div class="list-group mb-3">${listing.entries.map((entry,index)=>`<div class="list-group-item d-flex flex-wrap gap-2 align-items-center"><span class="text-break flex-fill">${esc(entry.name)}</span>${entry.type==='directory'?`<button class="btn btn-sm" data-storage-dir="${index}">打开目录</button>`:entry.type==='file'?`<button class="btn btn-sm" data-storage-preview="${index}">预览</button><a class="btn btn-sm" href="/api/storage/servers/${id}/file?path=${encodeURIComponent(join(directory,entry.name))}" download>下载文件</a>`:''}</div>`).join('')||'<div class="text-secondary p-3">当前目录为空</div>'}</div>${listing.truncated?'<div class="text-secondary small mb-3">仅显示前 500 项</div>':''}<div id="storage-file-preview" class="mb-3"></div><form id="storage-folder-form" class="d-flex flex-wrap gap-2 mb-4"><label class="visually-hidden" for="storage-folder">新目录名称</label><input class="form-control flex-fill" id="storage-folder" placeholder="新目录名称" required maxlength="200"><button class="btn" type="submit">创建目录</button></form><form id="storage-archive-form"><label class="form-label" for="storage-job">归档 PDF</label><select class="form-select" id="storage-job" required><option value="">请选择已完成的 PDF</option>${jobs.jobs.filter(j=>j.downloadable).map(j=>`<option value="${esc(j.jobId)}">${esc(j.filename||j.metadata?.order||j.jobId)}</option>`).join('')}</select><div class="text-end mt-3"><button class="btn btn-primary" type="submit">归档到当前目录</button></div></form></div></section>`;
|
||||
host.querySelectorAll('[data-storage-preview]').forEach(button=>button.onclick=()=>{
|
||||
closePreview();const filename=listing.entries[Number(button.dataset.storagePreview)].name,path=join(directory,filename),mount=host.querySelector('#storage-file-preview');
|
||||
mount.innerHTML=`<section class="storage-file-preview"><div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong class="text-break flex-fill">${esc(filename)}</strong><a class="btn btn-sm" href="/api/storage/servers/${id}/file?path=${encodeURIComponent(path)}" download>下载原文件</a><button class="btn btn-sm" id="storage-preview-fullscreen">全屏预览</button><button class="btn btn-sm" id="storage-preview-close">关闭预览</button></div><div id="storage-preview-mount"></div></section>`;
|
||||
preview=window.StoragePreview.open({container:mount.querySelector('#storage-preview-mount'),serverId:id,path,isActive});
|
||||
mount.querySelector('#storage-preview-close').onclick=closePreview;mount.querySelector('#storage-preview-fullscreen').onclick=e=>action(e.currentTarget,()=>preview?.fullscreen());
|
||||
});
|
||||
host.querySelector('#storage-browser-close').onclick=()=>{closePreview();host.replaceChildren();};host.querySelector('#storage-up').onclick=e=>action(e.currentTarget,()=>browse(id,directory.split('/').slice(0,-1).join('/')));host.querySelectorAll('[data-storage-dir]').forEach(b=>b.onclick=()=>action(b,()=>browse(id,join(directory,listing.entries[Number(b.dataset.storageDir)].name))));host.querySelector('#storage-folder-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{const name=host.querySelector('#storage-folder').value;if(/[\\/]/.test(name))throw new Error('请输入单个目录名称。');await api('/storage/servers/'+id+'/folders',{path:join(directory,name)});await browse(id,directory);});};host.querySelector('#storage-archive-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/storage/servers/'+id+'/archive',{jobId:host.querySelector('#storage-job').value,directory});if(isActive()){notify('PDF 已归档。');await render(container,isActive);await browse(id,directory);}});};
|
||||
}
|
||||
container.querySelectorAll('[data-storage-browse]').forEach(b=>b.onclick=()=>action(b,()=>browse(b.dataset.storageBrowse)));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user