301 Commits

Author SHA1 Message Date
keven
f1e956ad4c Merge pull request 'dev/0.11' (#3) from dev/0.11 into main
Reviewed-on: https://gitea.fudaoyuan.icu/keven/015/pulls/3
2026-05-24 18:21:29 +08:00
keven1024
7793bef944 fix(FileShareResult): set staleTime to Infinity for create-share query to prevent data refetching 2026-05-24 18:20:28 +08:00
keven1024
1fdd05f0ea feat(Tiptap): add internationalization support for word and length display in multiple languages 2026-05-24 18:18:20 +08:00
keven1024
7128a8c329 feat(Toaster): implement Sonner component for enhanced notification functionality and update import path in default layout 2026-05-24 17:55:19 +08:00
keven1024
3cb878b770 chore(dependencies): add nuxt-lucide-icons@2.1.0 to pnpm-lock.yaml and import Button component in BaseCard.vue for enhanced UI functionality 2026-05-24 14:49:01 +08:00
keven1024
05c3504627 feat(AboutBaseInfo): integrate Avatar, Accordion, and MarkdownRender components for enhanced UI functionality 2026-05-24 14:47:48 +08:00
keven1024
9b1ba13ec3 chore(dependencies): add nuxt-lucide-icons package to enhance icon support in the project 2026-05-24 14:43:01 +08:00
keven1024
2a4fac717a chore(dependencies): update TypeScript, @vueuse/core, and @vueuse/nuxt to 6.0.3 and 14.3.0 respectively, and upgrade various packages in package.json and pnpm-lock.yaml for improved compatibility and functionality 2026-05-24 14:37:07 +08:00
keven1024
e897fe1ed3 chore(dependencies): downgrade markdown-it to 14.1.1 in package.json and pnpm-lock.yaml for consistency and compatibility 2026-05-24 14:26:14 +08:00
keven1024
0aae4c2d36 chore(dependencies): downgrade @tanstack/vue-query and @tanstack/query-core to 5.100.13, update tinyexec to 1.1.2, and add markdown-it@14.1.1 in pnpm-lock.yaml for consistency and compatibility 2026-05-24 14:16:39 +08:00
keven1024
549bdd9f68 chore(dependencies): replace lucide-vue-next imports with @lucide/vue across multiple components for consistency and improved dependency management 2026-05-24 14:06:03 +08:00
keven1024
f956130b4f chore(dependencies): replace lucide-vue-next with @lucide/vue in package.json and update lint workflow for improved dependency management 2026-05-24 14:03:49 +08:00
keven1024
218b4cc6ac chore(dependencies): add @lucide/vue@1.16.0 and update @tanstack/vue-query to 5.100.12 in package.json and pnpm-lock.yaml for enhanced functionality 2026-05-24 13:57:07 +08:00
keven1024
64a936835c chore(dependencies): update @tanstack/vue-query to 5.100.14, markdown-it to 14.2.0, and nuxt to 4.4.6 in package.json and pnpm-lock.yaml for improved compatibility and features 2026-05-24 13:12:26 +08:00
keven1024
b8e4bee050 refactor(layout): replace background div with paragraph for improved semantic structure and maintain background image functionality 2026-05-24 13:06:58 +08:00
keven1024
7e90c54b27 chore(docker): add NODE_OPTIONS environment variable to Dockerfile for increased memory allocation during build 2026-05-24 11:41:20 +08:00
keven1024
ac8b6f642b refactor(i18n): consolidate i18n logic into pkg/i18n, fix TOML loading issue, and migrate translation files 2026-05-24 11:29:11 +08:00
keven1024
af6ca85ff5 docs(README): update screenshots section for clarity, enhance quick start instructions, and refine project structure details 2026-05-24 11:29:02 +08:00
keven1024
02900ab1f9 chore(docker): refactor Dockerfile to streamline build stages, update Node.js version, and adjust environment variables for improved deployment 2026-05-24 11:16:25 +08:00
keven1024
bdf7894e9b chore(docker): update Dockerfile to set CI environment variable, modify port configuration, and include Caddyfile for improved service management 2026-05-24 11:16:25 +08:00
keven1024
a8f504f377 refactor(config): comment out text-translate feature configuration in GetConfig and TextShareDrawer for future implementation 2026-05-24 11:16:25 +08:00
keven1024
cf92a50c82 chore(mail): add .gitkeep file to pkg/mail/out directory for template management 2026-05-24 11:16:25 +08:00
keven1024
848a0ff71b fix(notify): handle URL parsing error in SendEmail function to prevent potential crashes 2026-05-24 11:16:25 +08:00
keven1024
2f3acc76cd feat(config): add site_enable_bg property to configuration for background image control 2026-05-24 11:16:25 +08:00
keven1024
c89d1b554f feat(config): add site_enable_bg property to app configuration and update layout to conditionally render background image 2026-05-24 11:16:25 +08:00
keven1024
71737ebedc chore(docker): update Dockerfile to include email template generation and Caddy configuration 2026-05-24 11:16:25 +08:00
keven1024
b735200418 chore(gitignore): update .gitignore to include config.yaml and pkg/mail/out/ for better file management 2026-05-24 11:16:25 +08:00
keven1024
6084acb0d5 chore(deps): update package dependencies in pnpm-lock.yaml and package.json files for improved stability and performance 2026-05-24 11:16:25 +08:00
keven1024
a601964459 feat(asynq): implement Asynq initialization and client retrieval functions 2026-05-24 11:16:25 +08:00
keven1024
8758325da3 feat(redis): initialize Redis client and update context handling in Redis operations 2026-05-24 11:15:44 +08:00
keven1024
18ca80bb1b feat(front): add Vitest configuration and unit tests for calcFileHash to ensure consistency between native and wasm engines 2026-05-24 11:15:44 +08:00
keven1024
958ca799da refactor(http): simplify HTTPBaseResponse options by removing interface and using functional options directly 2026-05-24 11:15:44 +08:00
keven1024
9a9418c564 feat(worker): integrate GeoIP functionality into email notifications and enhance email template with region information 2026-05-24 11:15:44 +08:00
keven1024
0cb30b6293 feat(models): enhance RedisShareInfo struct with NotifyWebhooks and Locale fields for improved notification handling 2026-05-24 11:15:43 +08:00
keven1024
8828924a1f feat(geoip): implement GeoIP functionality with initialization, IP geolocation retrieval, and unit tests 2026-05-24 11:15:43 +08:00
keven1024
3275b8f68f feat(i18n): update email notification translations across multiple languages for improved clarity and consistency 2026-05-24 11:15:43 +08:00
keven1024
95ef5d261b feat(worker): refactor SendEmail function to use structured EmailTemplateData and improve SMTP configuration handling 2026-05-24 11:15:43 +08:00
keven1024
52d041b4c2 feat(notifications): include client IP in notification payload for share events to improve tracking and context 2026-05-24 11:15:43 +08:00
keven1024
2ff06946e1 feat(i18n): add translations for share type in multiple languages to enhance notification clarity 2026-05-24 11:15:43 +08:00
keven1024
4c6a18c063 feat(notifications): implement webhook and email notification services for share events, enhancing user communication capabilities 2026-05-24 11:15:43 +08:00
keven1024
bbf6ea561d feat(i18n): add initial i18n package with support for multiple languages and email notification translations 2026-05-24 11:15:43 +08:00
keven1024
1449664ca5 feat(deps): add sweet-curl-parser package version 1.0.4 to pnpm-lock.yaml for enhanced cURL parsing capabilities 2026-05-24 11:15:43 +08:00
keven1024
4a3ec790b7 feat(docs): add body field for webhook configuration in UI and enhance cURL import functionality to auto-fill request details 2026-05-24 11:15:43 +08:00
keven1024
f4a28e369f feat(i18n): add 'add' translation in multiple languages and update InputGroupField, KvInputGroupField, and NotifyConfigField components to use localized text for button labels 2026-05-24 11:15:43 +08:00
keven1024
833079d495 feat(front): enhance NotifyConfigField component to support parsing of cURL commands and add body field for webhook configuration 2026-05-24 11:15:43 +08:00
keven1024
a63d55b61d feat(i18n): update webhook body translations in multiple languages for consistency and clarity 2026-05-24 11:15:43 +08:00
keven1024
46c6cd84b5 feat(front): enhance FileShareHandle and TextShareHandle components with improved layout and overflow handling for better user experience 2026-05-24 11:15:43 +08:00
keven1024
84e747a909 feat(config): add initial configuration file for spec-driven development with project context and proposal rules 2026-05-24 11:15:43 +08:00
keven1024
a24bf24271 feat(front): enhance KvInputGroupField and NotifyConfigField components with autocomplete functionality and improved header configuration 2026-05-24 11:15:43 +08:00
keven1024
1226a7948e feat(front): add Command components for command palette functionality including Command, CommandDialog, CommandInput, and related components 2026-05-24 11:15:43 +08:00
keven1024
1e446a0240 refactor(front): simplify InputGroupField and KvInputGroupField components by removing unused state and streamlining item addition and update logic 2026-05-24 11:15:43 +08:00
keven1024
b023876e0f feat(front): update GlobalDrawer component to support async close handling and improve drawer visibility management 2026-05-24 11:15:43 +08:00
keven1024
ec1d70637b feat(i18n): add notification settings translations for multiple languages including email and webhook configurations 2026-05-24 11:15:43 +08:00
keven1024
6934bba7a1 feat(backend): enhance share creation with notification settings and webhook support 2026-05-24 11:15:43 +08:00
keven1024
2e5da4f7e9 feat(front): implement NotifyConfigField component for enhanced notification settings in FileShareHandle and TextShareHandle components 2026-05-24 11:15:43 +08:00
keven1024
d8704a8aa8 fix(front): adjust error message font size in InputField and InputGroupField components for better readability 2026-05-24 11:15:43 +08:00
keven1024
2273c589f6 fix(front): update success message for copy action in CopyButton and refactor token handling in FileShareView 2026-05-24 11:15:43 +08:00
keven1024
a14628718c feat(i18n): add notification messages for webhook configuration and update common copy success messages across multiple languages 2026-05-24 11:15:43 +08:00
keven1024
528df24988 refactor(front): replace clipboard functionality with CopyButton component in FileShareResult, TextShareResult, and TextShareView components 2026-05-24 11:15:43 +08:00
keven1024
2a42ca8cde feat(front): add CopyButton component for clipboard functionality and update icon sizes in existing components 2026-05-24 11:15:43 +08:00
keven1024
6edb1fe222 feat(front): enhance InputField component with validation support and error messaging 2026-05-24 11:15:43 +08:00
keven1024
c841d8e1a2 feat(front): update InputGroupField component with improved delete button styling and add new Textarea component for enhanced text input 2026-05-24 11:15:43 +08:00
keven1024
e8b5f98260 feat(front): add error handling to InputGroupField component with aria attributes for accessibility 2026-05-24 11:15:43 +08:00
keven1024
706464ce3c feat(backend): add default enabled features for file and text sharing in configuration 2026-05-24 11:15:43 +08:00
keven1024
b52d4c3a51 feat(front): add InputGroupField component for dynamic input management with add/remove functionality 2026-05-24 11:15:43 +08:00
keven1024
e9fc260cbc refactor(front): standardize import statements and improve prop handling in Select components 2026-05-24 11:15:43 +08:00
keven1024
e37402ff63 feat(front): enhance chart tooltip functionality with custom value formatting and update date format 2026-05-24 11:15:43 +08:00
keven1024
35654372a6 chore(front): add file-type and heic-to dependencies, and update FileIcon component to support file type detection 2026-05-24 11:15:43 +08:00
keven1024
018d13ea78 refactor(front): improve image handling in FileIcon component by adding HEIC support and optimizing file type checks 2026-05-24 11:15:43 +08:00
keven1024
0e0f6bb1c5 feat(front): implement engine detection for file hash calculation and add error handling for unsupported environments 2026-05-24 11:15:42 +08:00
keven1024
7ba7af6100 refactor(front): enhance drawer management by introducing DrawerItem type for improved type safety and structure 2026-05-24 11:15:42 +08:00
keven1024
55eb50faab fix(front): update outline-none utility in MarkdownRender and Tiptap components for consistent styling 2026-05-24 11:15:42 +08:00
keven1024
87d337c2a1 chore(deps): update go.work.sum and pnpm-lock.yaml to include new dependencies and remove obsolete ones 2026-05-24 11:15:42 +08:00
keven1024
2fc2f4ccf7 test(front): add unit tests for calcFileHash to verify consistency between native and wasm engines, and ensure correct hash format and uniqueness 2026-05-24 11:15:42 +08:00
keven1024
10a82a1751 chore(deps): update go.sum files to include module hashes for various dependencies and their go.mod files 2026-05-24 11:15:42 +08:00
keven1024
a5a01a667e refactor(front): replace MD5 with SHA1 for user avatar generation and update related components to use native hash calculation 2026-05-24 11:15:42 +08:00
keven1024
907f77aa66 refactor(backend): update file hash calculation from MD5 to SHA1 and rename related error handling 2026-05-24 11:15:42 +08:00
keven1024
ae2fbcc216 feat(front): enhance file hash calculation by introducing engine selection for large files using native or wasm methods 2026-05-24 11:15:42 +08:00
keven1024
f1dc65b1d0 feat(front): add FileIcon components for audio, video, image, and generic file previews with dynamic thumbnail extraction 2026-05-24 11:15:42 +08:00
keven1024
881d8e111a fix(front): update import path for filePreview type in FilePreviewView component 2026-05-24 11:15:42 +08:00
keven1024
58ba3f6d50 feat(front): add language support for multiple locales including English, German, French, Japanese, Korean, and Chinese with updated translations for locale switching 2026-05-24 11:15:42 +08:00
keven1024
788ef8df57 feat(front): add FileIcon component for dynamic file previews and icons based on file type 2026-05-24 11:15:42 +08:00
keven1024
d0021f9468 feat(backend): refactor GetConfig to extract enabled feature keys and include text-translate provider configuration 2026-05-24 11:15:42 +08:00
keven1024
a99790c9b1 feat(front): add support for additional locales including Japanese, Korean, French, German, and Traditional Chinese in nuxt.config.ts and update app config structure for text translation 2026-05-24 11:15:42 +08:00
keven1024
249b9f2350 feat(front): update I18nSwitchDrawer to support new locale structure and add German, French, Japanese, Korean, and Traditional Chinese translations 2026-05-24 11:15:42 +08:00
keven1024
6a7e8f85ac feat(backend): add text translation handler and update task mapping for new translation functionality 2026-05-24 11:15:42 +08:00
keven1024
3f5f8b3c97 feat(worker): implement multi-provider text translation service with Google, Microsoft, and custom LLM support 2026-05-24 11:15:42 +08:00
keven1024
f8b5b82179 feat(backend): add text translation functionality with new task payload structure 2026-05-24 11:15:42 +08:00
keven1024
0d4d89d4ec feat(front): add text-translate feature with corresponding UI components and action handlers 2026-05-24 11:15:42 +08:00
keven1024
2af28b6a50 feat(frontend): enhance SelectField and Tiptap components with improved class handling and word count display 2026-05-24 11:15:42 +08:00
keven1024
a1808a64cc fix(backend): improve error handling in DownloadShare by consolidating token validation and share info retrieval 2026-05-24 11:15:42 +08:00
keven1024
499b931c04 refactor(backend): streamline Redis operations in file and share handling by utilizing handler functions for improved data management 2026-05-24 11:15:42 +08:00
keven1024
1298bf79d3 refactor(backend): enhance DownloadShare functionality with context management and improve Redis share info handling 2026-05-24 11:15:42 +08:00
keven1024
83f6be0486 fix(models): handle JSON marshaling errors in SetRedis functions to improve error handling and data integrity 2026-05-24 11:15:42 +08:00
keven1024
17fa39b830 refactor(backend): update SetRedisFileInfo to use handler functions for better data manipulation and simplify file merging process with io.CopyBuffer 2026-05-24 11:15:42 +08:00
keven1024
55949d1f76 refactor(models): remove mergo dependency and update SetRedisFileInfo and SetRedisShareInfo to use handler functions for improved data handling 2026-05-24 11:15:42 +08:00
keven1024
d3e7760aea fix(backend): handle missing share information in DownloadShare and refactor SetRedisShareInfo to use a function for updating view count 2026-05-24 11:15:41 +08:00
keven1024
7566ddb5f2 fix(pkg): simplify task scheduling by removing unnecessary duration conversion in SetFileRemoveTask 2026-05-24 11:15:41 +08:00
keven1024
78624b302d feat(config): add new commands for apply, archive, explore, and propose workflows in the experimental OpenSpec framework
(cherry picked from commit bfccbf60e4)
2026-05-24 11:01:08 +08:00
keven
759318813c Merge pull request 'dev/0.1.0' (#2) from dev/0.10 into main
Reviewed-on: https://gitea.fudaoyuan.icu/keven/015/pulls/2
2026-04-06 10:31:57 +08:00
keven1024
a91345f39c feat(config): add feature flags for file sharing and image processing in config.example.yaml 2026-04-06 10:31:33 +08:00
keven1024
123b1ec4fb chore(vscode): add launch configuration for backend development in launch.json 2026-04-06 09:30:02 +08:00
keven1024
79887d6c6c chore(backend): update dependencies in go.mod and go.sum for compatibility and performance improvements 2026-04-06 09:29:51 +08:00
keven1024
f1f10de051 chore(backend): downgrade dependencies in go.mod and go.sum for compatibility and stability 2026-04-06 09:28:33 +08:00
keven1024
80d60cc0a0 chore(deps): add miniredis dependency to go.work.sum and update image tagging strategy in publish.yaml for edge version handling 2026-04-06 08:38:55 +08:00
keven1024
30d0abc2b5 chore(workflows): update image tagging strategy in publish.yaml to use semver and improve deployment conditions 2026-04-05 14:03:17 +08:00
keven1024
8d3675cfa1 fix(front): convert layoutId to string to ensure proper rendering of speed chart items 2026-04-05 13:19:49 +08:00
keven1024
cb6b0fae6a refactor(front): remove unused chart components and streamline chart implementation for improved maintainability 2026-04-05 13:19:32 +08:00
keven1024
6631e1e1a2 refactor(front): update FileUpload and Navbar components for improved code clarity and consistency 2026-04-05 12:05:33 +08:00
keven1024
625399bdd9 chore(front): remove service worker implementation to streamline front-end architecture 2026-04-05 11:59:00 +08:00
keven1024
10b79615b7 chore(front): update pnpm-lock.yaml with dependency version upgrades for improved compatibility and performance 2026-04-05 11:50:47 +08:00
keven1024
7c38773451 chore(front): update dependencies in package.json to latest versions for improved performance and security 2026-04-05 11:50:35 +08:00
keven1024
976011697c fix(seo): integrate nuxtApp context for SEO meta handling and ensure proper execution within server environment 2026-04-05 11:48:44 +08:00
keven1024
c25b41e20e fix(worker): lint err 2026-04-05 11:28:22 +08:00
keven1024
3c031dcee9 feat: enhance FileIcon and FileUpload components to support size prop and multi-file uploads, improving user experience and flexibility 2026-04-05 11:09:43 +08:00
keven1024
d6c54de659 feat: add file deduplication logic in FileUploadField component to prevent duplicate file uploads from clipboard and file selection 2026-04-05 10:32:51 +08:00
keven1024
72ca69330f refactor: simplify tsconfig.json by removing unnecessary compiler options and ensuring proper structure 2026-04-05 10:16:34 +08:00
keven1024
7f74441f5d feat: enhance About component with feature display and loading states, and refactor feature handling in share drawers for improved user experience 2026-04-05 09:46:56 +08:00
keven1024
28abd8d1a2 feat: implement feature-based action handling in file and text share drawers, enhancing user interaction with dynamic feature support 2026-04-04 23:07:43 +08:00
keven1024
c50bb5d0bf refactor: update environment variable handling to use GetEnvMap for improved type safety and add feature extraction functionality 2026-04-04 21:42:25 +08:00
keven1024
95ab8b97da refactor(pkg): ensure Redis client initialization is properly assigned during concurrent access 2026-04-04 21:21:27 +08:00
keven1024
d6880dbf00 refactor: improve context management in Redis stat updates by utilizing context in locking mechanism 2026-04-04 21:20:17 +08:00
keven1024
c871c55f79 refactor: enhance Redis lock utility by adding expiration duration support and improving context management 2026-04-04 16:18:19 +08:00
keven1024
82e9292b66 feat: add Redis lock utility for managing distributed locks with rueidislock 2026-04-04 16:02:38 +08:00
keven1024
1d86f2bdf6 refactor: update dependencies across multiple modules, including upgrading asynq to v0.26.0, Redis to v9.18.0, and various golang.org/x packages for improved performance and compatibility 2026-04-04 13:50:21 +08:00
keven1024
52cc89a73d refactor: implement session management using Gorilla sessions and streamline session retrieval in middleware 2026-04-04 13:47:12 +08:00
keven1024
af9a5b45d2 refactor: update Redis operations to use rueidis client for improved performance across multiple models 2026-04-04 12:45:08 +08:00
keven1024
b26821a504 refactor: migrate Redis client implementation from go-redis to rueidis for improved performance and functionality 2026-04-04 12:16:28 +08:00
keven1024
560387d8f1 refactor: streamline Redis stat updates by using a handler function to modify stat data directly 2026-04-04 11:01:50 +08:00
keven1024
b69af056aa feat: implement internationalization for share views and update UI text for better user experience 2026-03-08 14:57:46 +08:00
keven1024
707ade5dd2 chore: add .air.toml configuration files for backend and worker to streamline development and build processes 2026-03-08 12:34:21 +08:00
keven1024
b4570c5961 fix: update image conversion logic to handle JPG format by flattening transparent PNGs to a white background 2026-03-08 12:21:02 +08:00
keven1024
60a588c92a chore: add test.webp image and update image conversion tests to include webp format 2026-03-08 12:20:39 +08:00
keven1024
47781ff374 chore: update Dockerfile to rename output binary from 'backend' to 'backend-bin' for consistency in build process 2026-03-08 09:23:21 +08:00
keven1024
7760697233 chore: update Dockerfile to rename output binary from 'worker' to 'worker-bin' for clarity in build process 2026-03-08 09:22:33 +08:00
keven1024
8f1ced62ac chore: refactor publish workflow to separate build and deploy jobs, enhancing clarity and maintainability 2026-03-07 10:57:58 +08:00
keven1024
72560cf233 chore: enhance publish workflow by adding conditional tag for main branch deployment 2026-03-07 10:06:38 +08:00
keven1024
62443f38a4 chore: update Dockerfile to include imagemagick for enhanced image processing capabilities 2026-03-07 09:40:12 +08:00
keven1024
5c264a4297 chore: enhance Docker build workflows by adding QEMU setup and multi-platform support for amd64 and arm64 2026-03-07 09:29:06 +08:00
keven
332fa7195f Merge pull request '0.0.9' (#1) from dev into main
Reviewed-on: https://gitea.fudaoyuan.icu/keven/015/pulls/1
2026-03-07 09:24:01 +08:00
keven1024
4ce68d91a8 Merge branch 'main' into dev 2026-03-05 17:38:32 +08:00
keven1024
78cfc3943c chore: update build and publish workflows to use root context for Docker builds 2026-03-02 00:10:47 +08:00
keven1024
7772a935d7 fix: go work sync 2026-03-02 00:05:28 +08:00
keven1024
7d204345cc chore: streamline Dockerfile configurations by consolidating module downloads and improving source code organization 2026-03-02 00:04:21 +08:00
keven1024
f9251663a2 chore: refactor Dockerfiles to improve module management and build process by adding workspace support and restructuring source code copying 2026-03-01 23:55:27 +08:00
keven1024
75c269b60e chore: update Go version in Dockerfiles to 1.25.5 for improved compatibility and performance 2026-03-01 23:44:02 +08:00
keven1024
64126e7c4c chore: update packageManager version in package.json files for consistent dependency management 2026-03-01 23:32:55 +08:00
keven1024
f8a43c9b1f feat: add build and publish workflows for Docker images with automated tagging and deployment 2026-03-01 23:28:19 +08:00
keven1024
9aa52915b0 feat(front): implement ImageConvertResult component for image format conversion and update layout in ImageCompressResult 2026-02-28 10:23:45 +08:00
keven1024
fe66240671 feat(front): add translation for image format conversion in English and Chinese locales 2026-02-28 10:16:56 +08:00
keven1024
1635a31f33 feat(front): add image conversion option to FileShareDrawer and improve layout in ImageCompressResult 2026-02-28 10:16:34 +08:00
keven1024
67b1d07fbe feat(front): implement ImageConvertHandle component for image format selection and conversion 2026-02-28 10:08:00 +08:00
keven1024
ceb2d026d2 fix(worker): ensure temporary files are removed on error during image compression and conversion 2026-02-27 18:47:16 +08:00
keven1024
123178084a feat(worker): enhance image conversion tests to support multiple formats and improve error handling 2026-02-27 18:30:49 +08:00
keven1024
183297bd2c feat(front): add support for image conversion in Preprocessing and Result components 2026-02-27 17:56:43 +08:00
keven1024
55900224ae refactor(front): improve layout of ImageCompressResult component for better file display 2026-02-27 17:56:19 +08:00
keven1024
a64fa95608 feat(worker): add ImageConvertResult component and enhance image processing with WebP support 2026-02-27 17:41:23 +08:00
keven1024
70fc2be02f feat(worker): enhance GenStandardFile to set file expiration and store expiration info in Redis 2026-02-27 17:06:44 +08:00
keven1024
e14eed73c4 refactor(front): update download and view options to use array syntax for translation labels 2026-02-27 16:53:00 +08:00
keven1024
4a8932f921 feat(worker): introduce ErrFileNotFound for consistent error handling and update GenStandardFile to use it 2026-02-27 16:39:25 +08:00
keven1024
60831c779e feat: add backend and worker test scripts to package.json and create a combined test command 2026-02-27 16:24:21 +08:00
keven1024
7663e8eb0a fix(backend): improve error handling in controllers and services by checking errors from Redis operations and adding error comments for deferred function calls 2026-02-27 15:42:02 +08:00
keven1024
fe6c832275 refactor(backend): replace error handling with predefined error variables for consistency across download and upload tasks 2026-02-27 15:10:59 +08:00
keven1024
f1dec39851 feat(backend): add image conversion handler and refactor image compression logic into a new file 2026-02-27 14:59:09 +08:00
keven1024
59cd23daf7 feat(worker): add image conversion endpoint and update file utility references in tasks 2026-02-27 14:38:31 +08:00
keven1024
7ca301e54d chore(worker): update go.mod and go.sum to include new indirect dependencies and replace error handling in image conversion 2026-02-27 14:33:43 +08:00
keven1024
6d7dc6bc40 chore: add config.yaml to .gitignore to prevent tracking of configuration files 2026-02-27 14:33:02 +08:00
keven1024
bde4e36e47 feat(worker): add image conversion functionality and support for WEBP format in image compression 2026-02-27 14:32:42 +08:00
keven1024
e5b5def6f0 refactor: migrate file utility functions to services package and update references in controllers; remove deprecated utils file 2026-02-27 12:18:18 +08:00
keven1024
ed7ac4e657 feat(utils): add file utility functions for MD5 hashing, file ID generation, and upload directory management 2026-02-27 12:08:13 +08:00
keven1024
22637bcf6e feat(worker): add image conversion functionality with Magick and support for additional formats 2026-02-27 11:23:48 +08:00
keven1024
3d8d1ccd3f fix(front): conditionally render title in BaseCard component to prevent display issues when title is not provided 2026-02-26 18:57:55 +08:00
keven1024
ae7db9de02 feat(front): implement internationalization for image compression results with dynamic text updates in ImageCompressResult component 2026-02-26 18:29:21 +08:00
keven1024
6304dffa39 feat(front): add showBackButton prop to BaseCard component and update usages in FileShareResult and TextShareResult for improved navigation 2026-02-26 18:23:24 +08:00
keven1024
2ea2d89f44 refactor(front): replace div elements with BaseCard component for consistent styling across various views 2026-02-26 18:11:35 +08:00
keven1024
b98853ebe1 chore(deps): upgrade echo framework from v4 to v5 and remove custom context middleware 2026-02-26 16:09:47 +08:00
keven1024
e9d0848f87 refactor(worker): replace direct command execution with utility function for image compression and update test output for accuracy 2026-02-25 15:35:28 +08:00
keven1024
155c697e53 feat(services): implement image compression functionality for PNG and JPEG formats with corresponding unit tests 2026-02-25 12:04:22 +08:00
keven1024
301dcaf8b6 chore(front): comment out BubbleMenuView in Tiptap component for future adjustments 2026-02-25 12:03:15 +08:00
keven1024
8f3bafcbfb fix(front): ensure chunks default to an empty array in FileUploadProgressView for improved upload handling 2026-02-25 12:02:53 +08:00
keven1024
b471972dd4 chore(deps): update dependencies 2026-01-30 14:44:43 +08:00
keven1024
8c4c7b0471 feat(front): add axios for API requests and enhance FileUploadProgressView with speed tracking and UI improvements 2026-01-10 14:34:01 +08:00
keven1024
9679a42be2 feat(front): refactor FileUploadProgressView components to improve upload management and user experience with detailed progress tracking and new UI elements 2026-01-10 11:50:00 +08:00
keven1024
e43d27958d feat(utils): enhance InitEnv function to support multiple config types and add unit tests for environment initialization 2025-12-27 11:18:45 +08:00
keven1024
31c0736562 feat(backend): add password hashing error handling and implement HTTP utility tests 2025-12-27 11:04:21 +08:00
keven1024
185f7a3503 fix(backend): improve error handling in GetFileSliceList function to ignore non-existent directory errors 2025-12-21 21:17:36 +08:00
keven1024
90607aad7c feat(front): enhance FileUploadProgressView component to include chunk tracking for improved upload management 2025-12-21 17:52:23 +08:00
keven1024
e250202deb refactor(backend): enhance file upload handling by improving error management and restructuring CreateFileSlice and MergeFileSlices functions for better clarity 2025-12-21 17:21:19 +08:00
keven1024
e8653a8e8b refactor(backend): update UploadFileSlice and CreateFileSlice functions to include upload path handling for improved file management 2025-12-21 16:19:57 +08:00
keven1024
b4a4be09fa feat(front): add localization for upload speed calculation in FileUploadSpeedInfoView component to enhance user understanding 2025-12-20 10:39:57 +08:00
keven1024
bfe9a8f3d6 feat(front): enhance FileUploadProgressView component with new localization keys for improved user feedback and clarity during file upload processes 2025-12-20 10:11:13 +08:00
keven1024
a71cc5e919 chore(lint): enable skip-cache option for golangci-lint in Gitea workflow to improve linting performance 2025-12-20 09:43:53 +08:00
keven1024
18a626fd04 chore(lint): update actions and Node.js version in Gitea workflow for improved compatibility and performance 2025-12-20 09:38:27 +08:00
keven1024
ca33fcc332 refactor(front): update localization keys across components to improve consistency and maintainability 2025-12-20 09:22:58 +08:00
keven1024
85c6b4582f refactor(front): update download and view options in FileShareHandle and TextShareHandle components to use new localization keys for improved flexibility 2025-12-20 09:05:59 +08:00
keven1024
9eaf06e7a8 fix(front): add conditional rendering for file sizes in ImageCompressResult component to handle zero values and improve user experience 2025-12-20 08:53:25 +08:00
keven1024
0c980e8b6c chore(lint): rename lint action step for clarity and consistency in Gitea workflow 2025-12-20 08:42:05 +08:00
keven1024
831d9b2660 refactor(front): optimize ImageCompressResult component for better file handling and task status display 2025-12-18 23:08:16 +08:00
keven1024
dd3ced5b03 refactor(front): enhance ImageCompressResult component to support multiple file uploads and improve task management with useQueries 2025-12-17 08:26:23 +08:00
keven1024
d7d2a5c00b refactor(front): update component props and types for FileShareResult and TextShareResult, and introduce a new types file for better type management 2025-12-17 08:11:02 +08:00
keven1024
a82c894119 feat(backend): implement task management endpoints for image compression and task retrieval 2025-12-16 22:19:43 +08:00
keven1024
d4b0368ae2 chore(lint): upgrade golangci-lint-action from v6 to v9 in Gitea workflow for improved linting capabilities 2025-12-14 20:23:46 +08:00
keven1024
f317e0f538 chore(lint): simplify linting commands by using working-directory for backend and worker jobs in Gitea workflow 2025-12-14 20:18:36 +08:00
keven1024
e17b1a04c5 chore(front): remove transformMixedEsModules option from Vite configuration to streamline build process 2025-12-14 20:11:56 +08:00
keven1024
04ebb22d35 chore: add linting scripts for frontend, backend, and worker, and create a Gitea workflow for automated linting on push and pull request events 2025-12-14 20:10:52 +08:00
keven1024
552434e389 fix(front): update CircularProgress and FileIcon components to handle default values and null checks, and improve styling in FileUploadProgressView 2025-12-14 19:53:11 +08:00
keven1024
d5fc54de31 refactor(worker): streamline utility functions by removing unused files, update Redis client and environment variable handling, and enhance task logging for better clarity 2025-12-14 16:25:58 +08:00
keven1024
675a6e860a feat(pkg): add async queue and Redis client utilities, implement environment variable management with viper 2025-12-14 16:25:20 +08:00
keven1024
18a74b6545 refactor(backend): restructure main application by separating middleware and route definitions into dedicated files, update environment variable handling, and improve code organization for better maintainability 2025-12-14 16:25:00 +08:00
keven1024
313ce4455f chore: update Go modules to version 1.25.5, restructure models into pkg/models, and remove unused model files for improved organization and dependency management 2025-12-14 16:12:17 +08:00
keven1024
208875841e fix(front): Component GlobalDayjs.vue is missing template or render function. at <GlobalDayjs> 2025-12-13 12:02:45 +08:00
keven1024
35c5e1ccec chore: replace npm-run-all with concurrently in package.json for improved script execution and update pnpm-lock.yaml to reflect dependency changes 2025-12-13 11:48:51 +08:00
keven
6da3d9a15d chore(front): update package dependencies to latest versions, including Vue, Nuxt, and various plugins for improved performance and compatibility 2025-12-12 00:04:47 +08:00
keven
23c33fc52e chore(front): update package dependencies to latest versions for improved stability and features 2025-12-11 23:11:36 +08:00
keven
4f4139159e fix(front): add break-all class to MarkdownRender for improved text wrapping
(cherry picked from commit 62463494b4)
2025-11-12 14:34:54 +08:00
keven
62463494b4 fix(front): add break-all class to MarkdownRender for improved text wrapping 2025-11-12 14:33:20 +08:00
keven1024
c8fd8c874b docs: update README files to enhance screenshot presentation and improve layout consistency 2025-10-28 11:17:35 +08:00
keven
a8f0fb2bf3 fix(front): add max-w-full class to MarkdownRender in AboutBaseInfo for improved layout
(cherry picked from commit 0f0814ce40)
2025-10-28 09:25:21 +08:00
keven1024
70d35a1a15 docs: update README files to streamline Docker setup instructions and remove outdated environment configuration details
(cherry picked from commit 4355a29a52)
2025-10-28 09:21:07 +08:00
keven1024
4355a29a52 docs: update README files to streamline Docker setup instructions and remove outdated environment configuration details 2025-10-28 09:19:25 +08:00
keven
9e2a6411ec feat(config): add example configuration file with settings for sharing, uploading, redis, and site information
(cherry picked from commit 52af187fe9)
2025-10-28 08:26:43 +08:00
keven
d8bc68b008 chore: remove SITE_URL and UPLOAD_PATH environment variables from Dockerfile
(cherry picked from commit 647417fb4e)
2025-10-28 08:26:26 +08:00
keven
d2478dd23b chore: remove example environment file and update docker-compose for config file integration
(cherry picked from commit ea0065b415)
2025-10-28 08:24:58 +08:00
keven
647417fb4e chore: remove SITE_URL and UPLOAD_PATH environment variables from Dockerfile 2025-10-28 08:23:09 +08:00
keven
ea0065b415 chore: remove example environment file and update docker-compose for config file integration 2025-10-28 08:20:41 +08:00
keven
2194c9687f feat: add GNU Affero General Public License v3 to the project for open-source compliance
(cherry picked from commit 99538c6fdb)
2025-10-22 08:18:07 +08:00
keven
99538c6fdb feat: add GNU Affero General Public License v3 to the project for open-source compliance 2025-10-22 08:17:20 +08:00
keven
0f0814ce40 fix(front): add max-w-full class to MarkdownRender in AboutBaseInfo for improved layout 2025-10-19 20:53:41 +08:00
keven
15922ea2df chore(Dockerfile): comment out SITE_URL and UPLOAD_PATH environment variables for configuration flexibility 2025-10-19 20:51:37 +08:00
keven
52af187fe9 feat(config): add example configuration file with settings for sharing, uploading, redis, and site information 2025-10-19 18:58:45 +08:00
keven
9fff65d0d7 Revert "feat(front): add TextInlineAIDrawer and BubbleMenuView components for enhanced AI interaction and text formatting options"
This reverts commit d294027463.
2025-10-19 18:45:01 +08:00
keven
da58c53909 feat(front): add AboutVersionView component and enhance AboutBaseInfo with object-fit styling 2025-10-19 18:38:00 +08:00
keven
07fc182ccb feat(front): enhance About page components to support shares and downloads statistics, improve layout, and add loading state 2025-10-19 18:20:38 +08:00
keven
028d0c10fe refactor(backend): update statistics handling in GetStat function to include shares and downloads, and rename related data structures 2025-10-19 16:47:51 +08:00
keven
b4f577e758 feat(backend): implement statistics tracking for file uploads, shares, and downloads 2025-10-19 16:34:17 +08:00
keven
84c104be90 feat(backend, worker): add config watching and simplify error handling in InitEnv function 2025-10-19 15:23:42 +08:00
keven
a4b3dad85e feat(front): enhance localization support in AboutBaseInfo, useSeo, and default layout for improved SEO and user experience 2025-10-19 15:21:39 +08:00
keven
6238897c18 feat(front): add AboutBaseInfo and AboutChartView components for enhanced About page functionality and data visualization 2025-10-19 15:05:29 +08:00
keven
c931d10485 fix(backend): skip processing of queue items with zero processed and failed counts in GetStat function 2025-10-19 14:43:12 +08:00
keven
dd05510d27 feat(backend): implement About and Config endpoints, enhance GetStat with queue data and file size metrics 2025-10-19 14:39:46 +08:00
keven
5de6ed9eea Merge branch 'dev' of https://gitea.fudaoyuan.icu/keven/015 into dev 2025-10-19 14:07:17 +08:00
keven1024
7166ec5cb3 Merge branch 'dev' of https://gitea.fudaoyuan.icu/keven/015 into dev 2025-10-19 14:05:17 +08:00
keven1024
8676b12a66 feat(front): implement Accordion component and its subcomponents for enhanced UI interactivity and organization 2025-10-19 14:05:13 +08:00
keven
d8c9491a99 feat(front): enhance app configuration fetching and add localization support for "powered by" text 2025-10-19 13:33:55 +08:00
keven
e6cc1b0229 feat(backend): add About and Config controllers for dynamic environment variable retrieval 2025-10-19 10:19:28 +08:00
keven
50c0a14cc6 feat(front): implement dynamic API base URL retrieval and enhance SEO metadata handling 2025-10-19 00:26:12 +08:00
keven
1ed154913d refactor(backend,worker): update environment variable key for upload path to enhance consistency across modules 2025-10-19 00:10:09 +08:00
keven
12efc10e0e refactor(backend): standardize environment variable names for download and password handling, enhancing consistency and clarity 2025-10-19 00:05:56 +08:00
keven
b80cb0c2d8 refactor(backend,worker): update environment variable keys for consistency and improve configuration handling across backend and worker modules 2025-10-18 23:54:11 +08:00
keven
d294027463 feat(front): add TextInlineAIDrawer and BubbleMenuView components for enhanced AI interaction and text formatting options 2025-10-18 13:36:04 +08:00
keven1024
a66c5a26b0 Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-10-18 13:06:17 +08:00
keven1024
27fcfd73d9 feat(front): add Menubar component and its subcomponents for improved UI navigation and organization 2025-10-18 13:06:11 +08:00
keven
f525f48a8a Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-10-18 12:57:33 +08:00
keven1024
9961609e64 feat(front): implement DropdownMenu component and its subcomponents for enhanced UI interactivity and organization 2025-10-18 12:15:41 +08:00
keven
ff58262725 feat(vscode): add i18n-ally configuration for localization support in Vue projects 2025-10-18 11:00:04 +08:00
keven
80a01a2849 feat(front): add internationalization support to TextShareResult component, localizing titles and messages for enhanced user experience 2025-10-18 10:54:47 +08:00
keven
8924de58c0 feat(front): integrate GlobalDayjs component for dynamic date localization and formatting 2025-10-18 10:46:07 +08:00
keven
41b0076464 feat(front): add dayjs integration for date formatting in dev page, showcasing language pack rendering 2025-10-18 10:45:21 +08:00
keven
fa17009695 feat(front): enhance FileShareResult and FileUploadField components with internationalization support, adding localized text for file sharing success and related UI elements 2025-10-18 10:43:57 +08:00
keven
8fad0a4163 feat(front): implement internationalization for share options in FileShareHandle and TextShareHandle components, update layout in GlobalDrawer, and enhance FileUploadField with localized text 2025-10-18 09:41:45 +08:00
keven
836a3c866a feat(front): enhance PickupShareBtn and PickupShareDrawer components with internationalization support and improved user feedback for pickup code submission 2025-10-18 09:22:14 +08:00
keven
045031dd3c chore(front): update dependency versions for Tiptap and Vue Query to enhance functionality and compatibility 2025-10-18 00:13:17 +08:00
keven
3e8c782315 refactor(front): update MarkdownInputField import path and enhance TextUploadInputTextView component structure for improved readability 2025-10-17 23:57:51 +08:00
keven1024
77667024fd Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-10-17 23:01:26 +08:00
keven1024
9902f46c7a feat(front): add Tooltip component and related subcomponents for enhanced UI functionality 2025-10-17 23:01:21 +08:00
keven
164d07b8e0 style(front): enhance Markdown and Tiptap components with improved styling for blockquotes and selection background 2025-10-17 09:11:23 +08:00
keven1024
b59aec2d97 chore(front): update dependency versions for improved compatibility and stability, including upgrades to Tiptap, Tailwind CSS, Vue, and Pixi.js 2025-10-16 15:47:32 +08:00
keven1024
0df8ee0a8d Revert "refactor(front): replace MarkdownInputField with RichInputField for improved JSON handling in text uploads, update Tiptap component to support JSONContent, and increment dependency versions for better compatibility"
This reverts commit e959a0bc3e.
2025-10-16 15:43:55 +08:00
keven1024
083005dac3 fix(front): handle potential undefined values in file sharing logic to prevent runtime errors 2025-10-13 22:03:03 +08:00
keven1024
e959a0bc3e refactor(front): replace MarkdownInputField with RichInputField for improved JSON handling in text uploads, update Tiptap component to support JSONContent, and increment dependency versions for better compatibility 2025-10-13 21:27:28 +08:00
keven1024
6bd008f119 refactor(front): improve file upload progress handling by adding async wait to prevent UI freezing during upload tasks 2025-09-29 17:59:09 +08:00
keven
d306581e34 fix(front): 更新依赖项版本,将nuxt从3.18.0升级至4.1.2,以提高项目的稳定性和兼容性,同时更新pnpm-lock.yaml中的相关依赖项版本。 2025-09-23 09:28:19 +08:00
keven
f34ea51725 更新依赖项版本,包括@nuxt/image、@nuxtjs/i18n、@pinia/nuxt、@tailwindcss/postcss、@tailwindcss/vite、@tanstack/vue-query等,以提高项目的稳定性和兼容性。同时,更新了其他相关库的版本,确保与最新的Vue和TypeScript版本兼容。 2025-09-23 09:19:06 +08:00
keven
218387151f 更新后端和工作器的Dockerfile,升级Go版本至1.24.3,并更新相关依赖项的版本以提高稳定性和安全性 2025-09-23 00:50:25 +08:00
keven
427d958a41 feat(docs): 添加中文README文件,更新英文README中的图片路径,优化项目结构和环境配置说明 2025-09-23 00:28:54 +08:00
keven
8b0d90cdc3 refactor(front): 优化文件上传进度视图,改进文件ID和任务队列的处理逻辑,确保上传任务的有效性 2025-09-23 00:02:11 +08:00
keven1024
0a9d414751 refactor(backend): optimize file upload chunk size calculation and improve MD5 hash verification process 2025-09-22 14:15:10 +08:00
keven1024
f1c2e1a3d7 refactor(front): replace filesize library with custom getFileSize function for consistent file size formatting across components 2025-09-22 14:14:36 +08:00
keven1024
cfe166e8c9 refactor(front): update file handling components to use typed props for better type safety and maintainability 2025-09-22 10:41:55 +08:00
keven
29300a9448 feat(front): 增强文件上传组件,支持上传速度显示和动态进度更新,优化文件分块处理逻辑 2025-09-21 23:45:02 +08:00
keven
2a24f713cb fix(front): 调整 GlobalDrawer 组件的样式,增加内边距以改善布局 2025-09-21 16:56:01 +08:00
keven
427f1f6456 feat(front): 重构文件上传进度视图,支持多文件上传和动态状态更新,优化上传任务管理 2025-09-19 09:18:53 +08:00
keven
c8f36e6f8e feat(front): 添加文件上传进度视图和热图视图组件,支持动态渲染上传状态 2025-09-14 11:48:46 +08:00
keven
03ccd13f8f chore(front): 更新依赖项并添加异步重试和超时功能 2025-09-14 10:38:59 +08:00
keven
b2c0e85844 fix(front): 使用 useDevicePixelRatio 优化 Pixi 组件的分辨率计算 2025-09-14 10:36:43 +08:00
keven1024
c1ec2aee5b chore: update .env.example for Redis configuration and add docker-compose file for app, worker, and Redis services 2025-08-30 18:26:35 +08:00
keven1024
3d173d0321 refactor(front): update FileShareDrawer and FileUploadField components to handle multiple files and improve file type checks 2025-08-14 16:50:43 +08:00
keven1024
4d0a6f0a49 test(backend): add unit tests for HTTP result handlers and password hashing functionality 2025-08-14 14:40:03 +08:00
keven1024
e41d7a6305 fix(front): pass width and height props to slot in Pixi component for better flexibility 2025-08-14 11:53:34 +08:00
keven1024
60af6d2023 chore(front): update logo image in public assets 2025-08-14 11:53:05 +08:00
keven1024
dc16661fff chore: add docker-compose configuration for app, worker, and redis services 2025-08-14 11:52:50 +08:00
keven1024
f36221de05 feat(front): add development page with form components and button interactions 2025-08-09 00:20:48 +08:00
keven1024
e556b0f39d chore(front): update nuxt to 3.18.0 2025-08-08 17:14:56 +08:00
keven1024
13cbf5e5ed fix(front): set backgroundAlpha to 0 in Pixi component for improved rendering 2025-07-28 18:22:36 +08:00
keven1024
8392b26455 feat(front): add Pixi component integration and update dependencies for improved functionality 2025-07-28 18:17:04 +08:00
keven1024
c64c152124 fix(front): enhance error logging in error.vue and improve Tiptap component styling for better readability 2025-07-28 17:07:35 +08:00
keven1024
ecc4aefd33 chore: update dependencies in package.json and pnpm-lock.yaml to latest versions for improved stability and performance 2025-07-20 00:00:26 +08:00
keven1024
590a071dfb chore: update devDependencies in package.json for husky, lint-staged, and prettier to latest versions 2025-07-19 23:59:38 +08:00
keven
cf2d81bf9a refactor(front): 优化状态管理和组件逻辑,简化GlobalDrawer和Tiptap组件的实现 2025-07-19 22:29:48 +08:00
keven
e62f329d53 fix(front): 更新MarkdownRender组件的样式类以增强可读性 2025-07-19 19:19:33 +08:00
keven1024
421955a844 chore: update .env.example to include PASSWORD_SALT for enhanced password security 2025-07-11 10:41:50 +08:00
368 changed files with 22295 additions and 11478 deletions

View File

@@ -0,0 +1,152 @@
---
name: "OPSX: Apply"
description: Implement tasks from an OpenSpec change (Experimental)
category: Workflow
tags: [workflow, artifacts, experimental]
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,157 @@
---
name: "OPSX: Archive"
description: Archive a completed change in the experimental workflow
category: Workflow
tags: [workflow, archive, experimental]
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,173 @@
---
name: "OPSX: Explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
category: Workflow
tags: [workflow, explore, experimental, thinking]
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,106 @@
---
name: "OPSX: Propose"
description: Propose a new change - create it and generate all artifacts in one step
category: Workflow
tags: [workflow, artifacts, experimental]
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -1,16 +0,0 @@
# 你的下载secret每一次下载次数减1的时候都会根据这里的secret生成一个下载jwt token 有效期一小时使用该下载token有效期内可以多线程下载该文件而不会被多次扣除次数
DOWNLOAD_SECRET="your-secret-token"
UPLOAD_PATH="/upload" # 上传路径
REDIS_URL="redis://127.0.0.1:6379/0" # redis 地址
NODE_ENV="production" # 指定系统环境 production 或者 dev
MAX_LOCALSTORAGE_SIZE="100GB" # 指定实例最大上传容量支持填写人类可读的值比如1TB500GB等
# (可选): 系统状态页面显示站长信息的 头像会使用email的gravatar头像点击是触发mailto:your-email不填写不显示站长信息
ADMIN_EMAIL="keven@fudaoyuan.icu"
ADMIN_NAME="keven"
# 下面的env是前端渲染用到的SITE_URL必填对应你的公网域名
SITE_TITLE="015"
SITE_DESC="015 是一个开源的临时内容分享平台项目, 支持文件和文本上传, 下载, 分享"
SITE_URL="http://localhost:5000"

View File

@@ -0,0 +1,31 @@
name: Build
on:
pull_request:
jobs:
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: docker/setup-buildx-action@v3
- name: Set build time
id: build-time
run: echo "time=$(date +%s)" >> $GITHUB_OUTPUT
- name: build-app
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: false
tags: 015-app:test
build-args: |
VERSION=${{ gitea.ref_name || github.ref_name }}
BUILD_TIME=${{ steps.build-time.outputs.time }}
- name: build-worker
uses: docker/build-push-action@v5
with:
context: .
file: ./worker/Dockerfile
push: false
tags: 015-worker:test

View File

@@ -0,0 +1,48 @@
name: Lint
on:
push:
jobs:
lint-front:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: latest
cache: true
- name: Install dependencies
run: |
pnpm install --frozen-lockfile
- name: Run frontend lint
run: pnpm lint:front
lint-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version-file: 'go.work'
- name: Run golangci-lint
uses: golangci/golangci-lint-action@v9
with:
skip-cache: true
working-directory: backend
lint-worker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version-file: 'go.work'
- name: Run golangci-lint
uses: golangci/golangci-lint-action@v9
with:
skip-cache: true
working-directory: worker

View File

@@ -0,0 +1,87 @@
name: Publish
on:
push:
tags:
- '*'
jobs:
build-app:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
username: fudaoyuanicu
password: ${{ secrets.DOCKER_PASSWORD }}
- uses: docker/metadata-action@v5
id: meta
with:
images: fudaoyuanicu/015-app
tags: |
type=semver,pattern={{version}}
type=raw,value=edge,enable=${{ contains(github.ref_name, '-') }}
type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
- name: Set build time
id: build-time
run: |
echo "time=$(date +%s)" >> $GITHUB_OUTPUT
shell: bash
- name: build-app
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ gitea.ref_name || github.ref_name }}
BUILD_TIME=${{ steps.build-time.outputs.time }}
build-worker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
username: fudaoyuanicu
password: ${{ secrets.DOCKER_PASSWORD }}
- uses: docker/metadata-action@v5
id: meta
with:
images: fudaoyuanicu/015-worker
tags: |
type=semver,pattern={{version}}
type=raw,value=edge,enable=${{ contains(github.ref_name, '-') }}
type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
- name: Set build time
id: build-time
run: |
echo "time=$(date +%s)" >> $GITHUB_OUTPUT
shell: bash
- name: build-worker
uses: docker/build-push-action@v5
with:
context: .
file: ./worker/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
deploy:
runs-on: ubuntu-latest
needs: [build-app, build-worker]
if: ${{ !contains(github.ref_name, '-') }}
steps:
- name: Send deployment webhook
run: |
curl -X POST http://192.168.100.5:8364/v1/update \
-H "Content-Type: application/json" \
-H "Authorization: Bearer helloworld"

BIN
.github/image/0.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 804 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
.github/image/3.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

BIN
.github/image/4.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 750 KiB

BIN
.github/image/5.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 807 KiB

BIN
.github/image/6.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

4
.gitignore vendored
View File

@@ -22,6 +22,7 @@ logs
.env .env
.env.* .env.*
!.env.example !.env.example
/config.yaml
# Serwist # Serwist
/front/public/sw* /front/public/sw*
@@ -30,3 +31,6 @@ logs
# backend # backend
**/uploads/** **/uploads/**
**/tmp/** **/tmp/**
# worker
pkg/mail/out/

16
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,16 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Backend",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/backend",
"cwd": "${workspaceFolder}"
}
]
}

5
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"i18n-ally.localesPaths": ["front/i18n/locales"],
"i18n-ally.enabledFrameworks": ["vue"],
"i18n-ally.keystyle": "nested"
}

View File

@@ -1,34 +1,32 @@
FROM node:22-alpine AS front-base FROM node:22-alpine AS front-base
WORKDIR /app
# Install dependencies only when needed # Install dependencies only when needed
FROM front-base AS front-deps
RUN apk add --no-cache gcompat
WORKDIR /app
COPY . .
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front deploy dist
FROM front-base AS front-builder FROM front-base AS front-builder
WORKDIR /app RUN apk add --no-cache gcompat
COPY --from=front-deps /app/dist/ . ENV CI=true
RUN corepack enable pnpm && pnpm build ENV NODE_OPTIONS="--max-old-space-size=4096"
COPY . .
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front build && pnpm --dir pkg/mail export
FROM golang:1.23.1 AS backend-builder FROM golang:1.26.3 AS backend-builder
WORKDIR /app WORKDIR /app
# Download Go modules # Workspace and module manifests for cache
COPY backend/go.mod backend/go.sum ./ COPY go.work go.work.sum ./
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && go mod download COPY backend/ ./backend/
# Copy the source code. Note the slash at the end, as explained in COPY worker/ ./worker/
# https://docs.docker.com/engine/reference/builder/#copy COPY pkg/ ./pkg/
COPY backend/ . # Inject built email templates so Go can embed them
# Build COPY --from=front-builder /app/pkg/mail/out/ ./pkg/mail/out/
RUN CGO_ENABLED=0 GOOS=linux go build -o backend RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && \
go mod download
# Build from workspace root so pkg/utils, pkg/models, pkg/services resolve
RUN CGO_ENABLED=0 GOOS=linux go build -o backend-bin ./backend
FROM front-base AS runner FROM front-base AS runner
ARG VERSION ARG VERSION
ARG BUILD_TIME ARG BUILD_TIME
WORKDIR /app
RUN apk add --no-cache curl openssl RUN apk add --no-cache curl openssl
ENV NODE_ENV production ENV NODE_ENV production
@@ -36,14 +34,12 @@ RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nuxtjs RUN adduser --system --uid 1001 nuxtjs
# Only `.output` folder is needed from the build stage # Only `.output` folder is needed from the build stage
COPY --from=front-builder --chown=nuxtjs:nodejs /app/.output/ ./ COPY --from=front-builder --chown=nuxtjs:nodejs /app/front/.output/ ./
COPY --from=backend-builder /app/backend /bin/backend COPY --from=backend-builder /app/backend-bin /bin/backend
COPY 015.sh /app/015.sh COPY 015.sh /app/015.sh
# Change the port and host # Change the port and host
ENV PORT=80 HOST=0.0.0.0 ENV PORT=80 HOST=0.0.0.0
ENV SITE_URL="http://localhost"
ENV UPLOAD_PATH="/uploads"
ENV VERSION=${VERSION} ENV VERSION=${VERSION}
ENV BUILD_TIME=${BUILD_TIME} ENV BUILD_TIME=${BUILD_TIME}

235
LICENSE Normal file
View File

@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
interview
Copyright (C) 2025 keven
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

View File

@@ -1,10 +1,16 @@
<div align="center"><a name="readme-top"></a>
# 015 # 015
015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") 是一个支持selfhosted的临时文件分享平台。专注于提供一次性临时的文件和文本上传处理分享服务。项目名称来源于DARLING in the FRANXX的 [](https://darling-in-the-franxx.fandom.com/wiki/Ichigo) 015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") 是一个支持selfhosted的临时文件分享平台。专注于提供一次性临时的文件和文本上传处理分享服务。项目名称来源于DARLING in the FRANXX的 [](https://darling-in-the-franxx.fandom.com/wiki/Ichigo)
一个基于 Vue 3 + Nuxt 3 + Go 构建的现代文件分享网站,支持文件上传、文本分享、图片压缩、并发处理、秒传功能等,具备完整的分享管理和访问控制体系。 一个基于 Vue 3 + Nuxt 3 + Go 构建的现代文件分享网站,支持文件上传、文本分享、图片压缩、并发处理、秒传功能等,具备完整的分享管理和访问控制体系。
![015 Platform Overview](./image/0.png) ![015 Platform Overview](/.github/image/0.png)
[English](README.md) | 中文
</div>
## 🌟 功能特性 ## 🌟 功能特性
@@ -33,101 +39,74 @@
📷 **图片处理** - 图片压缩、格式转换等处理功能 📷 **图片处理** - 图片压缩、格式转换等处理功能
🏷️ **下载控制** - 基于 JWT 的下载令牌管理系统 🏷️ **下载控制** - 基于 JWT 的下载令牌管理系统
## 截图 ## 📸 截图预览
![](./image/1.webp) | 选择文件上传页面 | 输入文本上传页面 |
| ------------------------- | ------------------------- |
| ![](/.github/image/1.png) | ![](/.github/image/2.png) |
![](./image/2.webp) | 多选文件上传 | 文件上传进度热力图 |
| ------------------------- | ------------------------- |
| ![](/.github/image/3.png) | ![](/.github/image/4.png) |
![](./image/3.png) | 文件上传进度条 | 文件上传成功页面 |
| ------------------------- | ------------------------- |
| ![](/.github/image/5.png) | ![](/.github/image/6.png) |
![](./image/4.png) ## 🚀 快速开始
### Docker
1. 下载文件
- config.example.yaml
- docker-compose.yml
2. 把 config.example.yaml 配置完成后改为 config.yaml
3. 启动
```bash
docker compose up -d
```
4. 访问 `http://localhost:8080`
## 🏗️ 技术架构 ## 🏗️ 技术架构
### 前端技术栈 ### 前端技术栈
- **Vue 3** - 渐进式 JavaScript 框架 - **Vue 3** - 渐进式 JavaScript 框架
- **Nuxt 3** - Vue.js 全栈框架 - **Nuxt 3** - Vue.js 全栈框架
- **TypeScript** - 完整的类型安全 - **TypeScript** - 完整的类型安全
- **Tailwind CSS** - 原子化 CSS 框架 - **Tailwind CSS** - 原子化 CSS 框架
- **Reka UI** - 现代化组件库 - **Reka UI** - 现代化组件库
- **Pinia** - 状态管理 - **Pinia** - 状态管理
- **TanStack Query** - 数据获取和缓存 - **TanStack Query** - 数据获取和缓存
- **Vue Router** - 路由管理 - **Vue Router** - 路由管理
- **i18next** - 国际化支持 - **i18next** - 国际化支持
### 后端技术栈 ### 后端技术栈
- **Go 1.23** - 高性能服务器端语言 - **Go 1.23** - 高性能服务器端语言
- **Echo** - 高性能 HTTP 框架 - **Echo** - 高性能 HTTP 框架
- **Redis** - 缓存和会话存储 - **Redis** - 缓存和会话存储
- **Asynq** - 异步任务队列 - **Asynq** - 异步任务队列
- **JWT** - 身份验证 - **JWT** - 身份验证
- **Zap** - 结构化日志 - **Zap** - 结构化日志
### 构建系统 ### 构建系统
- **Node.js** - 服务器端运行时 - **Node.js** - 服务器端运行时
- **pnpm** - 快速包管理器 - **pnpm** - 快速包管理器
- **Husky** - Git hooks 管理 - **Husky** - Git hooks 管理
- **Prettier** - 代码格式化 - **Prettier** - 代码格式化
- **Lint-staged** - 暂存文件检查 - **Lint-staged** - 暂存文件检查
### 存储架构 ### 存储架构
- **文件存储** - 本地文件系统存储 - **文件存储** - 本地文件系统存储
- **Redis 缓存** - 分享信息、文件元数据缓存 - **Redis 缓存** - 分享信息、文件元数据缓存
- **队列系统** - 异步任务处理队列 - **队列系统** - 异步任务处理队列
## 🚀 快速开始
### 环境要求
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
### 安装依赖
```bash
# 安装根目录依赖
pnpm install
# 安装前端依赖
cd front && pnpm install
# 安装后端依赖
cd backend && go mod download
# 安装 Worker 依赖
cd worker && go mod download
```
### 环境配置
```bash
# 复制环境变量文件
cp .env.example .env
# 配置必要的环境变量
REDIS_URL=redis://localhost:6379
UPLOAD_PATH=./uploads
download_secret=your_download_secret
```
### 启动服务
```bash
# 开发模式启动所有服务
pnpm run dev
# 或分别启动
pnpm run dev:front # 前端服务 (端口 5000)
pnpm run dev:backend # 后端服务 (端口 1323)
pnpm run dev:worker # Worker 服务
```
## 📁 项目结构 ## 📁 项目结构
@@ -135,15 +114,15 @@ pnpm run dev:worker # Worker 服务
015/ 015/
├── front/ # 前端应用 (Vue 3 + Nuxt 3) ├── front/ # 前端应用 (Vue 3 + Nuxt 3)
│ ├── components/ # Vue 组件 │ ├── components/ # Vue 组件
│ ├── pages/ # 页面路由 │ ├── pages/ # 页面路由
│ ├── composables/ # 组合式函数 │ ├── composables/ # 组合式函数
│ ├── i18n/ # 国际化文件 │ ├── i18n/ # 国际化文件
│ └── assets/ # 静态资源 ── assets/ # 静态资源
── middleware/ # 中间 ── plugins/ # Nuxt 插
│ └── server/ # 服务端路由
├── backend/ # 后端服务 (Go + Echo) ├── backend/ # 后端服务 (Go + Echo)
│ ├── internal/ # 内部包 │ ├── internal/ # 内部包
│ │ ├── controllers/ # 控制器 │ │ ├── controllers/ # 控制器
│ │ ├── models/ # 数据模型
│ │ ├── services/ # 业务逻辑 │ │ ├── services/ # 业务逻辑
│ │ └── utils/ # 工具函数 │ │ └── utils/ # 工具函数
│ └── middleware/ # 中间件 │ └── middleware/ # 中间件
@@ -152,16 +131,16 @@ pnpm run dev:worker # Worker 服务
│ │ ├── tasks/ # 任务处理器 │ │ ├── tasks/ # 任务处理器
│ │ └── utils/ # 工具函数 │ │ └── utils/ # 工具函数
│ └── middleware/ # 中间件 │ └── middleware/ # 中间件
└── tmp/ # 临时文件 └── pkg/ # 公共包
``` ```
## 🔧 开发指南 ## 🔧 开发指南
### 代码规范 ### 代码规范
- 使用 Prettier 进行代码格式化 - 使用 Prettier 进行代码格式化
- 使用 Husky + lint-staged 进行提交前检查 - 使用 Husky + lint-staged 进行提交前检查
- 遵循 TypeScript 类型安全规范 - 遵循 TypeScript 类型安全规范
### 提交规范 ### 提交规范
@@ -188,22 +167,22 @@ cd worker && go build -o worker .
### 已完成功能 ✅ ### 已完成功能 ✅
- 前端计算哈希和秒传 - 前端计算哈希和秒传
- 并发切片上传 (使用 Web Worker) - 并发切片上传 (使用 Web Worker)
- 文件上传/文本上传和分享 - 文件上传/文本上传和分享
- 上传统计页面 - 支持多文件上传
- 多语言支持 - 上传统计页面
- 最大上传限制 - 多语言支持
- 后端队列系统和 Worker 处理文件 - 最大上传限制
- 后端队列系统和 Worker 处理文件
- 断点续传 (后端计算已上传部分并返回)
- 图片格式转换和压缩
### 计划功能 🚧 ### 计划功能 🚧
- 断点续传 (后端计算已上传部分并返回) - 图片 OCR 复制
- 图片格式转换和压缩 - 文档转 Markdown
- 图片 OCR 复制 - 文本翻译/总结
- 文档转 Markdown
- 文本翻译/总结
- 支持上传多文件
## 🤝 贡献指南 ## 🤝 贡献指南
@@ -215,7 +194,7 @@ cd worker && go build -o worker .
## 🔗 相关链接 ## 🔗 相关链接
- [Vue 3 文档](https://vuejs.org/) - [Vue 3 文档](https://vuejs.org/)
- [Nuxt 3 文档](https://nuxt.com/) - [Nuxt 3 文档](https://nuxt.com/)
- [Echo 框架文档](https://echo.labstack.com/) - [Echo 框架文档](https://echo.labstack.com/)
- [Asynq 文档](https://github.com/hibiken/asynq) - [Asynq 文档](https://github.com/hibiken/asynq)

207
README.md
View File

@@ -1,10 +1,16 @@
<div align="center"><a name="readme-top"></a>
# 015 # 015
015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") is a self-hosted temporary file sharing platform. Focused on providing one-time, temporary file and text upload, processing, and sharing services. The project name originates from [Ichigo](https://darling-in-the-franxx.fandom.com/wiki/Ichigo) from DARLING in the FRANXX. 015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") is a self-hosted temporary file sharing platform. Focused on providing one-time, temporary file and text upload, processing, and sharing services. The project name originates from [Ichigo](https://darling-in-the-franxx.fandom.com/wiki/Ichigo) from DARLING in the FRANXX.
A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file upload, text sharing, image compression, concurrent processing, instant transfer functionality, and more, featuring a complete sharing management and access control system. A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file upload, text sharing, image compression, concurrent processing, instant transfer functionality, and more, featuring a complete sharing management and access control system.
![015 Platform Overview](/docs/image/0.png) ![015 Platform Overview](/.github/image/0.png)
English | [中文](README-zh.md)
</div>
## 🌟 Features ## 🌟 Features
@@ -35,99 +41,71 @@ A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file up
## 📸 Screenshots ## 📸 Screenshots
![](/docs/image/1.webp) | File Selection Upload Page | Text Input Upload Page |
| -------------------------- | ------------------------- |
| ![](/.github/image/1.png) | ![](/.github/image/2.png) |
![](/docs/image/2.webp) | Multiple File Upload | Upload Progress Heatmap |
| -------------------------- | ------------------------- |
| ![](/.github/image/3.png) | ![](/.github/image/4.png) |
![](/docs/image/3.png) | Upload Progress Bar | Upload Success Page |
| -------------------------- | ------------------------- |
| ![](/.github/image/5.png) | ![](/.github/image/6.png) |
![](/docs/image/4.png) ## 🚀 Quick Start
### Docker
1. Download files
- config.example.yaml
- docker-compose.yml
2. Rename config.example.yaml to config.yaml after configuration
3. Start
```bash
docker compose up -d
```
4. Visit `http://localhost:8080`
## 🏗️ Technical Architecture ## 🏗️ Technical Architecture
### Frontend Tech Stack ### Frontend Tech Stack
- **Vue 3** - Progressive JavaScript framework - **Vue 3** - Progressive JavaScript framework
- **Nuxt 3** - Vue.js full-stack framework - **Nuxt 3** - Vue.js full-stack framework
- **TypeScript** - Complete type safety - **TypeScript** - Complete type safety
- **Tailwind CSS** - Atomic CSS framework - **Tailwind CSS** - Atomic CSS framework
- **Reka UI** - Modern component library - **Reka UI** - Modern component library
- **Pinia** - State management - **Pinia** - State management
- **TanStack Query** - Data fetching and caching - **TanStack Query** - Data fetching and caching
- **Vue Router** - Routing management - **Vue Router** - Routing management
- **i18next** - Internationalization support - **i18next** - Internationalization support
### Backend Tech Stack ### Backend Tech Stack
- **Go 1.23** - High-performance server-side language - **Go 1.23** - High-performance server-side language
- **Echo** - High-performance HTTP framework - **Echo** - High-performance HTTP framework
- **Redis** - Caching and session storage - **Redis** - Caching and session storage
- **Asynq** - Asynchronous task queue - **Asynq** - Asynchronous task queue
- **JWT** - Authentication - **JWT** - Authentication
- **Zap** - Structured logging - **Zap** - Structured logging
### Build System ### Build System
- **Node.js** - Server-side runtime - **Node.js** - Server-side runtime
- **pnpm** - Fast package manager - **pnpm** - Fast package manager
- **Husky** - Git hooks management - **Husky** - Git hooks management
- **Prettier** - Code formatting - **Prettier** - Code formatting
- **Lint-staged** - Staged file checking - **Lint-staged** - Staged file checking
### Storage Architecture ### Storage Architecture
- **File Storage** - Local file system storage - **File Storage** - Local file system storage
- **Redis Cache** - Share information and file metadata caching - **Redis Cache** - Share information and file metadata caching
- **Queue System** - Asynchronous task processing queue - **Queue System** - Asynchronous task processing queue
## 🚀 Quick Start
### Requirements
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
### Install Dependencies
```bash
# Install root dependencies
pnpm install
# Install frontend dependencies
cd front && pnpm install
# Install backend dependencies
cd backend && go mod download
# Install Worker dependencies
cd worker && go mod download
```
### Environment Configuration
```bash
# Copy environment variables file
cp .env.example .env
# Configure necessary environment variables
REDIS_URL=redis://localhost:6379
UPLOAD_PATH=./uploads
download_secret=your_download_secret
```
### Start Services
```bash
# Start all services in development mode
pnpm run dev
# Or start separately
pnpm run dev:front # Frontend service (port 5000)
pnpm run dev:backend # Backend service (port 1323)
pnpm run dev:worker # Worker service
```
## 📁 Project Structure ## 📁 Project Structure
@@ -135,32 +113,33 @@ pnpm run dev:worker # Worker service
015/ 015/
├── front/ # Frontend application (Vue 3 + Nuxt 3) ├── front/ # Frontend application (Vue 3 + Nuxt 3)
│ ├── components/ # Vue components │ ├── components/ # Vue components
│ ├── pages/ # Page routes │ ├── pages/ # Page routes
│ ├── composables/ # Composable functions │ ├── composables/ # Composable functions
│ ├── i18n/ # Internationalization files │ ├── i18n/ # Internationalization files
│ └── assets/ # Static assets ── assets/ # Static assets
│ ├── backend/ # Backend service (Go + Echo) │ ├── plugins/ # Nuxt plugins
│ ├── internal/ # Internal packages └── server/ # Server-side routes
├── controllers/ # Controllers ├── backend/ # Backend service (Go + Echo)
│ │ ├── models/ # Data models ├── internal/ # Internal packages
│ │ │ ├── services/ # Business logic │ │ ├── controllers/ # Controllers
│ │ │ └── utils/ # Utility functions │ │ ├── services/ # Business logic
│ │ └── middleware/ # Middleware │ │ └── utils/ # Utility functions
── worker/ # Asynchronous task processing (Go + Asynq) ── middleware/ # Middleware
│ │ ├── internal/ # Internal packages ├── worker/ # Asynchronous task processing (Go + Asynq)
│ │ ├── tasks/ # Task processors ├── internal/ # Internal packages
│ │ │ └── utils/ # Utility functions │ │ ├── tasks/ # Task processors
│ │ └── middleware/ # Middleware │ │ └── utils/ # Utility functions
│ └── tmp/ # Temporary files │ └── middleware/ # Middleware
└── pkg/ # Shared packages
``` ```
## 🔧 Development Guide ## 🔧 Development Guide
### Code Standards ### Code Standards
- Use Prettier for code formatting - Use Prettier for code formatting
- Use Husky + lint-staged for pre-commit checking - Use Husky + lint-staged for pre-commit checking
- Follow TypeScript type safety standards - Follow TypeScript type safety standards
### Commit Standards ### Commit Standards
@@ -187,22 +166,22 @@ cd worker && go build -o worker .
### Completed Features ✅ ### Completed Features ✅
- Frontend hash calculation and instant transfer - Frontend hash calculation and instant transfer
- Concurrent chunked upload (using Web Worker) - Concurrent chunked upload (using Web Worker)
- File upload/text upload and sharing - File upload/text upload and sharing
- Upload statistics page - Multiple file upload support
- Multi-language support - Upload statistics page
- Maximum upload limits - Multi-language support
- Backend queue system and Worker file processing - Maximum upload limits
- Backend queue system and Worker file processing
- Resume upload (backend calculates uploaded parts and returns)
- Image format conversion and compression
### Planned Features 🚧 ### Planned Features 🚧
- Resume upload (backend calculates uploaded parts and returns) - Image OCR copy
- Image format conversion and compression - Document to Markdown conversion
- Image OCR copy - Text translation/summarization
- Document to Markdown conversion
- Text translation/summarization
- Support for multiple file uploads
## 🤝 Contributing ## 🤝 Contributing
@@ -214,7 +193,7 @@ This project is licensed under AGPLV3.
## 🔗 Related Links ## 🔗 Related Links
- [Vue 3 Documentation](https://vuejs.org/) - [Vue 3 Documentation](https://vuejs.org/)
- [Nuxt 3 Documentation](https://nuxt.com/) - [Nuxt 3 Documentation](https://nuxt.com/)
- [Echo Framework Documentation](https://echo.labstack.com/) - [Echo Framework Documentation](https://echo.labstack.com/)
- [Asynq Documentation](https://github.com/hibiken/asynq) - [Asynq Documentation](https://github.com/hibiken/asynq)

55
backend/.air.toml Normal file
View File

@@ -0,0 +1,55 @@
#:schema https://json.schemastore.org/any.json
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"
[build]
args_bin = []
bin = "./tmp/main"
cmd = "go build -o ./tmp/main ."
delay = 1000
entrypoint = ["./tmp/main"]
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = ["../pkg"]
include_ext = ["go", "tpl", "tmpl", "html"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
main_only = false
silent = false
time = false
[misc]
clean_on_exit = false
[proxy]
app_port = 0
enabled = false
proxy_port = 0
[screen]
clear_on_rebuild = false
keep_scroll = true

View File

@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1
FROM golang:1.23.1 AS builder FROM golang:1.25.5 AS builder
# Set destination for COPY # Set destination for COPY
WORKDIR /app WORKDIR /app

View File

@@ -1,50 +1,36 @@
module backend module backend
go 1.23.1 go 1.25.5
require ( require (
dario.cat/mergo v1.0.1 github.com/golang-jwt/jwt/v5 v5.3.1
github.com/dustin/go-humanize v1.0.1
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/gorilla/sessions v1.4.0 github.com/gorilla/sessions v1.4.0
github.com/hibiken/asynq v0.25.1 github.com/hibiken/asynq v0.26.0
github.com/labstack/echo-contrib v0.17.3 github.com/labstack/echo/v5 v5.0.1
github.com/labstack/echo/v4 v4.13.3
github.com/matoous/go-nanoid/v2 v2.1.0 github.com/matoous/go-nanoid/v2 v2.1.0
github.com/redis/go-redis/v9 v9.7.3 github.com/samber/lo v1.53.0
github.com/samber/lo v1.50.0 github.com/spf13/cast v1.10.0
github.com/spf13/cast v1.7.1 github.com/stretchr/testify v1.11.1
github.com/spf13/viper v1.20.1 go.uber.org/zap v1.27.1
go.uber.org/zap v1.27.0 golang.org/x/crypto v0.49.0
golang.org/x/crypto v0.39.0
golang.org/x/time v0.11.0
) )
require ( require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect github.com/gorilla/securecookie v1.1.2 // indirect
github.com/labstack/gommon v0.4.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/redis/go-redis/v9 v9.18.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect go.uber.org/atomic v1.11.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.12.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect
golang.org/x/net v0.37.0 // indirect golang.org/x/net v0.52.0 // indirect
golang.org/x/sys v0.33.0 // indirect golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.26.0 // indirect golang.org/x/text v0.35.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect golang.org/x/time v0.15.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

View File

@@ -1,5 +1,3 @@
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
@@ -10,101 +8,70 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ= github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik= github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw= github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw=
github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg= github.com/hibiken/asynq v0.26.0/go.mod h1:Qk4e57bTnWDoyJ67VkchuV6VzSM9IQW2nPvAGuDyw58=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo-contrib v0.17.3 h1:hj+qXksKZG1scSe9ksUXMtv7fZYN+PtQT+bPcYA3/TY= github.com/labstack/echo/v5 v5.0.1 h1:60L7x1KMWRIJuaFqvnEHH322g+YnsMWq5Rzaeo6lcP4=
github.com/labstack/echo-contrib v0.17.3/go.mod h1:TcRBrzW8jcC4JD+5Dc/pvOyAps0rtgzj7oBqoR3nYsc= github.com/labstack/echo/v5 v5.0.1/go.mod h1:SyvlSdObGjRXeQfCCXW/sybkZdOOQZBmpKF0bvALaeo=
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE= github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM= github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k= github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/samber/lo v1.50.0 h1:XrG0xOeHs+4FQ8gJR97zDz5uOFMW7OwFWiFVzqopKgY= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/samber/lo v1.50.0/go.mod h1:RjZyNk6WSnUFRKK6EyOhsRJMqft3G+pg7dCWHQCWvsc= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs= github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,45 @@
package controllers
import (
"backend/internal/utils"
"encoding/json"
"pkg/models"
u "pkg/utils"
"github.com/labstack/echo/v5"
"github.com/samber/lo"
)
func GetAbout(c *echo.Context) error {
maxStorageSize, err := u.GetFileSize(u.GetEnv("upload.maximum"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
fileInfoMap, err := models.GetRedisFileInfoAll()
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
currentFileSize := lo.Reduce(lo.Values(fileInfoMap), func(agg int64, item string, _ int) int64 {
var fileInfo models.RedisFileInfo
err := json.Unmarshal([]byte(item), &fileInfo)
if err != nil {
return agg
}
return agg + fileInfo.FileSize
}, 0)
return utils.HTTPSuccessHandler(c, map[string]any{
"bg_url": u.GetEnv("about.bg_url"),
"content": u.GetEnvMap("about.content"),
"email": u.GetEnv("about.email"),
"name": u.GetEnv("about.name"),
"url": u.GetEnv("about.url"),
"avatar": u.GetEnv("about.avatar"),
"file": map[string]any{
"maximun": maxStorageSize,
"current": currentFileSize,
},
})
}

View File

@@ -0,0 +1,54 @@
package controllers
import (
"backend/internal/utils"
u "pkg/utils"
"time"
"github.com/labstack/echo/v5"
"github.com/samber/lo"
"github.com/spf13/cast"
)
var defaultEnabledFeatures = []string{
"file-share",
"text-share",
}
func getEnabledKeys(config map[string]any) []string {
return lo.FilterMap(lo.Entries(config), func(e lo.Entry[string, any], _ int) (string, bool) {
node, ok := e.Value.(map[string]any)
return e.Key, ok && cast.ToBool(node["enabled"])
})
}
func GetConfig(c *echo.Context) error {
featureConfig := u.GetEnvMap("features")
defaultFeatureConfig := lo.SliceToMap(defaultEnabledFeatures, func(item string) (string, any) {
return item, map[string]any{
"enabled": true,
}
})
featureConfig = lo.Assign(defaultFeatureConfig, featureConfig)
features := getEnabledKeys(featureConfig)
// textTranslateProviderConfig := u.GetEnvMap("features.text-translate.provider")
// textTranslateProviders := getEnabledKeys(textTranslateProviderConfig)
return utils.HTTPSuccessHandler(c, map[string]any{
"site_title": u.GetEnvMap("site.title"),
"site_desc": u.GetEnvMap("site.desc"),
"site_url": u.GetEnv("site.url"),
"site_icon": u.GetEnvWithDefault("site.icon", "/logo.png"),
"site_bg_url": u.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
"site_enable_bg": cast.ToBool(u.GetEnvWithDefault("site.enable_bg", "true")),
"version": u.GetEnvWithDefault("VERSION", "dev"),
"build_time": cast.ToInt(u.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
"features": features,
"config": map[string]any{
// "text-translate": map[string]any{
// "provider": textTranslateProviders,
// },
},
})
}

View File

@@ -1,15 +1,19 @@
package controllers package controllers
import ( import (
"backend/internal/models"
"backend/internal/utils" "backend/internal/utils"
"backend/middleware" "context"
"errors" "encoding/json"
"fmt" "fmt"
"pkg/models"
u "pkg/utils"
"time" "time"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4" "github.com/hibiken/asynq"
"github.com/labstack/echo/v5"
"github.com/samber/lo"
"github.com/spf13/cast"
) )
type DownloadShareClaims struct { type DownloadShareClaims struct {
@@ -17,31 +21,29 @@ type DownloadShareClaims struct {
jwt.RegisteredClaims jwt.RegisteredClaims
} }
func DownloadShare(c echo.Context) error { func DownloadShare(c *echo.Context) error {
cc := c.(*middleware.CustomContext) token := c.FormValue("token")
token := cc.FormValue("token")
if token == "" { if token == "" {
return utils.HTTPErrorHandler(c, errors.New("缺少token")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
claims := DownloadShareClaims{} claims := DownloadShareClaims{}
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) { t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(utils.GetEnv("download_secret")), nil return []byte(u.GetEnv("share.download_secret")), nil
}) })
if err != nil { if err != nil || !t.Valid {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrInvalidRequest))
} }
if !t.Valid { shareInfo, err := models.GetRedisShareInfo(claims.ShareId)
return utils.HTTPErrorHandler(c, errors.New("token格式错误")) if err != nil || shareInfo == nil {
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrShareNotFound))
} }
shareInfo, _ := models.GetRedisShareInfo(claims.ShareId)
if shareInfo.Type == models.ShareTypeFile { if shareInfo.Type == models.ShareTypeFile {
fileInfo, _ := models.GetRedisFileInfo(shareInfo.Data) fileInfo, _ := models.GetRedisFileInfo(shareInfo.Data)
uploadPath, err := utils.GetUploadDirPath() uploadPath, err := u.GetUploadDirPath()
if err != nil { if err != nil {
return err return err
} }
return cc.Attachment(fmt.Sprintf("%s/%s", uploadPath, utils.GetFileId(fileInfo.FileHash, fileInfo.FileSize)), shareInfo.FileName) return c.Attachment(fmt.Sprintf("%s/%s", uploadPath, u.GetFileId(fileInfo.FileHash, fileInfo.FileSize)), shareInfo.FileName)
} }
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"data": shareInfo.Data, "data": shareInfo.Data,
@@ -53,16 +55,14 @@ type VaildateShareProps struct {
Password string `json:"password"` Password string `json:"password"`
} }
func VaildateShare(c echo.Context) error { func VaildateShare(c *echo.Context) error {
cc := c.(*middleware.CustomContext)
r := new(VaildateShareProps) r := new(VaildateShareProps)
if err := cc.Bind(r); err != nil { if err := c.Bind(r); err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if r.ShareId == "" { if r.ShareId == "" {
return utils.HTTPErrorHandler(c, errors.New("缺少分享ID")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
shareInfo, err := models.GetRedisShareInfo(r.ShareId) shareInfo, err := models.GetRedisShareInfo(r.ShareId)
@@ -70,63 +70,89 @@ func VaildateShare(c echo.Context) error {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if shareInfo == nil { if shareInfo == nil {
return utils.HTTPErrorHandler(c, errors.New("分享不存在")) return utils.HTTPErrorHandler(c, ErrShareNotFound)
} }
if shareInfo.Password != "" { if shareInfo.Password != "" {
if r.Password == "" { if r.Password == "" {
return utils.HTTPErrorHandler(c, errors.New("缺少分享密码")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
hash, err := utils.GeneratePasswordHash(r.Password) hash, err := utils.GeneratePasswordHash(r.Password)
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if hash != shareInfo.Password { if hash != shareInfo.Password {
return utils.HTTPErrorHandler(c, errors.New("分享密码错误")) return utils.HTTPErrorHandler(c, ErrInvalidSharePassword)
} }
} }
// 如果下载次数为0则设置为-1 防止空值问题 return u.WithLocker(context.Background(), "015:shareInfoMap:"+r.ShareId, 0, func(ctx context.Context) error {
if shareInfo.ViewNum < 1 { shareInfo, err := models.GetRedisShareInfo(r.ShareId)
return utils.HTTPErrorHandler(c, errors.New("下载次数不足")) if err != nil || shareInfo == nil {
} return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrShareNotFound))
token := jwt.NewWithClaims(jwt.SigningMethodHS256, DownloadShareClaims{ }
ShareId: r.ShareId, if shareInfo.ViewNum < 1 {
RegisteredClaims: jwt.RegisteredClaims{ return utils.HTTPErrorHandler(c, ErrInsufficientDownloadQuota)
ExpiresAt: jwt.NewNumericDate(time.Now().Add(60 * time.Minute)), }
}, downloadWindow := u.GetEnvWithDefault("share.download_window", "12")
}) token := jwt.NewWithClaims(jwt.SigningMethodHS256, DownloadShareClaims{
ShareId: r.ShareId,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(cast.ToDuration(downloadWindow + "h"))),
},
})
// Sign and get the complete encoded token as a string using the secret // Sign and get the complete encoded token as a string using the secret
downloadToken, err := token.SignedString([]byte(utils.GetEnv("download_secret"))) downloadToken, err := token.SignedString([]byte(u.GetEnv("share.download_secret")))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
if shareInfo.Type == models.ShareTypeFile {
fileInfo, err := models.GetRedisFileInfo(shareInfo.Data)
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if fileInfo == nil { if shareInfo.Type == models.ShareTypeFile {
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在")) fileInfo, err := models.GetRedisFileInfo(shareInfo.Data)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
if fileInfo == nil {
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
}
if fileInfo.FileType != models.FileTypeUpload {
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
}
} }
if fileInfo.FileType != models.FileTypeUpload { // download_nums 必须放在创建token的时候减掉不然多线程下载会导致多次减掉
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误")) _, err = models.SetRedisShareInfo(r.ShareId, func(shareInfo *models.RedisShareInfo) *models.RedisShareInfo {
shareInfo.ViewNum -= 1
return shareInfo
})
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
// 统计分享数
currentDate := time.Now().Format("2006-01-02")
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
stat.DownloadNum += 1
return stat
})
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
if len(shareInfo.NotifyEmails) > 0 || len(shareInfo.NotifyWebhooks) > 0 {
payload, err := json.Marshal(map[string]string{
"share_id": r.ShareId,
"ip": c.RealIP(),
})
if err == nil {
_, _ = u.GetQueueClient().Enqueue(asynq.NewTask("share:notify", payload))
}
}
if shareInfo.Type == models.ShareTypeFile {
return utils.HTTPSuccessHandler(c, map[string]any{
"token": downloadToken,
})
} }
}
// download_nums 必须放在创建token的时候减掉不然多线程下载会导致多次减掉
latestViewNum := shareInfo.ViewNum - 1
// 如果下载次数为0则设置为-1 防止空值问题
if latestViewNum < 1 {
latestViewNum = -1
}
models.SetRedisShareInfo(r.ShareId, models.RedisShareInfo{
ViewNum: latestViewNum,
})
if shareInfo.Type == models.ShareTypeFile {
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"token": downloadToken, "token": downloadToken,
}) })
}
return utils.HTTPSuccessHandler(c, map[string]any{
"token": downloadToken,
}) })
} }

View File

@@ -0,0 +1,30 @@
package controllers
import "errors"
var (
// 通用错误(参数校验失败)
ErrInvalidRequest = errors.New("InvalidRequest") // 调用接口参数错误
// 任务相关
ErrTaskNotFound = errors.New("TaskNotFound") // 任务不存在
ErrTaskExpired = errors.New("TaskExpired") // 任务已过期
// 文件上传相关
ErrInsufficientStorage = errors.New("InsufficientStorage") // 存储空间不足
ErrUploadTaskExpired = errors.New("UploadTaskExpired") // 上传任务已过期
ErrInvalidUploadTaskState = errors.New("InvalidUploadTaskState") // 上传任务状态错误
ErrInvalidFileSliceIndex = errors.New("InvalidFileSliceIndex") // 文件切片索引错误
ErrInvalidFileSliceSize = errors.New("InvalidFileSliceSize") // 文件切片大小错误
ErrIncompleteFileSlices = errors.New("IncompleteFileSlices") // 文件切片不完整
ErrFileHashMismatch = errors.New("FileHashMismatch") // 文件Hash不一致
// 分享相关
ErrShareFileNotFound = errors.New("ShareFileNotFound") // 分享文件不存在
ErrInvalidShareFileState = errors.New("InvalidShareFileState") // 分享文件状态错误
ErrShareNotFound = errors.New("ShareNotFound") // 分享不存在
// 下载相关
ErrInvalidSharePassword = errors.New("InvalidSharePassword") // 分享密码错误
ErrInsufficientDownloadQuota = errors.New("InsufficientDownloadQuota") // 下载次数不足
)

View File

@@ -1,22 +1,21 @@
package controllers package controllers
import ( import (
"backend/internal/models"
"backend/internal/services" "backend/internal/services"
"backend/internal/utils" "backend/internal/utils"
"encoding/json" "encoding/json"
"errors" "math"
"fmt"
"mime/multipart" "mime/multipart"
"os" "os"
"path/filepath" "pkg/models"
s "pkg/services"
u "pkg/utils"
"time" "time"
"github.com/hibiken/asynq" "github.com/labstack/echo/v5"
"github.com/labstack/echo/v4"
) )
func CreateUploadTask(c echo.Context) error { func CreateUploadTask(c *echo.Context) error {
// cc := c.(*middleware.CustomContext) // cc := c.(*middleware.CustomContext)
r := new(models.FileInfo) r := new(models.FileInfo)
if err := c.Bind(r); err != nil { if err := c.Bind(r); err != nil {
@@ -24,12 +23,23 @@ func CreateUploadTask(c echo.Context) error {
} }
if r.FileSize == 0 || r.MimeType == "" || r.FileHash == "" { if r.FileSize == 0 || r.MimeType == "" || r.FileHash == "" {
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
}
fileId := u.GetFileId(r.FileHash, r.FileSize)
fileInfo, err := models.GetRedisFileInfo(fileId)
if err != nil {
return utils.HTTPErrorHandler(c, err)
} }
fileId := utils.GetFileId(r.FileHash, r.FileSize)
fileInfo, _ := models.GetRedisFileInfo(fileId)
if fileInfo != nil { if fileInfo != nil {
uploadPath, err := u.GetUploadDirPath()
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
sliceList, err := services.GetFileSliceList(fileId, uploadPath)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"size": fileInfo.FileSize, "size": fileInfo.FileSize,
"mime_type": fileInfo.MimeType, "mime_type": fileInfo.MimeType,
@@ -38,9 +48,10 @@ func CreateUploadTask(c echo.Context) error {
"expire": fileInfo.Expire, "expire": fileInfo.Expire,
"id": fileId, "id": fileId,
"chunk_size": fileInfo.ChunkSize, "chunk_size": fileInfo.ChunkSize,
"chunks": sliceList,
}) })
} }
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE")) maxStorageSize, err := u.GetFileSize(u.GetEnv("upload.maximum"))
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
@@ -58,50 +69,41 @@ func CreateUploadTask(c echo.Context) error {
totalSize += fileInfo.FileSize totalSize += fileInfo.FileSize
} }
if totalSize+r.FileSize > int64(maxStorageSize) { if totalSize+r.FileSize > int64(maxStorageSize) {
return utils.HTTPErrorHandler(c, errors.New("存储空间不足")) return utils.HTTPErrorHandler(c, ErrInsufficientStorage)
} }
ChunkSize := int64(1 * 1024 * 1024) ChunkSize := int64(0.25 * 1024 * 1024)
if r.FileSize > 500*1024*1024 { // 根据文件大小动态调整块大小
ChunkSize = r.FileSize / 500 for r.FileSize/ChunkSize > 1000 {
ChunkSize *= 2
} }
uploadTaskExpire := int64(3600) redisFileInfo, err := models.SetRedisFileInfo(fileId, func(fileInfo *models.RedisFileInfo) *models.RedisFileInfo {
newFileInfo := models.RedisFileInfo{ fileInfo.FileType = models.FileTypeInit
FileType: models.FileTypeInit, fileInfo.FileInfo = models.FileInfo{
FileInfo: models.FileInfo{
FileSize: r.FileSize, FileSize: r.FileSize,
MimeType: r.MimeType, MimeType: r.MimeType,
FileHash: r.FileHash, FileHash: r.FileHash,
ChunkSize: ChunkSize, ChunkSize: ChunkSize,
}, }
CreatedAt: time.Now().Unix(), return fileInfo
Expire: uploadTaskExpire,
}
err = models.SetRedisFileInfo(fileId, newFileInfo)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
client := utils.GetQueueClient()
json, err := json.Marshal(map[string]any{
"file_id": fileId,
}) })
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
_, err = client.Enqueue(asynq.NewTask("file:remove", json), asynq.ProcessIn(time.Duration(uploadTaskExpire)*time.Second))
err = s.SetFileRemoveTask(fileId, time.Duration(redisFileInfo.Expire)*time.Second)
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"size": newFileInfo.FileSize, "size": redisFileInfo.FileSize,
"mime_type": newFileInfo.MimeType, "mime_type": redisFileInfo.MimeType,
"hash": newFileInfo.FileHash, "hash": redisFileInfo.FileHash,
"type": newFileInfo.FileType, "type": redisFileInfo.FileType,
"expire": newFileInfo.Expire, "expire": redisFileInfo.Expire,
"id": fileId, "id": fileId,
"chunk_size": newFileInfo.ChunkSize, "chunk_size": redisFileInfo.ChunkSize,
}) })
} }
@@ -111,14 +113,14 @@ type UploadFileSliceProps struct {
FileSlice *multipart.FileHeader `form:"file"` FileSlice *multipart.FileHeader `form:"file"`
} }
func UploadFileSlice(c echo.Context) error { func UploadFileSlice(c *echo.Context) error {
r := new(UploadFileSliceProps) r := new(UploadFileSliceProps)
if err := c.Bind(r); err != nil { if err := c.Bind(r); err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if r.FileId == "" || r.FileIndex == 0 || r.FileSlice == nil { if r.FileId == "" || r.FileIndex == 0 || r.FileSlice == nil {
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
fileInfo, err := models.GetRedisFileInfo(r.FileId) fileInfo, err := models.GetRedisFileInfo(r.FileId)
if err != nil { if err != nil {
@@ -127,18 +129,18 @@ func UploadFileSlice(c echo.Context) error {
now := time.Now().Unix() now := time.Now().Unix()
if fileInfo.CreatedAt+fileInfo.Expire < now { if fileInfo.CreatedAt+fileInfo.Expire < now {
return utils.HTTPErrorHandler(c, errors.New("上传任务已过期")) return utils.HTTPErrorHandler(c, ErrUploadTaskExpired)
} }
if fileInfo.FileType != models.FileTypeInit { if fileInfo.FileType != models.FileTypeInit {
return utils.HTTPErrorHandler(c, errors.New("上传任务状态错误")) return utils.HTTPErrorHandler(c, ErrInvalidUploadTaskState)
} }
if r.FileIndex > ((fileInfo.FileSize / fileInfo.ChunkSize) + 1) { if r.FileIndex > ((fileInfo.FileSize / fileInfo.ChunkSize) + 1) {
return utils.HTTPErrorHandler(c, errors.New("文件切片索引错误")) return utils.HTTPErrorHandler(c, ErrInvalidFileSliceIndex)
} }
if r.FileSlice.Size > fileInfo.ChunkSize { if r.FileSlice.Size > fileInfo.ChunkSize {
return utils.HTTPErrorHandler(c, errors.New("文件切片大小错误")) return utils.HTTPErrorHandler(c, ErrInvalidFileSliceSize)
} }
// 打开文件 // 打开文件
@@ -146,9 +148,14 @@ func UploadFileSlice(c echo.Context) error {
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
defer file.Close() defer file.Close() //nolint:errcheck
if err := services.CreateFileSlice(file, r.FileId, r.FileIndex); err != nil { uploadPath, err := u.GetUploadDirPath()
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
if _, err := services.CreateFileSlice(r.FileId, uploadPath, file, r.FileIndex); err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
@@ -161,14 +168,14 @@ type FinishUploadTaskProps struct {
FileId string `json:"id"` FileId string `json:"id"`
} }
func FinishUploadTask(c echo.Context) error { func FinishUploadTask(c *echo.Context) error {
r := new(FinishUploadTaskProps) r := new(FinishUploadTaskProps)
if err := c.Bind(r); err != nil { if err := c.Bind(r); err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if r.FileId == "" { if r.FileId == "" {
return utils.HTTPErrorHandler(c, errors.New("文件ID不能为空")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
fileInfo, err := models.GetRedisFileInfo(r.FileId) fileInfo, err := models.GetRedisFileInfo(r.FileId)
@@ -177,50 +184,68 @@ func FinishUploadTask(c echo.Context) error {
} }
if fileInfo.FileType != models.FileTypeInit { if fileInfo.FileType != models.FileTypeInit {
return utils.HTTPErrorHandler(c, errors.New("上传任务状态错误")) return utils.HTTPErrorHandler(c, ErrInvalidUploadTaskState)
} }
now := time.Now().Unix() now := time.Now().Unix()
if fileInfo.CreatedAt+fileInfo.Expire < now { if fileInfo.CreatedAt+fileInfo.Expire < now {
return utils.HTTPErrorHandler(c, errors.New("上传任务已过期")) return utils.HTTPErrorHandler(c, ErrUploadTaskExpired)
} }
// 合并文件切片 uploadPath, err := u.GetUploadDirPath()
uploadPath, _ := utils.GetUploadDirPath() if err != nil {
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", r.FileId, "tmp")) return utils.HTTPErrorHandler(c, err)
}
fileSliceList, err := services.GetFileSliceList(r.FileId, uploadPath)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
if len(fileSliceList) != int(math.Ceil(float64(fileInfo.FileSize)/float64(fileInfo.ChunkSize))) {
return utils.HTTPErrorHandler(c, ErrIncompleteFileSlices)
}
// 最终合并后的文件路径 // 最终合并后的文件路径
mergeFilePath := filepath.Join(uploadPath, r.FileId) mergeFilePath, err := services.MergeFileSlices(r.FileId, uploadPath)
if err := services.MergeFileSlices(slicesPath, mergeFilePath); err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
// 计算文件MD5 // 计算文件SHA1
file, err := os.Open(mergeFilePath) file, err := os.Open(mergeFilePath)
if err != nil { if err != nil {
file.Close() return utils.HTTPErrorHandler(c, err)
os.Remove(mergeFilePath) }
defer file.Close() //nolint:errcheck
file_hash, err := u.GetFileSHA1(file)
if err != nil || file_hash != fileInfo.FileHash {
defer os.Remove(mergeFilePath) //nolint:errcheck
if err == nil {
return utils.HTTPErrorHandler(c, ErrFileHashMismatch)
}
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
file_hash, err := utils.GetFileMd5(file)
if err != nil {
file.Close()
os.Remove(mergeFilePath)
return utils.HTTPErrorHandler(c, err)
}
if file_hash != fileInfo.FileHash {
file.Close()
os.Remove(mergeFilePath)
return utils.HTTPErrorHandler(c, errors.New("文件MD5不一致"))
}
defer file.Close()
// 更新文件信息 // 更新文件信息
models.SetRedisFileInfo(r.FileId, models.RedisFileInfo{ fileInfo, err = models.SetRedisFileInfo(r.FileId, func(fileInfo *models.RedisFileInfo) *models.RedisFileInfo {
FileType: models.FileTypeUpload, fileInfo.FileType = models.FileTypeUpload
return fileInfo
}) })
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
// 统计
currentDate := time.Now().Format("2006-01-02")
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
stat.FileSize += fileInfo.FileSize
stat.FileNum += 1
return stat
})
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"size": fileInfo.FileSize, "size": fileInfo.FileSize,

View File

@@ -1,17 +1,17 @@
package controllers package controllers
import ( import (
"backend/internal/models"
"backend/internal/utils" "backend/internal/utils"
"backend/middleware"
"encoding/json" "encoding/json"
"errors" "pkg/models"
u "pkg/utils"
"strings" "strings"
"time" "time"
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v5"
gonanoid "github.com/matoous/go-nanoid/v2" gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/spf13/cast"
) )
type CreateShareProps struct { type CreateShareProps struct {
@@ -23,28 +23,31 @@ type CreateShareProps struct {
} }
type ShareConfig struct { type ShareConfig struct {
ExpireAt int `json:"expire_time"` // 分钟 ExpireAt int `json:"expire_time"` // 分钟
ViewNum int64 `json:"download_nums"` ViewNum int64 `json:"download_nums"`
HasPassword bool `json:"has_password"` HasPassword bool `json:"has_password"`
Password string `json:"password"` Password string `json:"password"`
HasNotify bool `json:"has_notify"` HasNotify bool `json:"has_notify"`
NotifyEmail []string `json:"notify_email"` NotifyTypes []string `json:"notify_types"`
HasPickupCode bool `json:"has_pickup_code"` NotifyEmails []string `json:"notify_emails"`
NotifyWebhooks []models.NotifyWebhook `json:"notify_webhooks"`
Locale string `json:"locale"`
HasPickupCode bool `json:"has_pickup_code"`
} }
func CreateShareInfo(c echo.Context) error { func CreateShareInfo(c *echo.Context) error {
cc := c.(*middleware.CustomContext) owner, _ := echo.ContextGet[string](c, "auth")
r := new(CreateShareProps) r := new(CreateShareProps)
if err := cc.Bind(r); err != nil { if err := c.Bind(r); err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if r.Config.ExpireAt < 1 { if r.Config.ExpireAt < 1 {
return utils.HTTPErrorHandler(c, errors.New("非法的分享过期时间")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
ExpireTime := time.Now().Add(time.Duration(r.Config.ExpireAt) * time.Minute) ExpireTime := time.Now().Add(time.Duration(r.Config.ExpireAt) * time.Minute)
if r.Data == "" || (r.Type != models.ShareTypeFile && r.Type != models.ShareTypeText) || ExpireTime.Before(time.Now()) || r.Config.ViewNum < 1 { if r.Data == "" || (r.Type != models.ShareTypeFile && r.Type != models.ShareTypeText) || ExpireTime.Before(time.Now()) || r.Config.ViewNum < 1 {
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
id, err := gonanoid.New() id, err := gonanoid.New()
@@ -58,10 +61,10 @@ func CreateShareInfo(c echo.Context) error {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if fileInfo == nil { if fileInfo == nil {
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在")) return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
} }
if fileInfo.FileType != models.FileTypeUpload { if fileInfo.FileType != models.FileTypeUpload {
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误")) return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
} }
} }
password := "" password := ""
@@ -73,17 +76,45 @@ func CreateShareInfo(c echo.Context) error {
password = hash password = hash
} }
models.SetRedisShareInfo(id, models.RedisShareInfo{ var notifyEmails []string
Data: r.Data, var notifyWebhooks []models.NotifyWebhook
Type: r.Type, if r.Config.HasNotify {
CreatedAt: time.Now().Unix(), hasEmail, hasWebhook := false, false
Owner: cc.Auth.(string), for _, nt := range r.Config.NotifyTypes {
ViewNum: r.Config.ViewNum, switch nt {
Password: password, case "email":
// NotifyEmail: r.Config.NotifyEmail, hasEmail = true
FileName: r.FileName, case "webhook":
ExpireAt: ExpireTime.Unix(), hasWebhook = true
default:
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
}
}
if hasEmail {
notifyEmails = r.Config.NotifyEmails
}
if hasWebhook {
notifyWebhooks = r.Config.NotifyWebhooks
}
}
_, err = models.SetRedisShareInfo(id, func(shareInfo *models.RedisShareInfo) *models.RedisShareInfo {
shareInfo.Data = r.Data
shareInfo.Type = r.Type
shareInfo.CreatedAt = time.Now().Unix()
shareInfo.Owner = owner
shareInfo.ViewNum = r.Config.ViewNum
shareInfo.Password = password
shareInfo.FileName = r.FileName
shareInfo.NotifyEmails = notifyEmails
shareInfo.NotifyWebhooks = notifyWebhooks
shareInfo.Locale = r.Config.Locale
shareInfo.ExpireAt = ExpireTime.Unix()
return shareInfo
}) })
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
var pickupCode string var pickupCode string
if r.Config.HasPickupCode { if r.Config.HasPickupCode {
for { for {
@@ -105,18 +136,34 @@ func CreateShareInfo(c echo.Context) error {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
shareIDs = append(shareIDs, id) shareIDs = append(shareIDs, id)
models.SetRedisFileShareRelational(r.Data, shareIDs) err = models.SetRedisFileShareRelational(r.Data, shareIDs)
client := utils.GetQueueClient() if err != nil {
return utils.HTTPErrorHandler(c, err)
}
client := u.GetQueueClient()
json, err := json.Marshal(map[string]any{"share_id": id, "file_id": r.Data}) json, err := json.Marshal(map[string]any{"share_id": id, "file_id": r.Data})
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(time.Duration(r.Config.ExpireAt)*time.Minute)) // 这里延时分享过期时间基础上加下载窗口期后1小时删除防止用户过期前几分钟才开始下载下载一半文件不见了
downloadWindow := u.GetEnvWithDefault("share.download_window", "12")
deleteTime := time.Duration(r.Config.ExpireAt)*time.Minute + cast.ToDuration(downloadWindow+"h") + 1*time.Hour
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(deleteTime))
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
} }
// 统计分享数
currentDate := time.Now().Format("2006-01-02")
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
stat.ShareNum += 1
return stat
})
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"id": id, "id": id,
"file_name": r.FileName, "file_name": r.FileName,
@@ -130,11 +177,10 @@ type GetShareProps struct {
ShareId string `param:"id"` ShareId string `param:"id"`
} }
func GetShareInfo(c echo.Context) error { func GetShareInfo(c *echo.Context) error {
cc := c.(*middleware.CustomContext) shareId := c.Param("id")
shareId := cc.Param("id")
if shareId == "" { if shareId == "" {
return utils.HTTPErrorHandler(c, errors.New("缺少分享ID")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
shareInfo, err := models.GetRedisShareInfo(shareId) shareInfo, err := models.GetRedisShareInfo(shareId)
@@ -142,7 +188,7 @@ func GetShareInfo(c echo.Context) error {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if shareInfo == nil || shareInfo.ViewNum < 1 { if shareInfo == nil || shareInfo.ViewNum < 1 {
return utils.HTTPErrorHandler(c, errors.New("分享不存在")) return utils.HTTPErrorHandler(c, ErrShareNotFound)
} }
if shareInfo.Type == models.ShareTypeFile { if shareInfo.Type == models.ShareTypeFile {
@@ -151,10 +197,10 @@ func GetShareInfo(c echo.Context) error {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if fileInfo == nil { if fileInfo == nil {
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在")) return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
} }
if fileInfo.FileType != models.FileTypeUpload { if fileInfo.FileType != models.FileTypeUpload {
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误")) return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
} }
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"id": shareId, "id": shareId,
@@ -180,18 +226,17 @@ func GetShareInfo(c echo.Context) error {
}) })
} }
func GetShareByPickupCode(c echo.Context) error { func GetShareByPickupCode(c *echo.Context) error {
cc := c.(*middleware.CustomContext) pickupCode := c.Param("code")
pickupCode := cc.Param("code")
if pickupCode == "" { if pickupCode == "" {
return utils.HTTPErrorHandler(c, errors.New("缺少提取码")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
shareId, err := models.GetRedisPickupData(strings.ToUpper(pickupCode)) shareId, err := models.GetRedisPickupData(strings.ToUpper(pickupCode))
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if shareId == "" { if shareId == "" {
return utils.HTTPErrorHandler(c, errors.New("分享不存在")) return utils.HTTPErrorHandler(c, ErrShareNotFound)
} }
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"share_id": shareId, "share_id": shareId,

View File

@@ -1,102 +1,75 @@
package controllers package controllers
import ( import (
"backend/internal/models"
"backend/internal/utils" "backend/internal/utils"
"encoding/json" "encoding/json"
"time" "pkg/models"
u "pkg/utils"
"github.com/hibiken/asynq" "github.com/labstack/echo/v5"
"github.com/labstack/echo/v4"
"github.com/samber/lo"
"github.com/spf13/cast"
) )
type FileChartData struct { const (
FileSize int64 `json:"file_size"` DateLayout = "2006-01-02"
FileNum int64 `json:"file_num"` DaysToAnalyze = 30
Date string `json:"date"` QueueHistoryDays = 30
)
type StatChartData struct {
FileSize int64 `json:"file_size"`
FileNum int64 `json:"file_num"`
ShareNum int64 `json:"share_num"`
DownloadNum int64 `json:"download_num"`
} }
func GetStat(c echo.Context) error { type QueueChartData struct {
fileInfoMap, err := models.GetRedisFileInfoAll() Processed int `json:"processed"`
Failed int `json:"failed"`
}
func GetStat(c *echo.Context) error {
statInfoMap, err := models.GetRedisStatAll()
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
fileChartData := make(map[string]FileChartData)
for _, value := range fileInfoMap { statChartData := make(map[string]StatChartData)
var fileInfo models.RedisFileInfo for key, value := range statInfoMap {
err := json.Unmarshal([]byte(value), &fileInfo) var statData models.StatData
err := json.Unmarshal([]byte(value), &statData)
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if fileInfo.FileType != models.FileTypeUpload { statChartData[key] = StatChartData{
FileSize: statData.FileSize,
FileNum: statData.FileNum,
ShareNum: statData.ShareNum,
DownloadNum: statData.DownloadNum,
}
}
queueInspector := u.GetQueueInspector()
queues, err := queueInspector.History("default", QueueHistoryDays)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
queuesChartData := make(map[string]QueueChartData)
for _, item := range queues {
dateKey := item.Date.Format(DateLayout)
if item.Processed == 0 && item.Failed == 0 {
continue continue
} }
if time.Unix(fileInfo.CreatedAt, 0).After(time.Now().Add(-30 * 24 * time.Hour)) { queuesChartData[dateKey] = QueueChartData{
dateKey := time.Unix(fileInfo.CreatedAt, 0).Format("2006-01-02") Processed: item.Processed,
if data, ok := fileChartData[dateKey]; ok { Failed: item.Failed,
fileChartData[dateKey] = FileChartData{
FileSize: data.FileSize + fileInfo.FileSize,
FileNum: data.FileNum + 1,
}
} else {
fileChartData[dateKey] = FileChartData{
FileSize: fileInfo.FileSize,
FileNum: 1,
}
}
} }
} }
storageChartData := lo.Times(30, func(i int) FileChartData {
dateKey := time.Now().AddDate(0, 0, -i).Format("2006-01-02")
if data, ok := fileChartData[dateKey]; ok {
return FileChartData{
FileSize: data.FileSize,
FileNum: data.FileNum,
Date: dateKey,
}
}
return FileChartData{
FileSize: 0,
FileNum: 0,
Date: dateKey,
}
})
queueInspector := utils.GetQueueInspector()
queues, err := queueInspector.History("default", 30)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
queueData := lo.Map(queues, func(item *asynq.DailyStats, _ int) map[string]any {
return map[string]any{
"date": item.Date.Format("2006-01-02"),
"processed": item.Processed,
"failed": item.Failed,
}
})
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"version": utils.GetEnvWithDefault("VERSION", "dev"),
"build_time": cast.ToInt(utils.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
"max_limit": map[string]any{
"file_size": maxStorageSize,
},
"admin": map[string]any{
"name": utils.GetEnv("ADMIN_NAME"),
"email": utils.GetEnv("ADMIN_EMAIL"),
"url": utils.GetEnv("ADMIN_URL"),
},
"chart": map[string]any{ "chart": map[string]any{
"storage": storageChartData, "storage": statChartData,
"queue": queueData, "queue": queuesChartData,
}, },
}) })
} }

View File

@@ -1,38 +1,37 @@
package controllers package controllers
import ( import (
"backend/internal/models" "backend/internal/controllers/task"
"backend/internal/utils" "backend/internal/utils"
"backend/middleware" "pkg/models"
"encoding/json" u "pkg/utils"
"errors"
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v5"
) )
type GenCompressImageRequest struct { var handleTaskMap = map[string]func(c *echo.Context) ([]byte, error){
FileId string `json:"file_id"` "image:compress": task.HandleImageCompress,
"image:convert": task.HandleImageConvert,
"text:translate": task.HandleTextTranslate,
} }
func GenCompressImage(c echo.Context) error { func CreateTask(c *echo.Context) error {
cc := c.(*middleware.CustomContext) taskType := c.Param("type")
r := new(GenCompressImageRequest) if taskType == "" {
if err := cc.Bind(r); err != nil { return utils.HTTPErrorHandler(c, ErrInvalidRequest)
return utils.HTTPErrorHandler(c, err)
} }
handleTask, ok := handleTaskMap[taskType]
if r.FileId == "" { if !ok {
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误")) return utils.HTTPErrorHandler(c, ErrTaskNotFound)
} }
client := utils.GetQueueClient() json, err := handleTask(c)
json, err := json.Marshal(map[string]any{
"file_id": r.FileId,
})
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
info, err := client.Enqueue(asynq.NewTask("image:compress", json), asynq.MaxRetry(3))
client := u.GetQueueClient()
info, err := client.Enqueue(asynq.NewTask(taskType, json), asynq.MaxRetry(3))
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
@@ -42,11 +41,10 @@ func GenCompressImage(c echo.Context) error {
}) })
} }
func GetCompressImage(c echo.Context) error { func GetTask(c *echo.Context) error {
cc := c.(*middleware.CustomContext) taskId := c.Param("id")
taskId := cc.Param("id")
if taskId == "" { if taskId == "" {
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误")) return utils.HTTPErrorHandler(c, ErrInvalidRequest)
} }
taskInfo, err := models.GetRedisTaskInfo(taskId) taskInfo, err := models.GetRedisTaskInfo(taskId)
@@ -54,11 +52,11 @@ func GetCompressImage(c echo.Context) error {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
} }
if taskInfo == nil { if taskInfo == nil {
client := utils.GetQueueInspector() client := u.GetQueueInspector()
queneTaskInfo, err := client.GetTaskInfo("default", taskId) queneTaskInfo, err := client.GetTaskInfo("default", taskId)
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, errors.New("任务已过期")) return utils.HTTPErrorHandler(c, ErrTaskExpired)
} }
stateMap := map[asynq.TaskState]string{ stateMap := map[asynq.TaskState]string{
asynq.TaskStateActive: "processing", asynq.TaskStateActive: "processing",

View File

@@ -0,0 +1,7 @@
package task
import "errors"
var (
ErrInvalidRequest = errors.New("InvalidRequest")
)

View File

@@ -0,0 +1,53 @@
package task
import (
"encoding/json"
"github.com/labstack/echo/v5"
)
type BaseImageRequest struct {
FileId string `json:"file_id"`
}
func HandleImageCompress(c *echo.Context) ([]byte, error) {
r := new(BaseImageRequest)
if err := c.Bind(r); err != nil {
return nil, err
}
if r.FileId == "" {
return nil, ErrInvalidRequest
}
json, err := json.Marshal(map[string]any{
"file_id": r.FileId,
})
if err != nil {
return nil, err
}
return json, nil
}
type ImageConvertRequest struct {
BaseImageRequest
TargetExt string `json:"target_ext"`
}
func HandleImageConvert(c *echo.Context) ([]byte, error) {
r := new(ImageConvertRequest)
if err := c.Bind(r); err != nil {
return nil, err
}
if r.FileId == "" || r.TargetExt == "" {
return nil, ErrInvalidRequest
}
json, err := json.Marshal(map[string]any{
"file_id": r.FileId,
"target_ext": r.TargetExt,
})
if err != nil {
return nil, err
}
return json, nil
}

View File

@@ -0,0 +1,45 @@
package task
import (
"encoding/json"
"github.com/labstack/echo/v5"
)
var validProviders = map[string]bool{
"google": true,
"microsoft": true,
"deeplx": true,
"deepseek": true,
}
var validSources = map[string]bool{
"auto": true,
"zh-CN": true,
"en": true,
"ja": true,
"ko": true,
}
type TranslateTextRequest struct {
Text string `json:"text"`
Source string `json:"source"`
Target string `json:"target"`
Provider string `json:"provider"`
}
func HandleTextTranslate(c *echo.Context) ([]byte, error) {
r := new(TranslateTextRequest)
if err := c.Bind(r); err != nil {
return nil, err
}
if r.Text == "" || r.Target == "" || !validProviders[r.Provider] || !validSources[r.Source] {
return nil, ErrInvalidRequest
}
return json.Marshal(map[string]any{
"text": r.Text,
"source": r.Source,
"target": r.Target,
"provider": r.Provider,
})
}

View File

@@ -1,65 +0,0 @@
package models
import (
"backend/internal/utils"
"encoding/json"
"dario.cat/mergo"
"github.com/redis/go-redis/v9"
)
type FileInfo struct {
FileSize int64 `json:"size"`
MimeType string `json:"mime_type"`
FileHash string `json:"hash"`
ChunkSize int64 `json:"chunk_size"`
}
type FileType string
const (
FileTypeInit FileType = "init"
FileTypeUpload FileType = "already"
)
type RedisFileInfo struct {
FileInfo
FileType FileType `json:"type"`
CreatedAt int64 `json:"created_at"`
Expire int64 `json:"expire"` // 只有上传文件(init)的时候有这个字段
}
func GetRedisFileInfo(fileId string) (*RedisFileInfo, error) {
rdb, ctx := utils.GetRedisClient()
fileInfoUnmarshalData, err := rdb.HGet(ctx, "015:fileInfoMap", fileId).Result()
if err == redis.Nil {
return nil, nil
}
if err != nil {
return nil, err
}
var fileInfoData RedisFileInfo
if err := json.Unmarshal([]byte(fileInfoUnmarshalData), &fileInfoData); err != nil {
return nil, err
}
return &fileInfoData, nil
}
func SetRedisFileInfo(fileId string, fileInfo RedisFileInfo) error {
rdb, ctx := utils.GetRedisClient()
old_fileInfo, err := GetRedisFileInfo(fileId)
if err != nil {
return err
}
if old_fileInfo != nil {
mergo.Merge(&fileInfo, old_fileInfo)
}
jsonData, _ := json.Marshal(fileInfo)
_, err = rdb.HSet(ctx, "015:fileInfoMap", fileId, string(jsonData)).Result()
return err
}
func GetRedisFileInfoAll() (map[string]string, error) {
rdb, ctx := utils.GetRedisClient()
return rdb.HGetAll(ctx, "015:fileInfoMap").Result()
}

View File

@@ -1,31 +0,0 @@
package models
import (
"backend/internal/utils"
"encoding/json"
"github.com/redis/go-redis/v9"
)
func GetRedisFileShareRelational(fileId string) ([]string, error) {
rdb, ctx := utils.GetRedisClient()
fileShareRelationalUnmarshalData, err := rdb.HGet(ctx, "015:fileShareRelational", fileId).Result()
if err == redis.Nil {
return nil, nil
}
if err != nil {
return nil, err
}
var shareIDs []string
if err := json.Unmarshal([]byte(fileShareRelationalUnmarshalData), &shareIDs); err != nil {
return nil, err
}
return shareIDs, nil
}
func SetRedisFileShareRelational(fileId string, shareIDs []string) error {
rdb, ctx := utils.GetRedisClient()
jsonData, _ := json.Marshal(shareIDs)
_, err := rdb.HSet(ctx, "015:fileShareRelational", fileId, string(jsonData)).Result()
return err
}

View File

@@ -1,27 +0,0 @@
package models
import (
"backend/internal/utils"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func GetRedisPickupData(pickupCode string) (string, error) {
rdb, ctx := utils.GetRedisClient()
ShareId, err := rdb.Get(ctx, fmt.Sprintf("015:pickupCode:%s", pickupCode)).Result()
if err == redis.Nil {
return "", nil
}
if err != nil {
return "", err
}
return ShareId, nil
}
func SetRedisPickupData(pickupCode string, shareId string) (bool, error) {
rdb, ctx := utils.GetRedisClient()
ok, err := rdb.SetNX(ctx, fmt.Sprintf("015:pickupCode:%s", pickupCode), shareId, time.Until(time.Now().Add(24*time.Hour))).Result()
return ok, err
}

View File

@@ -1,66 +0,0 @@
package models
import (
"backend/internal/utils"
"encoding/json"
"fmt"
"time"
"dario.cat/mergo"
"github.com/redis/go-redis/v9"
)
type RedisShareInfo struct {
// Id string `json:"id"`
CreatedAt int64 `json:"created_at"`
Owner string `json:"owner"`
Type ShareType `json:"type"`
Data string `json:"data"` // 分享数据 文件分享为文件id 文本分享为文本内容
ExpireAt int64 `json:"expire_time"`
ViewNum int64 `json:"download_nums"`
Password string `json:"password"`
NotifyEmail []string `json:"notify_email"`
FileName string `json:"file_name"`
// PickupCode bool `json:"pickup_code"`
}
type ShareType string
const (
ShareTypeFile ShareType = "file"
ShareTypeText ShareType = "text"
)
func GetRedisShareInfo(shareId string) (*RedisShareInfo, error) {
rdb, ctx := utils.GetRedisClient()
shareInfo := rdb.Get(ctx, fmt.Sprintf("015:shareInfoMap:%s", shareId))
shareInfoUnmarshalData, err := shareInfo.Result()
ttl, _ := rdb.TTL(ctx, fmt.Sprintf("015:shareInfoMap:%s", shareId)).Result()
if err == redis.Nil {
return nil, nil
}
if err != nil {
return nil, err
}
var shareInfoData RedisShareInfo
if err := json.Unmarshal([]byte(shareInfoUnmarshalData), &shareInfoData); err != nil {
return nil, err
}
shareInfoData.ExpireAt = time.Now().Add(ttl).Unix()
return &shareInfoData, nil
}
func SetRedisShareInfo(shareId string, shareInfo RedisShareInfo) error {
rdb, ctx := utils.GetRedisClient()
old_shareInfo, err := GetRedisShareInfo(shareId)
if err != nil {
return err
}
if old_shareInfo != nil {
mergo.Merge(&shareInfo, old_shareInfo)
}
jsonData, _ := json.Marshal(shareInfo)
_, err = rdb.Set(ctx, fmt.Sprintf("015:shareInfoMap:%s", shareId), string(jsonData), time.Until(time.Unix(shareInfo.ExpireAt, 0))).Result()
return err
}

View File

@@ -1,35 +0,0 @@
package models
import (
"backend/internal/utils"
"encoding/json"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func GetRedisTaskInfo(taskId string) (*map[string]any, error) {
rdb, ctx := utils.GetRedisClient()
taskInfo := rdb.Get(ctx, fmt.Sprintf("015:taskInfoMap:%s", taskId))
taskInfoUnmarshalData, err := taskInfo.Result()
if err == redis.Nil {
return nil, nil
}
if err != nil {
return nil, err
}
var taskInfoData map[string]any
if err := json.Unmarshal([]byte(taskInfoUnmarshalData), &taskInfoData); err != nil {
return nil, err
}
return &taskInfoData, nil
}
func SetRedisTaskInfo(taskId string, taskInfo map[string]any) error {
rdb, ctx := utils.GetRedisClient()
jsonData, _ := json.Marshal(taskInfo)
_, err := rdb.Set(ctx, fmt.Sprintf("015:taskInfoMap:%s", taskId), jsonData, time.Hour).Result()
return err
}

View File

@@ -1,89 +1,84 @@
package services package services
import ( import (
"backend/internal/utils"
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"strconv" "strconv"
) )
func CreateFileSlice(fileSlice io.Reader, fileId string, fileIndex int64) error { func CreateFileSlice(fileId string, uploadPath string, fileSlice io.Reader, fileIndex int64) (string, error) {
uploadPath, err := utils.GetUploadDirPath()
if err != nil {
return err
}
filePath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp")) filePath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
if err := os.MkdirAll(filePath, 0755); err != nil { if err := os.MkdirAll(filePath, 0755); err != nil {
return err return "", err
} }
dst, err := os.Create(filepath.Join(filePath, fmt.Sprintf("%d", fileIndex))) dst, err := os.Create(filepath.Join(filePath, fmt.Sprintf("%d", fileIndex)))
if err != nil { if err != nil {
return err return "", err
} }
defer dst.Close() defer dst.Close() //nolint:errcheck
if _, err = io.Copy(dst, fileSlice); err != nil { if _, err = io.Copy(dst, fileSlice); err != nil {
return err return "", err
} }
return nil return filePath, nil
} }
// MergeFileSlices 合并文件切片 func GetFileSliceList(fileId string, uploadPath string) ([]int, error) {
func MergeFileSlices(slicesPath string, mergeFilePath string) error { slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
// 创建最终文件
destFile, err := os.Create(mergeFilePath)
if err != nil {
return fmt.Errorf("创建合并文件失败: %v", err)
}
defer destFile.Close()
// 读取目录下的所有文件
files, err := os.ReadDir(slicesPath) files, err := os.ReadDir(slicesPath)
if err != nil { if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("读取切片目录失败: %v", err) return nil, fmt.Errorf("读取切片目录失败: %v", err)
} }
fileSliceList := []int{}
// 按照索引排序文件切片
sliceFiles := make([]string, len(files))
for _, file := range files { for _, file := range files {
index, err := strconv.Atoi(file.Name()) index, err := strconv.Atoi(file.Name())
if err != nil { if err != nil {
return fmt.Errorf("无效的切片文件名: %v", err) return nil, fmt.Errorf("无效的切片文件名: %v", err)
} }
sliceFiles[index-1] = filepath.Join(slicesPath, file.Name()) fileSliceList = append(fileSliceList, index)
}
sort.Ints(fileSliceList)
return fileSliceList, nil
}
// MergeFileSlices 合并文件切片
func MergeFileSlices(fileId string, uploadPath string) (string, error) {
mergeFilePath := filepath.Join(uploadPath, fileId)
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
defer os.RemoveAll(slicesPath) //nolint:errcheck
// 创建最终文件
destFile, err := os.Create(mergeFilePath)
if err != nil {
return "", fmt.Errorf("创建合并文件失败: %v", err)
}
defer destFile.Close() //nolint:errcheck
fileSliceList, err := GetFileSliceList(fileId, uploadPath)
if err != nil {
return "", err
} }
// 合并文件 // 合并文件
buffer := make([]byte, 4*1024*1024) // 4MB buffer buffer := make([]byte, 4*1024*1024) // 4MB buffer
for _, sliceFile := range sliceFiles { for _, index := range fileSliceList {
sf, err := os.Open(sliceFile) sliceFilePath := filepath.Join(slicesPath, fmt.Sprintf("%d", index))
sf, err := os.Open(sliceFilePath)
if err != nil { if err != nil {
return fmt.Errorf("打开切片文件失败: %v", err) return "", fmt.Errorf("打开切片文件失败: %v", err)
} }
for { if _, err := io.CopyBuffer(destFile, sf, buffer); err != nil {
n, err := sf.Read(buffer) sf.Close() //nolint:errcheck
if err == io.EOF { return "", fmt.Errorf("合并切片文件失败: %v", err)
break }
} if err := sf.Close(); err != nil {
if err != nil { return "", fmt.Errorf("关闭切片文件失败: %v", err)
sf.Close()
return fmt.Errorf("读取切片文件失败: %v", err)
}
if _, err := destFile.Write(buffer[:n]); err != nil {
sf.Close()
return fmt.Errorf("写入合并文件失败: %v", err)
}
} }
sf.Close()
} }
defer os.RemoveAll(slicesPath) return mergeFilePath, nil
return nil
} }

View File

@@ -1,21 +0,0 @@
package utils
import "github.com/hibiken/asynq"
func GetQueueClient() *asynq.Client {
opt := RedisURI2AsynqOpt(GetEnv("REDIS_URL"))
return asynq.NewClient(opt)
}
func GetQueueInspector() *asynq.Inspector {
opt := RedisURI2AsynqOpt(GetEnv("REDIS_URL"))
return asynq.NewInspector(opt)
}
func RedisURI2AsynqOpt(uri string) asynq.RedisConnOpt {
opt, err := asynq.ParseRedisURI(GetEnv("REDIS_URL"))
if err != nil {
panic(err)
}
return opt
}

View File

@@ -1,42 +0,0 @@
package utils
import (
"github.com/spf13/viper"
)
var v *viper.Viper
func init() {
InitEnv()
}
func InitEnv() {
if v != nil {
return
}
v = viper.New()
v.SetConfigName(".env")
v.SetConfigType("env")
v.AddConfigPath(".")
v.AddConfigPath("../")
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// 只有当错误不是"配置文件未找到"时才 panic
panic(err)
}
}
}
func GetEnv(key string) string {
InitEnv()
return v.GetString(key)
}
func GetEnvWithDefault(key string, defaultValue string) string {
value := v.GetString(key)
if value == "" {
return defaultValue
}
return value
}

View File

@@ -1,53 +0,0 @@
package utils
import (
"bufio"
"crypto/md5"
"fmt"
"io"
"os"
"path/filepath"
humanize "github.com/dustin/go-humanize"
)
func GetFileId(fileHash string, fileSize int64) string {
return fmt.Sprintf("%s_%d", fileHash, fileSize)
}
func GetFileMd5(file io.Reader) (string, error) {
const bufferSize = 1024 * 1000 // 1MB
hash := md5.New()
for buf, reader := make([]byte, bufferSize), bufio.NewReader(file); ; {
n, err := reader.Read(buf)
if err != nil {
if err == io.EOF {
break
}
return "", err
}
hash.Write(buf[:n])
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
func GetUploadDirPath() (string, error) {
basepath, err := os.Getwd()
if err != nil {
return "", err
}
finalPath := filepath.Join(basepath, "uploads")
uploadPath := GetEnvWithDefault("UPLOAD_PATH", finalPath)
if err := os.MkdirAll(uploadPath, 0755); err != nil {
return "", err
}
return uploadPath, nil
}
func GetFileSize(size string) (uint64, error) {
return humanize.ParseBytes(size)
}

View File

@@ -3,43 +3,39 @@ package utils
import ( import (
"net/http" "net/http"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v5"
) )
type Option interface {
applyTo(*HTTPBaseResponse)
}
type HTTPBaseResponse struct { type HTTPBaseResponse struct {
code int code int
message string message string
data map[string]any data map[string]any
} }
type HTTPBaseResponseProps func(props *HTTPBaseResponse) error type HTTPBaseResponseProps func(props *HTTPBaseResponse)
type WithCode int func WithCode(data int) HTTPBaseResponseProps {
return func(props *HTTPBaseResponse) {
func (o WithCode) applyTo(props *HTTPBaseResponse) { props.code = data
props.code = int(o) }
} }
type WithMessage string func WithMessage(data string) HTTPBaseResponseProps {
return func(props *HTTPBaseResponse) {
func (o WithMessage) applyTo(props *HTTPBaseResponse) { props.message = data
props.message = string(o) }
} }
type WithData map[string]any func WithData(data map[string]any) HTTPBaseResponseProps {
return func(props *HTTPBaseResponse) {
func (o WithData) applyTo(props *HTTPBaseResponse) { props.data = data
props.data = o }
} }
func HTTPBaseHandler(c echo.Context, options ...Option) error { func HTTPBaseHandler(c *echo.Context, options ...HTTPBaseResponseProps) error {
props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}} props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}}
for _, option := range options { for _, option := range options {
option.applyTo(&props) option(&props)
} }
return c.JSON(props.code, map[string]any{ return c.JSON(props.code, map[string]any{
@@ -49,10 +45,12 @@ func HTTPBaseHandler(c echo.Context, options ...Option) error {
}) })
} }
func HTTPSuccessHandler(c echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error { func HTTPSuccessHandler(c *echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
return HTTPBaseHandler(c, WithData(data)) options = append([]HTTPBaseResponseProps{WithData(data)}, options...)
return HTTPBaseHandler(c, options...)
} }
func HTTPErrorHandler(c echo.Context, err error, options ...HTTPBaseResponseProps) error { func HTTPErrorHandler(c *echo.Context, err error, options ...HTTPBaseResponseProps) error {
return HTTPBaseHandler(c, WithMessage(err.Error()), WithCode(http.StatusBadRequest)) options = append([]HTTPBaseResponseProps{WithMessage(err.Error()), WithCode(http.StatusBadRequest)}, options...)
return HTTPBaseHandler(c, options...)
} }

View File

@@ -3,14 +3,19 @@ package utils
import ( import (
"errors" "errors"
"fmt" "fmt"
"pkg/utils"
"golang.org/x/crypto/argon2" "golang.org/x/crypto/argon2"
) )
var (
ErrPasswordSaltNotSet = errors.New("PasswordSaltNotSet")
)
func GeneratePasswordHash(password string) (string, error) { func GeneratePasswordHash(password string) (string, error) {
salt := GetEnv("PASSWORD_SALT") salt := utils.GetEnv("share.password_salt")
if salt == "" { if salt == "" {
return "", errors.New("请配置PASSWORD_SALT") return "", ErrPasswordSaltNotSet
} }
hash := argon2.IDKey([]byte(password), []byte(salt), 1, 64*1024, 4, 32) hash := argon2.IDKey([]byte(password), []byte(salt), 1, 64*1024, 4, 32)
return fmt.Sprintf("%x", hash), nil return fmt.Sprintf("%x", hash), nil

View File

@@ -1,22 +0,0 @@
package utils
import (
"context"
"github.com/redis/go-redis/v9"
)
var rdb *redis.Client = InitRedis()
var ctx = context.Background()
func InitRedis() *redis.Client {
opt, err := redis.ParseURL(GetEnv("REDIS_URL"))
if err != nil {
panic(err)
}
return redis.NewClient(opt)
}
func GetRedisClient() (*redis.Client, context.Context) {
return rdb, ctx
}

View File

@@ -0,0 +1,16 @@
package utils
import (
"fmt"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v5"
)
func GetSession(c *echo.Context, name string) (*sessions.Session, error) {
store, err := echo.ContextGet[sessions.Store](c, "_session_store")
if err != nil {
return nil, fmt.Errorf("failed to get session store: %w", err)
}
return store.Get(c.Request(), name)
}

View File

@@ -1,44 +1,42 @@
package main package main
import ( import (
"backend/internal/controllers" "fmt"
"backend/internal/utils" "pkg/utils"
"backend/middleware"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v5"
"go.uber.org/zap" "go.uber.org/zap"
) )
func main() { func main() {
// 日志 // 日志
var logger *zap.Logger var logger *zap.Logger
if utils.GetEnvWithDefault("NODE_ENV", "production") == "production" { if utils.GetEnvWithDefault("node.env", "production") == "production" {
logger, _ = zap.NewProduction() logger, _ = zap.NewProduction()
} else { } else {
logger, _ = zap.NewDevelopment() logger, _ = zap.NewDevelopment()
} }
defer logger.Sync() defer logger.Sync() //nolint:errcheck
zap.ReplaceGlobals(logger) zap.ReplaceGlobals(logger)
// redis
if err := utils.InitRedis(); err != nil {
logger.Fatal("redis init failed", zap.Error(err))
panic(err)
}
if err := utils.InitAsynq(); err != nil {
logger.Fatal("asynq init failed", zap.Error(err))
panic(err)
}
e := echo.New() e := echo.New()
e.Use(middleware.ContextMiddleware()) for _, middleware := range middlewares {
e.Use(middleware.SessionMiddleware()) e.Use(middleware())
e.Use(middleware.AuthMiddleware()) }
e.Use(middleware.RateLimiterMiddleware())
e.Use(middleware.LoggerMiddleware())
e.POST("/file/create", controllers.CreateUploadTask) for _, route := range routes {
e.POST("/file/slice", controllers.UploadFileSlice) e.Match(route.Method, route.Path, route.Handler)
e.POST("/file/finish", controllers.FinishUploadTask) }
e.GET("/share/:id", controllers.GetShareInfo) if err := e.Start(fmt.Sprintf(":%s", utils.GetEnvWithDefault("api.port", "5001"))); err != nil {
e.POST("/share", controllers.CreateShareInfo) logger.Fatal("server failed", zap.Error(err))
e.GET("/download", controllers.DownloadShare) }
e.POST("/download", controllers.VaildateShare)
e.GET("/share/pickup/:code", controllers.GetShareByPickupCode)
e.POST("/image/compress", controllers.GenCompressImage)
e.GET("/image/compress/:id", controllers.GetCompressImage)
e.GET("/stat", controllers.GetStat)
e.Logger.Fatal(e.Start(":1323"))
} }

14
backend/middleware.go Normal file
View File

@@ -0,0 +1,14 @@
package main
import (
"backend/middleware"
"github.com/labstack/echo/v5"
)
var middlewares = []func() echo.MiddlewareFunc{
middleware.SessionMiddleware,
middleware.AuthMiddleware,
middleware.RateLimiterMiddleware,
middleware.LoggerMiddleware,
}

View File

@@ -1,17 +1,18 @@
package middleware package middleware
import ( import (
"backend/internal/utils"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v5"
"github.com/labstack/echo/v4"
gonanoid "github.com/matoous/go-nanoid/v2" gonanoid "github.com/matoous/go-nanoid/v2"
) )
// CustomMiddleware 创建自定义中间件 // CustomMiddleware 创建自定义中间件
func AuthMiddleware() echo.MiddlewareFunc { func AuthMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c *echo.Context) error {
sess, err := session.Get("session", c) sess, err := utils.GetSession(c, "session")
if err != nil { if err != nil {
return err return err
} }
@@ -30,11 +31,8 @@ func AuthMiddleware() echo.MiddlewareFunc {
return err return err
} }
} }
c.Set("auth", sess.Values["auth"])
cc := c.(*CustomContext) return next(c)
cc.Auth = sess.Values["auth"]
// 将自定义上下文传递给下一个处理器
return next(cc)
} }
} }
} }

View File

@@ -1,28 +0,0 @@
package middleware
import (
"github.com/labstack/echo/v4"
)
// CustomContext 扩展 echo.Context 以添加自定义功能
type CustomContext struct {
echo.Context
Auth interface{}
}
// NewCustomContext 创建自定义上下文的构造函数
func NewCustomContext(c echo.Context) *CustomContext {
return &CustomContext{
Context: c,
}
}
// ContextMiddleware 中间件用于将标准 echo.Context 转换为 CustomContext
func ContextMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := NewCustomContext(c)
return next(cc)
}
}
}

View File

@@ -1,8 +1,8 @@
package middleware package middleware
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v5"
"github.com/labstack/echo/v4/middleware" "github.com/labstack/echo/v5/middleware"
"go.uber.org/zap" "go.uber.org/zap"
) )
@@ -10,7 +10,7 @@ func LoggerMiddleware() echo.MiddlewareFunc {
return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true, LogURI: true,
LogStatus: true, LogStatus: true,
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerValues) error {
zap.L().Info("request", zap.L().Info("request",
zap.String("url", v.URI), zap.String("url", v.URI),
zap.Int("status", v.Status), zap.Int("status", v.Status),

View File

@@ -5,9 +5,8 @@ import (
"slices" "slices"
"time" "time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v5"
echo_middleware "github.com/labstack/echo/v4/middleware" echo_middleware "github.com/labstack/echo/v5/middleware"
"golang.org/x/time/rate"
) )
type RateSkiper struct { type RateSkiper struct {
@@ -23,22 +22,22 @@ var RateSkipList = []RateSkiper{
func RateLimiterMiddleware() echo.MiddlewareFunc { func RateLimiterMiddleware() echo.MiddlewareFunc {
config := echo_middleware.RateLimiterConfig{ config := echo_middleware.RateLimiterConfig{
Skipper: func(e echo.Context) bool { Skipper: func(e *echo.Context) bool {
path := e.Path() path := e.Path()
r := e.Request() r := e.Request()
return slices.Contains(RateSkipList, RateSkiper{Path: path, Method: r.Method}) return slices.Contains(RateSkipList, RateSkiper{Path: path, Method: r.Method})
}, },
Store: echo_middleware.NewRateLimiterMemoryStoreWithConfig( Store: echo_middleware.NewRateLimiterMemoryStoreWithConfig(
echo_middleware.RateLimiterMemoryStoreConfig{Rate: rate.Limit(10), Burst: 30, ExpiresIn: 3 * time.Minute}, echo_middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute},
), ),
IdentifierExtractor: func(ctx echo.Context) (string, error) { IdentifierExtractor: func(ctx *echo.Context) (string, error) {
id := ctx.RealIP() id := ctx.RealIP()
return id, nil return id, nil
}, },
ErrorHandler: func(context echo.Context, err error) error { ErrorHandler: func(context *echo.Context, err error) error {
return context.JSON(http.StatusForbidden, nil) return context.JSON(http.StatusForbidden, nil)
}, },
DenyHandler: func(context echo.Context, identifier string, err error) error { DenyHandler: func(context *echo.Context, identifier string, err error) error {
return context.JSON(http.StatusTooManyRequests, nil) return context.JSON(http.StatusTooManyRequests, nil)
}, },
} }

View File

@@ -2,10 +2,15 @@ package middleware
import ( import (
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session" "github.com/labstack/echo/v5"
"github.com/labstack/echo/v4"
) )
func SessionMiddleware() echo.MiddlewareFunc { func SessionMiddleware() echo.MiddlewareFunc {
return session.Middleware(sessions.NewCookieStore([]byte("secret"))) store := sessions.NewCookieStore([]byte("secret")) // TODO: 从配置中获取密钥
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Set("_session_store", store)
return next(c)
}
}
} }

33
backend/route.go Normal file
View File

@@ -0,0 +1,33 @@
package main
import (
"backend/internal/controllers"
"github.com/labstack/echo/v5"
)
type Route struct {
Method []string
Path string
Handler func(c *echo.Context) error
}
var routes = []Route{
{Method: []string{"POST"}, Path: "/file/create", Handler: controllers.CreateUploadTask},
{Method: []string{"POST"}, Path: "/file/slice", Handler: controllers.UploadFileSlice},
{Method: []string{"POST"}, Path: "/file/finish", Handler: controllers.FinishUploadTask},
{Method: []string{"GET"}, Path: "/share/:id", Handler: controllers.GetShareInfo},
{Method: []string{"POST"}, Path: "/share", Handler: controllers.CreateShareInfo},
{Method: []string{"GET"}, Path: "/download", Handler: controllers.DownloadShare},
{Method: []string{"POST"}, Path: "/download", Handler: controllers.VaildateShare},
{Method: []string{"GET"}, Path: "/share/pickup/:code", Handler: controllers.GetShareByPickupCode},
{Method: []string{"GET"}, Path: "/stat", Handler: controllers.GetStat},
{Method: []string{"GET"}, Path: "/config", Handler: controllers.GetConfig},
{Method: []string{"GET"}, Path: "/about", Handler: controllers.GetAbout},
{Method: []string{"POST"}, Path: "/task/:type", Handler: controllers.CreateTask},
{Method: []string{"GET"}, Path: "/task/:id", Handler: controllers.GetTask},
}

View File

@@ -0,0 +1,60 @@
package utils
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"backend/internal/utils"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestHTTPSuccessHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
data := map[string]interface{}{"result": "success"}
err := utils.HTTPSuccessHandler(c, data)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rec.Code)
var response map[string]interface{}
err = json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
expected := map[string]interface{}{
"code": float64(http.StatusOK),
"message": "success",
"data": data,
}
assert.Equal(t, expected, response)
}
func TestHTTPErrorHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := utils.HTTPErrorHandler(c, assert.AnError)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, rec.Code)
var response map[string]interface{}
err = json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
expected := map[string]interface{}{
"code": float64(http.StatusBadRequest),
"message": assert.AnError.Error(),
"data": map[string]interface{}{},
}
assert.Equal(t, expected, response)
}

View File

@@ -0,0 +1,74 @@
package utils
import (
"bytes"
"fmt"
"testing"
"backend/internal/utils"
u "pkg/utils"
"github.com/stretchr/testify/assert"
)
func TestGeneratePasswordHash(t *testing.T) {
tests := []struct {
name string
password string
salt string
expectError bool
err error
}{
{
name: "share.password_salt未配置",
password: "testpassword",
salt: "",
expectError: true,
err: utils.ErrPasswordSaltNotSet,
},
{
name: "正常生成哈希",
password: "testpassword123",
salt: "testsalt",
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 设置环境变量
u.InitTestViper(u.EnvOption{
ConfigData: bytes.NewBuffer([]byte(fmt.Sprintf(`
share:
password_salt: %s
`, tt.salt))),
})
u.SetEnv("share.password_salt", tt.salt)
hash, err := utils.GeneratePasswordHash(tt.password)
if tt.expectError {
if err == nil {
t.Errorf("期望错误,但得到了 nil")
return
}
if err != tt.err {
t.Errorf("期望错误信息 '%s',但得到了 '%s'", tt.err.Error(), err.Error())
}
return
}
if err != nil {
t.Errorf("不期望错误,但得到了: %v", err)
return
}
// 验证哈希格式argon2 32字节 = 64个十六进制字符
if len(hash) != 64 {
t.Errorf("期望哈希长度为64但得到了 %d", len(hash))
}
assert.Equal(t, hash, "537275f995fdd46eb2e5455b8a29adccb60c5637689d29646676a5f1bffb63f3")
})
}
}

66
config.example.yaml Normal file
View File

@@ -0,0 +1,66 @@
share:
# (必填)你的下载secret每一次下载次数减1的时候都会根据这里的secret生成一个下载jwt token 有效期一小时使用该下载token有效期内可以多线程下载该文件而不会被多次扣除次数
download_secret: your-secret-token
# 颁发的下载token的窗口期默认12小时文件过期后自动从服务器删除时间为此时间基础上加1小时默认为12+1=13小时
download_window: 12
# (必填)设置密码时会把密码加盐
password_salt: your-passwall-salt
upload:
# 上传文件保存路径
path: /upload
# 指定实例最大上传容量支持填写人类可读的值比如1TiB500GiB等注意填写GiB而不是GB, Gib按1024字节计算Gb按1000字节计算
maximum: 100GiB
redis:
# (必填)redis 地址
url: redis://redis:6379/0
# 实例功能配置
features:
file-share:
enabled: true
text-share:
enabled: true
file-image-compress:
enabled: true
file-image-convert:
enabled: true
# 站点基本信息
site:
# 必填,对应你的公网域名
url: http://localhost:5000
title:
'en': '015'
desc:
'en': '015 is an open-source temporary file sharing platform project that supports uploading, downloading, and sharing files and text.'
icon: '/logo.png'
bg_url: 'https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302'
# 关于页面的
about:
# hero图片 推荐3:1 比例
bg_url: 'https://files.mastodon.social/site_uploads/files/000/000/001/@1x/57c12f441d083cde.png'
# 关于信息markdown格式
content:
'zh': |
### markdown测试文案
这里有一个图片示例:
![示例图片](https://cdn.ani.work/site_uploads/files/000/000/005/@1x/d68677a8b7a8d296.png)
这里有一个[示例链接](https://fudaoyuan.icu)
'en': |
### Markdown Test Content
Here is an image example:
![Sample Image](https://cdn.ani.work/site_uploads/files/000/000/005/@1x/d68677a8b7a8d296.png)
Here is a [sample link](https://fudaoyuan.icu)
email: keven@fudaoyuan.icu
name: keven
url: 'https://fudaoyuan.icu'
avatar: ''

24
docker-compose.yml Normal file
View File

@@ -0,0 +1,24 @@
services:
app:
image: fudaoyuanicu/015-app:latest
container_name: 015-app
volumes:
- ./uploads:/uploads
- ./config.yaml:/app/config.yaml
ports:
- '8080:80'
depends_on:
- redis
worker:
image: fudaoyuanicu/015-worker:latest
container_name: worker
volumes:
- ./uploads:/uploads
- ./config.yaml:/config.yaml
depends_on:
- app
- redis
redis:
image: redis:7
container_name: redis

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 654 KiB

View File

@@ -1,19 +1,19 @@
<!-- app.vue --> <!-- app.vue -->
<script setup lang="ts"> <script setup lang="ts">
import { defineRule } from 'vee-validate'; import { defineRule } from 'vee-validate'
import { all } from '@vee-validate/rules'; import { all } from '@vee-validate/rules'
Object.entries(all).forEach(([name, rule]) => { Object.entries(all).forEach(([name, rule]) => {
defineRule(name, rule); defineRule(name, rule)
}); })
// @ts-check // @ts-check
const { $serwist } = useNuxtApp(); // const { $serwist } = useNuxtApp();
$serwist?.addEventListener("installed", () => { // $serwist?.addEventListener("installed", () => {
console.log("Serwist installed!"); // console.log("Serwist installed!");
}); // });
void $serwist?.register({ immediate: true }); // void $serwist?.register({ immediate: true });
</script> </script>
<template> <template>
<NuxtLayout> <NuxtLayout>
<NuxtPage /> <NuxtPage />
</NuxtLayout> </NuxtLayout>
</template> </template>

View File

@@ -41,6 +41,24 @@
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border); --color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring); --color-sidebar-ring: var(--sidebar-ring);
--animate-accordion-down: accordion-down 0.2s ease-out;
--animate-accordion-up: accordion-up 0.2s ease-out;
@keyframes accordion-down {
from {
height: 0;
}
to {
height: var(--reka-accordion-content-height);
}
}
@keyframes accordion-up {
from {
height: var(--reka-accordion-content-height);
}
to {
height: 0;
}
}
} }
:root { :root {

View File

@@ -0,0 +1,158 @@
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
import { Skeleton } from '@/components/ui/skeleton'
import getFileSize from '~/lib/getFileSize'
import useMyAppConfig from '@/composables/useMyAppConfig'
import { useFeatureMeta } from '@/composables/useFeatureMeta'
import Progress from '~/components/ui/progress/Progress.vue'
import renderI18n from '~/lib/renderI18n'
import { I18nT } from 'vue-i18n'
import { calcNativeHash } from '~/lib/calcFileHash'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/ui/accordion'
import MarkdownRender from '@/components/MarkdownRender.vue'
const { locale } = useI18n()
const appConfig = useMyAppConfig()
const featureMeta = useFeatureMeta()
const { data, isLoading } = useQuery({
queryKey: ['about'],
queryFn: async () => {
const data = await $fetch<{
data: {
file: {
maximun: number
current: number
}
bg_url?: string
avatar?: string
name?: string
email?: string
url?: string
content?: Record<string, string>
}
}>('/api/about')
return data?.data
},
})
const { t } = useI18n()
const { state: userAvatar } = useAsyncState(async () => {
if (!data?.value?.email) return null
const buffer = new TextEncoder().encode(data?.value?.email)
const hash = await calcNativeHash(buffer)
return `https://www.gravatar.com/avatar/${hash}?d=retro`
}, null)
</script>
<template>
<template v-if="isLoading">
<div class="flex flex-col gap-2">
<Skeleton class="aspect-[3/1] w-full rounded-xl" />
<div class="flex flex-col gap-2 items-center">
<Skeleton class="h-6 w-32 rounded" />
<Skeleton class="h-4 w-52 rounded" />
</div>
</div>
</template>
<template v-else>
<NuxtImg v-if="data?.bg_url" :src="data?.bg_url" class="aspect-[3/1] w-full rounded-xl object-cover" />
<div class="flex flex-col gap-2 items-center">
<div class="text-xl">{{ renderI18n(appConfig?.site_title ?? {}, 'en', locale) }}</div>
<div class="text-sm opacity-75 text-center px-5">
<I18nT keypath="page.about.powerBy" tag="span">
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
</I18nT>
</div>
</div>
</template>
<div class="font-semibold">{{ t('page.about.systemInfo') }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
</div>
</template>
<template v-else>
<div class="grid grid-cols-1 md:grid-cols-2 gap-2">
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
<div class="opacity-75 text-xs">{{ t('page.about.admin') }}</div>
<div
class="flex flex-row gap-2 items-center cursor-pointer"
@click="
() => {
if (data?.url) {
navigateTo(data?.url, { external: true })
return
}
if (data?.email) {
navigateTo(`mailto:${data?.email ?? ''}`, { external: true })
return
}
return
}
"
>
<Avatar class="size-10">
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || (userAvatar as string)" />
<AvatarFallback class="bg-black/10 font-bold">
{{ data?.name?.charAt(0)?.toUpperCase() }}
</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<div class="text-md font-semibold">{{ data?.name }}</div>
<div class="text-xs opacity-75">{{ data?.email }}</div>
</div>
</div>
</div>
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
<div class="opacity-75 text-xs">{{ t('page.about.storage') }}</div>
<div class="text-right flex flex-row items-baseline">
<span class="text-lg font-semibold">{{ getFileSize(data?.file?.current ?? 0) }}</span>
<span class="text-md opacity-75">/ {{ getFileSize(data?.file?.maximun ?? 0) }}</span>
</div>
<Progress class="h-1" :model-value="((data?.file?.current ?? 0) / (data?.file?.maximun ?? 0)) * 100" />
</div>
</div>
</template>
<template v-if="isLoading">
<Skeleton class="w-full h-24 rounded-xl" />
</template>
<template v-else>
<div class="rounded-xl bg-white/50 flex flex-col p-3 gap-3">
<div class="font-semibold">{{ t('page.about.enabledFeatures') }}</div>
<div v-if="featureMeta.length" class="flex flex-row flex-wrap gap-2">
<div
v-for="feature in featureMeta"
:key="feature.key"
class="flex flex-row items-center gap-2 rounded-full bg-black/5 px-2 py-1 text-sm font-medium"
>
<div class="flex size-6 items-center justify-center rounded-full text-black/80" :style="feature.style">
<component :is="feature.icon" class="size-3.5" />
</div>
<span>{{ feature.label }}</span>
</div>
</div>
<div v-else class="text-sm opacity-75">
{{ t('page.about.enabledFeaturesEmpty') }}
</div>
</div>
</template>
<template v-if="isLoading">
<Skeleton class="w-full h-16 rounded-xl" />
</template>
<template v-else>
<div v-if="data?.content" class="rounded-xl bg-white/50 flex flex-col px-3 gap-2">
<Accordion type="single" collapsible>
<AccordionItem value="about">
<AccordionTrigger>
<span class="font-semibold">{{ t('page.about.about') }}</span>
</AccordionTrigger>
<AccordionContent>
<MarkdownRender class="max-w-full" :markdown="renderI18n(data?.content ?? {}, 'en', locale) ?? ''" />
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</template>
</template>

View File

@@ -0,0 +1,232 @@
<script setup lang="ts">
import { cx } from 'class-variance-authority'
import { useQuery } from '@tanstack/vue-query'
import { Skeleton } from '@/components/ui/skeleton'
import dayjs from 'dayjs'
import { filesize } from 'filesize'
import { times } from 'lodash-es'
import type { ChartConfig } from '@/components/ui/chart'
import { VisArea, VisAxis, VisLine, VisXYContainer } from '@unovis/vue'
import { ChartContainer, ChartTooltip, ChartCrosshair, ChartLegendContent, componentToString, ChartTooltipContent } from '@/components/ui/chart'
interface StatChartData {
file_size: number
file_num: number
share_num: number
download_num: number
date: Date
}
interface QueueChartData {
processed: number
failed: number
date: Date
}
type ChartDataItem = StatChartData | QueueChartData
type AreaChartConfig = {
data: ChartDataItem[]
index: string
config: ChartConfig
}
const { data, isLoading } = useQuery({
queryKey: ['stat'],
queryFn: async () => {
const response = await $fetch<{
data: {
chart: {
storage: Record<string, StatChartData>
queue: Record<string, QueueChartData>
}
}
}>('/api/stat')
return response.data
},
})
const { t } = useI18n()
const chartTabs = computed(() => {
return [
{
label: t('page.about.file'),
value: 'storage',
total: data.value?.chart?.storage
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.file_num, 0)
: 0,
},
{
label: t('page.about.share'),
value: 'share',
total: data.value?.chart?.storage
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.share_num, 0)
: 0,
},
{
label: t('page.about.download'),
value: 'download',
total: data.value?.chart?.storage
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.download_num, 0)
: 0,
},
{
label: t('page.about.task'),
value: 'queue',
total: data.value?.chart?.queue
? Object.values(data.value.chart.queue).reduce((acc: number, curr: QueueChartData) => acc + curr.processed + curr.failed, 0)
: 0,
},
]
})
const currentChartTab = ref<'storage' | 'queue' | 'share' | 'download'>('storage')
const currentChartData = computed((): AreaChartConfig => {
const { storage, queue } = data.value?.chart || {}
if (currentChartTab.value === 'queue') {
const queueData = times(30, (i) => {
return {
date: dayjs().subtract(i, 'day').toDate(),
processed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.processed || 0,
failed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.failed || 0,
}
})
return {
data: queueData,
index: 'date' as const,
config: {
processed: { color: '#4ade80', label: t('page.about.processed') },
failed: { color: '#f87171', label: t('page.about.failed') },
},
}
}
const storageData = times(30, (i) => {
const base = { date: dayjs().subtract(i, 'day').toDate() }
if (currentChartTab.value === 'share') {
return {
...base,
share_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.share_num || 0,
}
}
if (currentChartTab.value === 'download') {
return {
...base,
download_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.download_num || 0,
}
}
return {
...base,
file_size: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.file_size || 0,
file_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.file_num || 0,
}
})
if (currentChartTab.value === 'share') {
return {
data: storageData as ChartDataItem[],
index: 'date' as const,
config: {
share_num: { color: '#ea580c', label: t('page.about.share') },
},
}
}
if (currentChartTab.value === 'download') {
return {
data: storageData as ChartDataItem[],
index: 'date' as const,
config: {
download_num: { color: '#a3e635', label: t('page.about.download') },
},
}
}
return {
data: storageData as ChartDataItem[],
index: 'date' as const,
config: {
file_size: { color: '#38bdf8', label: t('page.about.fileSize') },
file_num: { color: '#a78bfa', label: t('page.about.fileNum') },
},
}
})
</script>
<template>
<div class="font-semibold">{{ t('page.about.analysis') }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-96 rounded-xl" />
</div>
</template>
<template v-else>
<div class="flex flex-col gap-2 bg-white/50 w-full rounded-xl py-5">
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-5">
<div
:class="cx('rounded-md min-w-30 flex flex-col px-3 py-1.5 cursor-pointer', currentChartTab === tab.value && 'bg-black/10')"
v-for="tab in chartTabs"
:key="tab.value"
@click="
() => {
currentChartTab = tab.value as 'storage' | 'queue'
}
"
>
<div class="opacity-75 text-xs">{{ tab.label }}</div>
<div class="text-lg font-semibold">{{ tab.total }}</div>
</div>
</div>
<ChartContainer :config="currentChartData.config" class="h-64 w-full p-5" :cursor="false">
<VisXYContainer :data="currentChartData.data" :x-domain="[dayjs().toDate(), dayjs().subtract(29, 'day').toDate()]">
<VisArea
:key="currentChartTab"
:x="(d: ChartDataItem) => d.date"
:y="Object.keys(currentChartData.config).map((key) => (d: ChartDataItem) => d?.[key as keyof ChartDataItem])"
:color="Object.values(currentChartData.config).map((c) => c.color)"
:opacity="0.6"
/>
<VisLine
:key="currentChartTab"
:x="(d: ChartDataItem) => d.date"
:y="Object.keys(currentChartData.config).map((key) => (d: ChartDataItem) => d?.[key as keyof ChartDataItem])"
:color="Object.values(currentChartData.config).map((c) => c.color)"
:line-width="1"
/>
<VisAxis
:key="currentChartTab"
type="x"
:tick-line="false"
:domain-line="false"
:grid-line="false"
:num-ticks="6"
:tick-format="
(d: Date) => {
return dayjs(d).format('MMM')
}
"
:tick-values="currentChartData.data.map((d) => d.date)"
/>
<ChartTooltip />
<ChartCrosshair
:key="currentChartTab"
:template="
componentToString(currentChartData.config, ChartTooltipContent, {
class: 'w-[14rem]',
labelFormatter: (d) => {
return dayjs(d).format('MM-DD')
},
valueFormatter: (value, key) => {
if (key === 'file_size' && typeof value === 'number') {
return filesize(value)
}
return String(value)
},
})
"
:color="(d: any, i: number) => Object.values(currentChartData.config).map((c) => c.color as string)[i]"
/>
</VisXYContainer>
<ChartLegendContent />
</ChartContainer>
</div>
</template>
</template>

View File

@@ -0,0 +1,20 @@
<script setup lang="ts">
import useMyAppConfig from '@/composables/useMyAppConfig'
import dayjs from 'dayjs'
const appConfig = useMyAppConfig()
</script>
<template>
<div class="flex flex-row flex-wrap gap-4 items-center text-sm opacity-60">
<div class="flex flex-row gap-1 opacity-100">
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
{{ appConfig?.version ?? 'dev' }}
</div>
<div v-if="appConfig?.build_time">
{{ `Build at ${dayjs(appConfig?.build_time * 1000).format('YYYY-MM-DD')}` }}
</div>
<div>Designed by <NuxtLink href="https://fudaoyuan.icu" target="_blank" class="text-primary hover:underline">keven1024</NuxtLink></div>
</div>
</template>

View File

@@ -1,53 +0,0 @@
<script setup lang="ts">
import { filesize } from "filesize";
const props = defineProps<{
data: { name: string; value: string; color: string }[];
title: string;
}>();
const dataKeyMap = {
file_size: {
"zh-CN": "文件大小",
en: "File Size",
},
file_num: {
"zh-CN": "文件数量",
en: "File Num",
},
processed: {
"zh-CN": "处理数量",
en: "Processed",
},
failed: {
"zh-CN": "失败数量",
en: "Failed",
},
};
</script>
<template>
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
<div class="text-sm font-medium">{{ title }}</div>
<div v-for="(item, index) in data" :key="index">
<div class="flex flex-row items-center gap-2">
<div
class="h-5 w-2 rounded-full"
:style="{ backgroundColor: item.color ?? '#222' }"
></div>
<div class="text-xs font-medium">
{{
dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.["en"] ??
item.name
}}
</div>
<div class="text-sm">
{{
["file_size"]?.includes(item?.name)
? filesize(item.value)
: item.value
}}
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,30 @@
<script setup lang="ts">
import { Button } from '@/components/ui/button'
const props = defineProps<{
title?: string
showBackButton?: boolean
}>()
const router = useRouter()
</script>
<template>
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
<div v-if="title" class="flex flex-row justify-between">
<h1 class="text-xl font-normal">{{ title }}</h1>
<Button
v-if="!!showBackButton"
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
router.push('/')
}
"
>
<LucideHome class="size-4" />
</Button>
</div>
<slot />
</div>
</template>

View File

@@ -1,19 +1,21 @@
<script lang="ts" setup> <script lang="ts" setup>
import { VisSingleContainer, VisDonut } from '@unovis/vue' import { VisSingleContainer, VisDonut } from '@unovis/vue'
import { withDefaults, defineProps } from 'vue'
const props = withDefaults(defineProps<{ const props = withDefaults(
value?: number defineProps<{
size?: number value?: number
color?: string size?: number
}>(), { color?: string
value: 0, }>(),
size: 40, {
color: '#06b6d4' value: 0,
}) size: 40,
color: '#06b6d4',
}
)
const data = computed(() => { const data = computed(() => {
const progress = Math.min(Math.max(props.value, 0), 100) const progress = Math.min(Math.max(props.value, 0), 100)
return [progress, 100 - progress ] return [progress, 100 - progress]
}) })
const getValue = (d: number) => d const getValue = (d: number) => d
const getColor = (d: number, i: number) => [props?.color, 'transparent'][i] const getColor = (d: number, i: number) => [props?.color, 'transparent'][i]

View File

@@ -0,0 +1,32 @@
<script setup lang="ts">
import { Button } from '@/components/ui/button'
import asyncWait from '~/lib/asyncWait'
import { toast } from 'vue-sonner'
import { LucideCheck, LucideCopy } from '@lucide/vue'
const isCopy = ref(false)
const props = defineProps<{
value: string
}>()
const { copy } = useClipboard()
const { t } = useI18n()
</script>
<template>
<Button
variant="outline"
class="transition-all duration-300"
size="icon"
@click="
async () => {
await copy(props?.value)
isCopy = true
toast.success(t('common.copySuccess'))
await asyncWait(3000)
isCopy = false
}
"
>
<component :is="isCopy ? LucideCheck : LucideCopy" class="size-1/2" />
</Button>
</template>

View File

@@ -1,120 +1,93 @@
<script setup lang="ts"> <script setup lang="ts">
import { import showDrawer from '@/lib/showDrawer'
LucideShare, import FileShareHandle from '@/components/Preprocessing/FileShareHandle.vue'
LucideImage, import ImageConvertHandle from '@/components/Preprocessing/ImageConvertHandle.vue'
LucideBot, import { useFeatureMeta, type FeatureKey } from '@/composables/useFeatureMeta'
LucideLanguages, import type { FileShareHandleProps } from '../Preprocessing/types'
LucideFileText,
LucideImageMinus,
LucideArrowRightLeft,
LucideImagePlus,
LucideAudioLines,
LucideListMusic,
} from "lucide-vue-next";
import { cx } from "class-variance-authority";
import { isObject } from "lodash-es";
import showDrawer from "@/lib/showDrawer";
import FileShareHandle from "@/components/Preprocessing/FileShareHandle.vue";
const { t } = useI18n();
const props = defineProps<{ const props = defineProps<{
hide: () => void; hide: () => void
file: File; file: File[]
onFileHandle: ({ type, config }: { type: string; config: any }) => void; onFileHandle: (props: FileShareHandleProps) => void
}>(); }>()
const isImage = computed(() => props.file.type.startsWith("image/")); const isImage = computed(() => props.file.every((r) => r?.type?.startsWith('image/')))
const isVideo = computed(() => props.file.type.startsWith("video/"));
const isAudio = computed(() => props.file.type.startsWith("audio/"));
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value);
const isPDF = computed(() => props.file.type.startsWith("application/pdf")); const featureMeta = useFeatureMeta()
const isDOC = computed(() => props.file.type.startsWith("application/msword"));
const isXLS = computed(() => type ActionHandler = {
props.file.type.startsWith("application/vnd.ms-excel"), condition?: () => boolean
); onClick: () => void
const isPPT = computed(() => }
props.file.type.startsWith("application/vnd.ms-powerpoint"),
); const actionHandlers: Partial<Record<FeatureKey, ActionHandler>> = {
const isDocument = computed( 'file-share': {
() => isPDF.value || isDOC.value || isXLS.value || isPPT.value, onClick: () => showDrawer({ render: ({ hide }) => h(FileShareHandle, { ...props, hide }) }),
);
const actions = [
{
label: t("file.handleType.file-share"),
icon: LucideShare,
className: "bg-green-300",
onClick: () => {
showDrawer({
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
});
}, },
}, 'file-image-compress': {
isImage.value && { condition: () => isImage.value,
label: t("file.handleType.file-image-compress"), onClick: () => props.onFileHandle({ type: 'file-image-compress', config: {} }),
icon: LucideImageMinus,
className: "bg-red-300",
onClick: () => {
props.onFileHandle({ type: "file-image-compress", config: {} });
}, },
}, 'file-image-convert': {
// isImage.value && { condition: () => isImage.value,
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => { onClick: () => showDrawer({ render: ({ hide }) => h(ImageConvertHandle, { ...props, hide }) }),
// console.log('复制链接') },
// } // isImage.value && {
// }, // label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
// isImage.value && { // console.log('复制链接')
// label: '图片超分', icon: LucideImagePlus, className: 'bg-cyan-300', onClick: () => { // }
// console.log('复制链接') // },
// } // isImage.value && {
// }, // label: '图片超分', icon: LucideImagePlus, className: 'bg-cyan-300', onClick: () => {
// (isAudio.value || isVideo.value) && { // console.log('复制链接')
// label: '转文本', icon: LucideListMusic, className: 'bg-cyan-300', onClick: () => { // }
// console.log('复制链接') // },
// } // (isAudio.value || isVideo.value) && {
// }, // label: '转文本', icon: LucideListMusic, className: 'bg-cyan-300', onClick: () => {
// isAudio.value && { // console.log('复制链接')
// label: '语音克隆', icon: LucideAudioLines, className: 'bg-cyan-300', onClick: () => { // }
// console.log('复制链接') // },
// } // isAudio.value && {
// }, // label: '语音克隆', icon: LucideAudioLines, className: 'bg-cyan-300', onClick: () => {
// (isDocument.value || isMedia.value) && { // console.log('复制链接')
// label: '格式转换', icon: LucideArrowRightLeft, className: 'bg-purple-300', onClick: () => { // }
// console.log('复制链接') // },
// } // (isDocument.value || isMedia.value) && {
// }, // label: '格式转换', icon: LucideArrowRightLeft, className: 'bg-purple-300', onClick: () => {
]?.filter(isObject) as { // console.log('复制链接')
label: string; // }
icon: any; // },
className: string; }
onClick: () => void;
}[]; const actions = computed(() =>
featureMeta.value
.filter((meta) => {
const { key } = meta || {}
const handler = actionHandlers?.[key]
return handler && (!handler.condition || handler.condition())
})
.map((meta) => ({ ...meta, onClick: actionHandlers[meta.key]!.onClick }))
)
</script> </script>
<template> <template>
<div class="flex flex-col gap-5 p-5"> <div class="flex flex-col gap-5 p-5 overflow-x-auto">
<div class="flex flex-row gap-2"> <div class="flex flex-row gap-2">
<div <div
v-for="item in actions" v-for="item in actions"
:key="item.label" :key="item.key"
class="flex flex-col items-center gap-2 max-w-20" class="flex flex-col items-center gap-2 max-w-20"
@click=" @click="
() => { () => {
props?.hide(); props?.hide()
item?.onClick(); item?.onClick()
} }
" "
> >
<div <div class="size-14 flex justify-center items-center rounded-full mx-3" :style="item?.style">
:class=" <component :is="item?.icon" />
cx( </div>
'size-14 flex justify-center items-center rounded-full mx-3', <div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
item?.className, </div>
)
"
>
<component :is="item?.icon" />
</div> </div>
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
</div>
</div> </div>
</div>
</template> </template>

View File

@@ -1,41 +1,29 @@
<script setup lang="ts"> <script setup lang="ts">
import { cx } from "class-variance-authority"; import { cx } from 'class-variance-authority'
import type { Locale } from '@intlify/core-base'
const { availableLocales, setLocale, locale: currentLocale, t } = useI18n(); const props = defineProps<{
const route = useRoute(); hide: () => void
}>()
const localeMap = { const { locales, setLocale, locale: currentLocale, t } = useI18n()
"zh-CN": "简体中文",
en: "English",
// 'ja': '日本語',
// 'ko': '한국어',
// 'fr': 'Français',
// 'de': 'Deutsch',
};
const switchLocale = async (locale: string) => { const switchLocale = async (locale: Locale) => {
await setLocale(locale as keyof typeof localeMap); await setLocale(locale)
navigateTo(route.path, { props.hide()
external: true, }
});
};
</script> </script>
<template> <template>
<div class="flex flex-col gap-1 py-2"> <div class="flex flex-col gap-1 py-2">
<div class="text-xl font-bold mb-3">{{ t("i18n.switchLocale") }}</div> <div class="text-xl font-bold mb-3">{{ t('i18n.switchLocale') }}</div>
<div <div
v-for="locale in availableLocales" v-for="locale in locales"
:key="locale" :key="locale.code"
:class=" :class="cx('rounded-md hover:bg-black/10 p-2 cursor-pointer', currentLocale === locale.code && 'bg-black/10 font-bold')"
cx( @click="() => switchLocale(locale.code)"
'rounded-md hover:bg-black/10 p-2 cursor-pointer', >
currentLocale === locale && 'bg-black/10 font-bold', {{ locale.name }}
) </div>
"
@click="() => switchLocale(locale)"
>
{{ localeMap?.[locale as keyof typeof localeMap] }}
</div> </div>
</div>
</template> </template>

View File

@@ -4,6 +4,7 @@ import FormButton from '@/components/Field/FormButton.vue'
import InputField from '@/components/Field/InputField.vue' import InputField from '@/components/Field/InputField.vue'
import type { FormContext, GenericObject } from 'vee-validate' import type { FormContext, GenericObject } from 'vee-validate'
import { toast } from 'vue-sonner' import { toast } from 'vue-sonner'
const { t } = useI18n()
const props = defineProps<{ const props = defineProps<{
share_id: string share_id: string
hide: any hide: any
@@ -15,14 +16,14 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
const password = form.values.password const password = form.values.password
const token = await getShareToken(props.share_id, { password }) const token = await getShareToken(props.share_id, { password })
if (!token) { if (!token) {
toast.error('密码错误') toast.error(t('page.shareView.passwall.passwordError'))
form.resetForm() form.resetForm()
return return
} }
props?.hide(token) props?.hide(token)
return return
} catch (error) { } catch (error) {
toast.error('密码错误') toast.error(t('page.shareView.passwall.passwordError'))
form.resetForm() form.resetForm()
} }
} }
@@ -31,9 +32,9 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
<template> <template>
<VeeForm> <VeeForm>
<div class="flex flex-col gap-5"> <div class="flex flex-col gap-5">
<div class="text-xl font-bold">输入密码</div> <div class="text-xl font-bold">{{ t('page.shareView.passwall.title') }}</div>
<InputField name="password" type="password" rules="required" placeholder="请输入密码" /> <InputField name="password" type="password" rules="required" :placeholder="t('page.shareView.passwall.passwordPlaceholder')" />
<FormButton @click="handleSubmit">提交</FormButton> <FormButton @click="handleSubmit">{{ t('btn.submit') }}</FormButton>
</div> </div>
</VeeForm> </VeeForm>
</template> </template>

View File

@@ -1,57 +1,56 @@
<script setup lang="ts"> <script setup lang="ts">
import VeeForm from "@/components/VeeForm.vue"; import VeeForm from '@/components/VeeForm.vue'
import FormButton from "@/components/Field/FormButton.vue"; import FormButton from '@/components/Field/FormButton.vue'
import PinInputField from "@/components/Field/PinInputField.vue"; import PinInputField from '@/components/Field/PinInputField.vue'
import type { FormContext, GenericObject } from "vee-validate"; import type { FormContext, GenericObject } from 'vee-validate'
import { toast } from "vue-sonner"; import { toast } from 'vue-sonner'
const router = useRouter(); const router = useRouter()
const { t } = useI18n()
const props = defineProps<{ const props = defineProps<{
hide: () => void; hide: () => void
}>(); }>()
const handleSubmit = async ( const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) => {
form: FormContext<GenericObject, GenericObject>, try {
) => { const code = form.values.code
try { const data = await $fetch<{
const code = form.values.code; data: {
const data = await $fetch<{ share_id: string
data: { }
share_id: string; }>(`/api/share/pickup/${code}`)
}; if (!data.data.share_id) {
}>(`/api/share/pickup/${code}`); toast.error(t('page.upload.pickup.codeError'))
if (!data.data.share_id) { form.resetForm()
toast.error("取件码错误"); return
form.resetForm(); }
return; const { share_id } = data.data
props.hide()
router.push({
path: `/s/${share_id}`,
})
return
} catch (error) {
toast.error(t('page.upload.pickup.codeError'))
form.resetForm()
} }
const { share_id } = data.data; }
props.hide();
router.push({
path: `/s/${share_id}`,
});
return;
} catch (error) {
toast.error("取件码错误");
form.resetForm();
}
};
</script> </script>
<template> <template>
<VeeForm> <VeeForm>
<div class="flex flex-col gap-5"> <div class="flex flex-col gap-5">
<div class="text-xl font-bold">输入取件码</div> <div class="text-xl font-bold">{{ t('page.upload.pickup.title') }}</div>
<PinInputField <PinInputField
name="code" name="code"
:rules=" :rules="
(value) => { (value) => {
if (value?.length !== 4) { if (value?.length !== 4) {
return false; return false
} }
return true; return true
} }
" "
/> />
<FormButton @click="handleSubmit">提交</FormButton> <FormButton @click="handleSubmit">{{ t('btn.submit') }}</FormButton>
</div> </div>
</VeeForm> </VeeForm>
</template> </template>

View File

@@ -1,20 +1,21 @@
<script setup lang="ts"> <script setup lang="ts">
import QRCode from "qrcode"; import QRCode from 'qrcode'
const { t } = useI18n()
const props = defineProps<{ const props = defineProps<{
hide: () => void; hide: () => void
data: any; data: any
}>(); }>()
const { state } = useAsyncState(async () => { const { state } = useAsyncState(async () => {
return await QRCode.toDataURL(props.data); return await QRCode.toDataURL(props.data)
}, null); }, null)
</script> </script>
<template> <template>
<div class="flex flex-col gap-5"> <div class="flex flex-col gap-5">
<div class="text-xl font-bold">分享二维码</div> <div class="text-xl font-bold">{{ t('page.result.qrCode.title') }}</div>
<div class="flex flex-row justify-center"> <div class="flex flex-row justify-center">
<img :src="state" v-if="!!state" /> <img :src="state" v-if="!!state" />
<Skeleton class="size-20" v-else /> <Skeleton class="size-20" v-else />
</div>
</div> </div>
</div>
</template> </template>

View File

@@ -1,74 +1,77 @@
<script setup lang="ts"> <script setup lang="ts">
import { import showDrawer from '@/lib/showDrawer'
LucideShare, import TextShareHandle from '@/components/Preprocessing/TextShareHandle.vue'
LucideImage, import { useFeatureMeta, type FeatureKey } from '@/composables/useFeatureMeta'
LucideBot,
LucideLanguages,
} from "lucide-vue-next";
import { cx } from "class-variance-authority";
import showDrawer from "@/lib/showDrawer";
import TextShareHandle from "@/components/Preprocessing/TextShareHandle.vue";
const props = defineProps<{ const props = defineProps<{
hide: () => void; hide: () => void
text: string; text: string
onTextHandle: ({ type, config }: { type: string; config: any }) => void; onTextHandle: ({ type, config }: { type: string; config: any }) => void
}>(); }>()
const { t } = useI18n();
const actions = [ const featureMeta = useFeatureMeta()
{
label: t("text.handleType.text-share"), type ActionHandler = {
icon: LucideShare, condition?: () => boolean
className: "bg-green-300", onClick: () => void
onClick: () => { }
showDrawer({
render: ({ hide }) => h(TextShareHandle, { ...props, hide }), const actionHandlers: Partial<Record<FeatureKey, ActionHandler>> = {
}); 'text-share': {
onClick: () => showDrawer({ render: ({ hide }) => h(TextShareHandle, { ...props, hide }) }),
}, },
}, // 'text-translate': {
// { // onClick: () =>
// label: '生成配图', icon: LucideImage, className: 'bg-red-300', onClick: () => { // props.onTextHandle({
// console.log('复制链接') // type: 'text-translate',
// } // config: {
// }, // source: 'auto',
// { // },
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300', onClick: () => { // }),
// console.log('复制链接') // },
// } // 'text-image-generate': {
// }, // label: '生成配图', icon: LucideImage, className: 'bg-red-300',
// { // onClick: () => { console.log('复制链接') }
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => { // },
// console.log('复制链接') // 'text-ai-ask': {
// } // label: '问大模型', icon: LucideBot, className: 'bg-blue-300',
// }, // onClick: () => { console.log('复制链接') }
]; // },
// 'text-translate': {
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300',
// onClick: () => { console.log('复制链接') }
// },
}
const actions = computed(() =>
featureMeta.value
.filter((meta) => {
const { key } = meta || {}
const handler = actionHandlers?.[key]
return handler && (!handler.condition || handler.condition())
})
.map((meta) => ({ ...meta, onClick: actionHandlers[meta.key]!.onClick }))
)
</script> </script>
<template> <template>
<div class="flex flex-col gap-5 p-5"> <div class="flex flex-col gap-5 p-5 overflow-x-auto">
<div class="flex flex-row gap-2"> <div class="flex flex-row gap-2">
<div <div
v-for="item in actions" v-for="item in actions"
:key="item.label" :key="item.key"
class="flex flex-col items-center gap-2 max-w-20" class="flex flex-col items-center gap-2 max-w-20"
@click=" @click="
() => { () => {
props?.hide(); props?.hide()
item?.onClick(); item?.onClick()
} }
" "
> >
<div <div class="size-14 flex justify-center items-center rounded-full mx-3" :style="item?.style">
:class=" <component :is="item?.icon" />
cx( </div>
'size-14 flex justify-center items-center rounded-full mx-3', <div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
item?.className, </div>
)
"
>
<component :is="item?.icon" />
</div> </div>
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
</div>
</div> </div>
</div>
</template> </template>

View File

@@ -1,42 +1,80 @@
<script setup lang="ts"> <script setup lang="ts">
import FileUpload from "@/components/FileUpload.vue"; import FileUpload from '@/components/FileUpload.vue'
import { cx } from "class-variance-authority"; import { cx } from 'class-variance-authority'
import type { RuleExpression } from "vee-validate"; import type { RuleExpression } from 'vee-validate'
import Button from '../ui/button/Button.vue'
import { PlusIcon } from '@lucide/vue'
import { isEmpty } from 'lodash-es'
const props = defineProps<{ const props = defineProps<{
name: string; name: string
rules?: RuleExpression<File>; rules?: RuleExpression<File[]>
}>(); }>()
const { value, setValue } = useField<File>(props?.name, props?.rules); const { value, setValue } = useField<File[]>(props?.name, props?.rules)
const { t } = useI18n(); const { t } = useI18n()
const filterOutSameFile = (files: File[] | undefined, targetFile: File[] | undefined) => {
return files?.filter((file) => !targetFile?.some((r) => r?.name === file?.name && r?.type === file?.type && r?.size === file?.size)) || []
}
useEventListener(document, 'paste', (evt: ClipboardEvent) => {
const { files } = evt.clipboardData || {}
if (files?.length) {
setValue([...filterOutSameFile(value?.value, Array.from(files)), ...Array.from(files)])
}
})
</script> </script>
<template> <template>
<FileUpload <FileUpload
@onChange=" @onChange="
(file) => { (files) => {
setValue(file); // 这里没hash我们姑且认为name和size,type都一样的为同一个文件
} setValue([...filterOutSameFile(value, files), ...files])
" }
v-slot="{ isOverDropZone }" "
> v-slot="{ isOverDropZone }"
<div
:class="
cx(
'bg-white/50 rounded-md p-2 w-full h-40 flex flex-col items-center justify-center border border-dashed border-black/20 cursor-pointer text-gray-500 gap-3',
isOverDropZone && '!bg-green-100/50 ',
)
"
> >
<template v-if="!!value"> <div
<FilePreviewView :value="value" /> :class="
</template> cx(
<template v-else> 'bg-white/50 rounded-md p-2 w-full min-h-40 flex flex-col items-center justify-center border border-dashed border-black/20 cursor-pointer text-gray-500 gap-3 transition-all duration-300',
<LucideUpload class="size-10" /> isOverDropZone && '!bg-green-100/50 '
<div class="text-sm"> )
{{ t("file.uploadFilePlaceholder") }} "
>
<template v-if="!isEmpty(value)">
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-5 w-full">
<div v-for="item in value" :key="item?.name" class="flex flex-col items-center justify-center relative">
<div class="absolute top-0 right-0">
<Button
class="size-5 p-0 bg-red-500/20 hover:bg-red-500/60 text-red-500 hover:text-white"
@click="
(e: any) => {
e.stopPropagation()
setValue(filterOutSameFile(value, [item]))
}
"
>
<LucideX class="size-3" />
</Button>
</div>
<FilePreviewView :value="item" />
</div>
<div class="flex flex-col items-center justify-center opacity-50 gap-1">
<div class="size-16 flex justify-center items-center rounded-xl bg-white/80">
<PlusIcon class="size-7" />
</div>
<div class="mb-3">{{ t('page.upload.file.addMore') }}</div>
</div>
</div>
</template>
<template v-else>
<LucideUpload class="size-10" />
<div class="text-sm select-none">
{{ t('page.upload.file.uploadFilePlaceholder') }}
</div>
</template>
</div> </div>
</template> </FileUpload>
</div>
</FileUpload>
</template> </template>

View File

@@ -1,15 +1,20 @@
<template>
<Field :name="props.name" v-slot="{ field }">
<div class="flex flex-col gap-2">
<Label v-if="props.label">{{ props.label }}</Label>
<Input v-bind="{ ...field, ...$attrs }" />
</div>
</Field>
</template>
<script setup lang="ts"> <script setup lang="ts">
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import type { RuleExpression } from 'vee-validate'
const props = defineProps<{ const props = defineProps<{
name: string name: string
label?: string label?: string
rules?: RuleExpression<string>
}>() }>()
const { value, errorMessage } = useField<string>(props.name, props.rules)
</script> </script>
<template>
<div class="flex flex-col gap-2">
<Label v-if="props.label">{{ props.label }}</Label>
<Input v-model="value" :aria-invalid="!!errorMessage || undefined" v-bind="$attrs" />
</div>
</template>

View File

@@ -0,0 +1,37 @@
<script setup lang="ts">
import { Label } from '@/components/ui/label'
import type { RuleExpression } from 'vee-validate'
const props = defineProps<{
name: string
label?: string
rules?: RuleExpression<string[]>
}>()
const { t } = useI18n()
const { value, setValue, errorMessage } = useField<string[]>(props.name, props?.rules)
</script>
<template>
<div class="flex flex-col gap-2">
<Label v-if="label">{{ label }}</Label>
<div v-for="(item, index) in value" class="flex flex-row gap-2 items-center">
<Input
:model-value="item"
@update:model-value="(v: string | number) => setValue(value.map((o, i) => (i === index ? String(v) : o)))"
:aria-invalid="!!errorMessage || undefined"
v-bind="$attrs"
/>
<Button
variant="ghost"
size="icon"
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
@click="setValue(value.filter((_, i) => i !== index))"
>
<LucideTrash class="size-4" />
</Button>
</div>
<Button class="self-start" size="sm" @click="() => setValue([...(value || []), ''])">
<LucidePlus class="size-4" />
{{ t('common.add') }}
</Button>
</div>
</template>

View File

@@ -0,0 +1,102 @@
<script setup lang="ts">
import { Label } from '@/components/ui/label'
import { AutocompleteAnchor, AutocompleteContent, AutocompleteInput, AutocompleteItem, AutocompleteRoot, AutocompleteViewport } from 'reka-ui'
import type { Component } from 'vue'
import InputField from '../Field/InputField.vue'
type KvInputValueComponentConfig = [(key: string) => boolean, Component]
type KvInputConfig = {
key?: {
placeholder?: string
enum?: string[]
}
value?: {
placeholder?: string
component?: KvInputValueComponentConfig[]
default?: Component
}
}
const defaultConfig = {
key: {},
value: {
default: InputField,
},
} satisfies Required<KvInputConfig>
const props = defineProps<{
name: string
label?: string
config?: KvInputConfig
}>()
const { t } = useI18n()
const config = computed(() => {
return {
key: { ...defaultConfig.key, ...(props.config?.key ?? {}) },
value: { ...defaultConfig.value, ...(props.config?.value ?? {}) },
}
})
const { value, setValue } = useField<[string, string][]>(props.name)
const updateKey = (index: number, nextKey: string | number) => {
const next = [...(value.value ?? [])]
next[index] = [String(nextKey), next[index]?.[1] ?? '']
setValue(next)
}
</script>
<template>
<div class="flex flex-col gap-2">
<Label v-if="label">{{ label }}</Label>
<div v-for="([key, _], index) in value" class="flex flex-row gap-2 items-center">
<AutocompleteRoot class="basis-40 relative" :model-value="String(key ?? '')" @update:model-value="(v) => updateKey(index, v)">
<AutocompleteAnchor>
<AutocompleteInput
class="w-full placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
:placeholder="config.key.placeholder"
>
</AutocompleteInput>
</AutocompleteAnchor>
<AutocompleteContent
v-if="config.key?.enum"
class="bg-popover border rounded-md shadow-md z-50 w-(--reka-autocomplete-trigger-width) absolute inset-x-0"
>
<AutocompleteViewport class="p-1">
<AutocompleteItem
v-for="opt in config.key?.enum"
:key="opt"
:value="opt"
class="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-highlighted:bg-accent data-highlighted:text-accent-foreground"
>
{{ opt }}
</AutocompleteItem>
</AutocompleteViewport>
</AutocompleteContent>
</AutocompleteRoot>
<div class="flex-1">
<component
:is="config.value.component?.find(([isMatchCom]) => isMatchCom(key))?.[1] ?? config.value.default"
:name="`${props.name}[${index}][1]`"
:placeholder="config.value.placeholder"
class="w-full"
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
@click="() => setValue(value?.filter((_, i) => i !== index))"
>
<LucideTrash class="size-4" />
</Button>
</div>
<Button type="button" class="self-start" size="sm" @click="() => setValue([...(value ?? []), ['', '']])">
<LucidePlus class="size-4" />
{{ t('common.add') }}
</Button>
</div>
</template>

View File

@@ -3,11 +3,11 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import Tiptap from '@/components/Tiptap.vue' import Tiptap from '@/components/Tiptap/Index.vue'
import type { RuleExpression } from 'vee-validate' import type { RuleExpression } from 'vee-validate'
const props = defineProps<{ const props = defineProps<{
name: string name: string
rules?: RuleExpression<string> rules?: RuleExpression<string>
}>() }>()
const { value, } = useField<string>(props.name, props.rules) const { value } = useField<string>(props.name, props.rules)
</script> </script>

View File

@@ -1,13 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select'
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import type { RuleExpression } from 'vee-validate' import type { RuleExpression } from 'vee-validate'
type SelectValue = string | number type SelectValue = string | number
const props = defineProps<{ const props = defineProps<{
@@ -19,13 +11,14 @@ const props = defineProps<{
label?: string label?: string
value: SelectValue value: SelectValue
}[] }[]
class?: string
}>() }>()
const { value } = useField<SelectValue>(props.name, props?.rules) const { value } = useField<SelectValue>(props.name, props?.rules)
</script> </script>
<template> <template>
<Select v-model="value"> <Select v-model="value">
<SelectTrigger> <SelectTrigger :class="class">
<SelectValue :placeholder="placeholder" /> <SelectValue :placeholder="placeholder" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -37,4 +30,4 @@ const { value } = useField<SelectValue>(props.name, props?.rules)
</SelectGroup> </SelectGroup>
</SelectContent> </SelectContent>
</Select> </Select>
</template> </template>

View File

@@ -0,0 +1,25 @@
<script setup lang="ts">
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
const props = withDefaults(
defineProps<{
name: string
label?: string
placeholder?: string
rows?: number
}>(),
{
rows: 3,
}
)
const { value } = useField<string>(props.name)
</script>
<template>
<div class="flex flex-col gap-2">
<Label v-if="label">{{ label }}</Label>
<Textarea v-model="value" :placeholder="placeholder" :rows="rows" v-bind="$attrs" />
</div>
</template>

View File

@@ -1,61 +0,0 @@
<script setup lang="ts">
export type filePreview = {
type: string
name: string
size: number
}
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from 'lucide-vue-next'
const props = defineProps<{
file: File | filePreview
}>()
const imageUrl = computed(() => {
if (props?.file?.type?.startsWith('image/') && props?.file instanceof File) {
return URL.createObjectURL(props?.file)
}
return null
})
onUnmounted(() => {
if (imageUrl.value) {
URL.revokeObjectURL(imageUrl.value)
}
})
const fileIcon = computed(() => {
const [baseType, type] = props?.file?.type?.split('/')
if (baseType === 'video') {
return LucideFileVideo
}
if (baseType === 'audio') {
return LucideFileAudio
}
if (baseType === 'text' || ["json", "ld+json", "html"]?.includes(type)) {
return LucideFileCode
}
if (['pdf', 'msword',
'vnd.openxmlformats-officedocument.wordprocessingml.document',
'vnd.ms-excel',
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'vnd.ms-powerpoint',
'vnd.openxmlformats-officedocument.presentationml.presentation'].includes(type)) {
return LucideFileText
}
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type)) {
return LucideFileArchive
}
return LucideFile
})
</script>
<template>
<div v-if="!!imageUrl" class="flex max-w-30 max-h-20">
<div class="object-contain m-auto h-full">
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
</div>
</div>
<div v-if="!imageUrl" class="size-16 flex justify-center items-center rounded-xl bg-white/80">
<component :is="fileIcon" class="size-10" />
</div>
</template>

View File

@@ -0,0 +1,41 @@
<script setup lang="ts">
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from '@lucide/vue'
import type { filePreview } from './Index.vue'
const props = defineProps<{
file: File | filePreview
}>()
const fileIcon = computed(() => {
const [baseType, type] = props?.file?.type?.split('/')
// if (baseType === 'video') {
// return LucideFileVideo
// }
if (baseType === 'audio') {
return LucideFileAudio
}
if (baseType === 'text' || ['json', 'ld+json', 'html']?.includes(type ?? '')) {
return LucideFileCode
}
if (
[
'pdf',
'msword',
'vnd.openxmlformats-officedocument.wordprocessingml.document',
'vnd.ms-excel',
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'vnd.ms-powerpoint',
'vnd.openxmlformats-officedocument.presentationml.presentation',
].includes(type ?? '')
) {
return LucideFileText
}
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type ?? '')) {
return LucideFileArchive
}
return LucideFile
})
</script>
<template>
<component :is="fileIcon" />
</template>

View File

@@ -0,0 +1,29 @@
<script setup lang="ts">
import { isHeic, heicTo } from 'heic-to'
const props = defineProps<{
file: File
}>()
const { state: imageUrl } = useAsyncState(async () => {
let blob: Blob = props?.file
if (await isHeic(props?.file)) {
blob = await heicTo({
blob: props?.file,
type: 'image/jpeg',
quality: 1,
})
}
return URL.createObjectURL(blob)
}, null)
onUnmounted(() => {
if (imageUrl.value) {
URL.revokeObjectURL(imageUrl.value)
}
})
</script>
<template>
<img v-if="!!imageUrl" :src="imageUrl" />
</template>

View File

@@ -0,0 +1,61 @@
<script setup lang="ts">
import { cx } from 'class-variance-authority'
import FileIcon from './File.vue'
import ImageIcon from './Image.vue'
import VideoIcon from './Video.vue'
import { fileTypeFromBuffer } from 'file-type'
export type filePreview = {
type: string
name: string
size: number
}
const props = withDefaults(
defineProps<{
file: File | filePreview
class?: string
size?: 'sm' | 'md' | 'lg'
}>(),
{
size: 'md',
}
)
const isFile = computed(() => props?.file instanceof File)
const { state: fileType } = useAsyncState(async () => {
if (!isFile.value) {
return null
}
if (!!props?.file?.type) {
return props?.file?.type
}
const { mime } = (await fileTypeFromBuffer(await (props?.file as File)?.arrayBuffer())) || {}
return mime
}, null)
const isImage = computed(() => isFile.value && fileType.value?.startsWith('image/'))
const isVideo = computed(() => isFile.value && fileType.value?.startsWith('video/'))
</script>
<template>
<div v-if="isImage || isVideo" :class="cx('flex overflow-hidden', size === 'sm' && 'max-w-20 max-h-16', size === 'md' && 'max-w-30 max-h-20')">
<component
:is="isImage ? ImageIcon : VideoIcon"
:file="props?.file as File"
class="block max-w-full max-h-full object-contain border border-black/20 rounded"
/>
</div>
<div
v-else
:class="
cx(
'flex justify-center items-center bg-white/80',
size === 'sm' && 'size-7 rounded-md',
size === 'md' && 'size-16 rounded-xl',
props?.class
)
"
>
<component :is="FileIcon" :file="props?.file" class="size-[62.5%]" />
</div>
</template>

View File

@@ -0,0 +1,27 @@
<script setup lang="ts">
import getVideoFileThumbnail from '@/lib/getVideoFileThumbnail'
const props = defineProps<{
file: File
}>()
const { state: thumbnailUrl } = useAsyncState(async () => {
if (props.file.type.startsWith('video/')) {
return await getVideoFileThumbnail(props.file)
}
return null
}, null)
onUnmounted(() => {
if (!!thumbnailUrl.value) {
URL.revokeObjectURL(thumbnailUrl.value)
}
})
</script>
<template>
<div v-if="thumbnailUrl" class="relative grayscale-50 overflow-hidden">
<img :src="thumbnailUrl" class="object-contain block max-w-full max-h-full" />
<LucidePlay class="size-[40%] absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white" />
</div>
</template>

Some files were not shown because too many files have changed in this diff Show More