@omnizap-system/omnizap 2.5.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.clusterfuzzlite/Dockerfile +10 -0
- package/.env.example +907 -0
- package/.github/codeql/codeql-config.yml +10 -0
- package/.github/dependabot.yml +35 -0
- package/.github/workflows/ci.yml +73 -0
- package/.github/workflows/codeql.yml +106 -0
- package/.github/workflows/db-migration-check.yml +98 -0
- package/.github/workflows/dependency-review.yml +22 -0
- package/.github/workflows/deploy.yml +95 -0
- package/.github/workflows/release.yml +106 -0
- package/.github/workflows/security-attest-provenance.yml +51 -0
- package/.github/workflows/security-gitleaks.yml +34 -0
- package/.github/workflows/security-runner-hardening.yml +31 -0
- package/.github/workflows/security-scorecard.yml +44 -0
- package/.github/workflows/security-zap-baseline.yml +44 -0
- package/.github/workflows/security-zap-full-scan.yml +43 -0
- package/.github/workflows/security-zizmor.yml +36 -0
- package/.github/workflows/wiki-sync.yml +44 -0
- package/.gitleaks.toml +15 -0
- package/.prettierrc +34 -0
- package/CODE_OF_CONDUCT.md +114 -0
- package/LICENSE +56 -0
- package/README.md +110 -0
- package/SECURITY.md +110 -0
- package/app/config/index.js +4 -0
- package/app/configParts/adminIdentity.js +92 -0
- package/app/configParts/baileysConfig.js +1818 -0
- package/app/configParts/groupUtils.js +692 -0
- package/app/configParts/loggerConfig.js +394 -0
- package/app/configParts/messagePersistenceService.js +305 -0
- package/app/connection/baileysCompatibility.test.js +40 -0
- package/app/connection/baileysDbAuthState.js +344 -0
- package/app/connection/socketController.js +2243 -0
- package/app/controllers/messageController.js +7 -0
- package/app/controllers/messagePipeline/commandMiddleware.js +146 -0
- package/app/controllers/messagePipeline/conversationMiddleware.js +183 -0
- package/app/controllers/messagePipeline/messagePipelineMiddlewares.test.js +522 -0
- package/app/controllers/messagePipeline/postProcessingMiddleware.js +41 -0
- package/app/controllers/messagePipeline/preProcessingMiddlewares.js +166 -0
- package/app/controllers/messageProcessingPipeline.js +699 -0
- package/app/modules/adminModule/AGENT.md +4056 -0
- package/app/modules/adminModule/adminAiHelpService.js +56 -0
- package/app/modules/adminModule/adminConfigRuntime.js +177 -0
- package/app/modules/adminModule/commandConfig.json +7122 -0
- package/app/modules/adminModule/groupCommandHandlers.js +1823 -0
- package/app/modules/adminModule/groupCommandHandlers.test.js +350 -0
- package/app/modules/adminModule/groupEventHandlers.js +399 -0
- package/app/modules/aiModule/AGENT.md +547 -0
- package/app/modules/aiModule/aiAiHelpService.js +14 -0
- package/app/modules/aiModule/aiConfigRuntime.js +135 -0
- package/app/modules/aiModule/catCommand.js +967 -0
- package/app/modules/aiModule/commandConfig.json +981 -0
- package/app/modules/analyticsModule/messageAnalysisEventRepository.js +83 -0
- package/app/modules/gameModule/AGENT.md +196 -0
- package/app/modules/gameModule/commandConfig.json +366 -0
- package/app/modules/gameModule/diceCommand.js +42 -0
- package/app/modules/gameModule/gameAiHelpService.js +14 -0
- package/app/modules/gameModule/gameConfigRuntime.js +68 -0
- package/app/modules/menuModule/AGENT.md +205 -0
- package/app/modules/menuModule/commandConfig.json +366 -0
- package/app/modules/menuModule/common.js +316 -0
- package/app/modules/menuModule/menuAiHelpService.js +14 -0
- package/app/modules/menuModule/menuConfigRuntime.js +68 -0
- package/app/modules/menuModule/menus.js +66 -0
- package/app/modules/playModule/AGENT.md +321 -0
- package/app/modules/playModule/commandConfig.json +584 -0
- package/app/modules/playModule/playAiHelpService.js +14 -0
- package/app/modules/playModule/playCommand.js +1417 -0
- package/app/modules/playModule/playConfigRuntime.js +68 -0
- package/app/modules/quoteModule/AGENT.md +199 -0
- package/app/modules/quoteModule/commandConfig.json +366 -0
- package/app/modules/quoteModule/quoteAiHelpService.js +14 -0
- package/app/modules/quoteModule/quoteCommand.js +842 -0
- package/app/modules/quoteModule/quoteConfigRuntime.js +68 -0
- package/app/modules/rpgPokemonModule/AGENT.md +229 -0
- package/app/modules/rpgPokemonModule/commandConfig.json +386 -0
- package/app/modules/rpgPokemonModule/rpgBattleCanvasRenderer.js +795 -0
- package/app/modules/rpgPokemonModule/rpgBattleService.js +2110 -0
- package/app/modules/rpgPokemonModule/rpgBattleService.test.js +770 -0
- package/app/modules/rpgPokemonModule/rpgEvolutionUtils.js +22 -0
- package/app/modules/rpgPokemonModule/rpgPokemonAiHelpService.js +14 -0
- package/app/modules/rpgPokemonModule/rpgPokemonCommand.js +174 -0
- package/app/modules/rpgPokemonModule/rpgPokemonConfigRuntime.js +68 -0
- package/app/modules/rpgPokemonModule/rpgPokemonDomain.js +192 -0
- package/app/modules/rpgPokemonModule/rpgPokemonDomain.test.js +93 -0
- package/app/modules/rpgPokemonModule/rpgPokemonEvolution.test.js +46 -0
- package/app/modules/rpgPokemonModule/rpgPokemonMessages.js +746 -0
- package/app/modules/rpgPokemonModule/rpgPokemonRepository.js +1847 -0
- package/app/modules/rpgPokemonModule/rpgPokemonService.js +6839 -0
- package/app/modules/rpgPokemonModule/rpgProfileCanvasRenderer.js +354 -0
- package/app/modules/statsModule/AGENT.md +320 -0
- package/app/modules/statsModule/commandConfig.json +540 -0
- package/app/modules/statsModule/globalRankingCommand.js +64 -0
- package/app/modules/statsModule/rankingCommand.js +41 -0
- package/app/modules/statsModule/rankingCommon.js +1305 -0
- package/app/modules/statsModule/statsAiHelpService.js +14 -0
- package/app/modules/statsModule/statsConfigRuntime.js +68 -0
- package/app/modules/stickerModule/AGENT.md +692 -0
- package/app/modules/stickerModule/addStickerMetadata.js +239 -0
- package/app/modules/stickerModule/commandConfig.json +1216 -0
- package/app/modules/stickerModule/convertToWebp.js +367 -0
- package/app/modules/stickerModule/stickerAiHelpService.js +14 -0
- package/app/modules/stickerModule/stickerCommand.js +446 -0
- package/app/modules/stickerModule/stickerConfigRuntime.js +68 -0
- package/app/modules/stickerModule/stickerConvertCommand.js +159 -0
- package/app/modules/stickerModule/stickerTextCommand.js +653 -0
- package/app/modules/stickerPackModule/AGENT.md +215 -0
- package/app/modules/stickerPackModule/autoPackCollectorRuntime.js +20 -0
- package/app/modules/stickerPackModule/autoPackCollectorService.js +357 -0
- package/app/modules/stickerPackModule/commandConfig.json +387 -0
- package/app/modules/stickerPackModule/domainEventOutboxRepository.js +227 -0
- package/app/modules/stickerPackModule/domainEvents.js +52 -0
- package/app/modules/stickerPackModule/semanticReclassificationEngine.js +429 -0
- package/app/modules/stickerPackModule/semanticReclassificationEngine.test.js +75 -0
- package/app/modules/stickerPackModule/semanticThemeClusterService.js +544 -0
- package/app/modules/stickerPackModule/stickerAssetClassificationRepository.js +400 -0
- package/app/modules/stickerPackModule/stickerAssetRepository.js +400 -0
- package/app/modules/stickerPackModule/stickerAssetReprocessQueueRepository.js +175 -0
- package/app/modules/stickerPackModule/stickerAutoPackByTagsRuntime.js +3702 -0
- package/app/modules/stickerPackModule/stickerClassificationBackgroundRuntime.js +559 -0
- package/app/modules/stickerPackModule/stickerClassificationService.js +557 -0
- package/app/modules/stickerPackModule/stickerDedicatedTaskWorkerRuntime.js +249 -0
- package/app/modules/stickerPackModule/stickerDomainEventBus.js +65 -0
- package/app/modules/stickerPackModule/stickerDomainEventConsumerRuntime.js +208 -0
- package/app/modules/stickerPackModule/stickerMarketplaceDriftService.js +99 -0
- package/app/modules/stickerPackModule/stickerObjectStorageService.js +285 -0
- package/app/modules/stickerPackModule/stickerPackAiHelpService.js +14 -0
- package/app/modules/stickerPackModule/stickerPackCommandHandlers.js +1148 -0
- package/app/modules/stickerPackModule/stickerPackConfigRuntime.js +68 -0
- package/app/modules/stickerPackModule/stickerPackEngagementRepository.js +152 -0
- package/app/modules/stickerPackModule/stickerPackErrors.js +30 -0
- package/app/modules/stickerPackModule/stickerPackInteractionEventRepository.js +101 -0
- package/app/modules/stickerPackModule/stickerPackItemRepository.js +432 -0
- package/app/modules/stickerPackModule/stickerPackMarketplaceService.js +313 -0
- package/app/modules/stickerPackModule/stickerPackMessageService.js +268 -0
- package/app/modules/stickerPackModule/stickerPackRepository.js +450 -0
- package/app/modules/stickerPackModule/stickerPackScoreSnapshotRepository.js +179 -0
- package/app/modules/stickerPackModule/stickerPackScoreSnapshotRuntime.js +271 -0
- package/app/modules/stickerPackModule/stickerPackService.js +733 -0
- package/app/modules/stickerPackModule/stickerPackServiceRuntime.js +32 -0
- package/app/modules/stickerPackModule/stickerPackUtils.js +107 -0
- package/app/modules/stickerPackModule/stickerStorageService.js +559 -0
- package/app/modules/stickerPackModule/stickerWorkerPipelineRuntime.js +242 -0
- package/app/modules/stickerPackModule/stickerWorkerTaskQueueRepository.js +242 -0
- package/app/modules/systemMetricsModule/AGENT.md +193 -0
- package/app/modules/systemMetricsModule/commandConfig.json +344 -0
- package/app/modules/systemMetricsModule/pingCommand.js +399 -0
- package/app/modules/systemMetricsModule/systemMetricsAiHelpService.js +14 -0
- package/app/modules/systemMetricsModule/systemMetricsConfigRuntime.js +68 -0
- package/app/modules/tiktokModule/AGENT.md +196 -0
- package/app/modules/tiktokModule/commandConfig.json +366 -0
- package/app/modules/tiktokModule/tiktokAiHelpService.js +14 -0
- package/app/modules/tiktokModule/tiktokCommand.js +716 -0
- package/app/modules/tiktokModule/tiktokConfigRuntime.js +68 -0
- package/app/modules/userModule/AGENT.md +200 -0
- package/app/modules/userModule/commandConfig.json +386 -0
- package/app/modules/userModule/userAiHelpService.js +14 -0
- package/app/modules/userModule/userCommand.js +1155 -0
- package/app/modules/userModule/userConfigRuntime.js +68 -0
- package/app/modules/waifuPicsModule/AGENT.md +431 -0
- package/app/modules/waifuPicsModule/commandConfig.json +780 -0
- package/app/modules/waifuPicsModule/waifuPicsAiHelpService.js +14 -0
- package/app/modules/waifuPicsModule/waifuPicsCommand.js +586 -0
- package/app/modules/waifuPicsModule/waifuPicsConfigRuntime.js +68 -0
- package/app/observability/metrics.js +766 -0
- package/app/services/ai/aiHelpResponseCacheRepository.js +280 -0
- package/app/services/ai/aiLearningRepository.js +400 -0
- package/app/services/ai/commandConfigEnrichmentRepository.js +769 -0
- package/app/services/ai/commandConfigEnrichmentService.js +452 -0
- package/app/services/ai/commandConfigValidationService.js +443 -0
- package/app/services/ai/commandToolBuilderService.js +192 -0
- package/app/services/ai/conversationRouterService.js +516 -0
- package/app/services/ai/geminiService.js +115 -0
- package/app/services/ai/geminiService.test.js +87 -0
- package/app/services/ai/globalModuleAiHelpService.js +1412 -0
- package/app/services/ai/globalToolCallingService.js +203 -0
- package/app/services/ai/messageCommandExecutionService.js +391 -0
- package/app/services/ai/moduleAiHelpCoreService.js +1099 -0
- package/app/services/ai/moduleAiHelpWrapperFactory.js +65 -0
- package/app/services/ai/moduleCommandConfigRuntimeService.js +113 -0
- package/app/services/ai/moduleToolExecutorService.js +464 -0
- package/app/services/ai/moduleToolRegistryService.js +178 -0
- package/app/services/ai/toolCandidateSelectorService.js +781 -0
- package/app/services/auth/googleWebLinkService.js +80 -0
- package/app/services/auth/whatsappLoginLinkService.js +230 -0
- package/app/services/external/pokeApiService.js +398 -0
- package/app/services/group/groupMetadataService.js +311 -0
- package/app/services/infra/dbWriteQueue.js +874 -0
- package/app/services/infra/featureFlagService.js +131 -0
- package/app/services/infra/queueUtils.js +55 -0
- package/app/services/messaging/captchaService.js +491 -0
- package/app/services/messaging/messagePersistenceService.js +1 -0
- package/app/services/messaging/newsBroadcastService.js +347 -0
- package/app/services/sticker/stickerFocusService.js +347 -0
- package/app/services/sticker/stickerFocusService.test.js +43 -0
- package/app/store/aiPromptStore.js +38 -0
- package/app/store/conversationSessionStore.js +131 -0
- package/app/store/groupConfigStore.js +58 -0
- package/app/store/premiumUserStore.js +54 -0
- package/app/utils/antiLink/antiLinkModule.js +700 -0
- package/app/utils/http/getImageBufferModule.js +18 -0
- package/app/utils/json/jsonSanitizer.js +113 -0
- package/app/utils/json/jsonSanitizer.test.js +40 -0
- package/app/utils/systemMetrics/systemMetricsModule.js +88 -0
- package/app/workers/aiLearningWorker.js +605 -0
- package/app/workers/commandConfigEnrichmentWorker.js +242 -0
- package/database/index.js +2075 -0
- package/database/init.js +151 -0
- package/database/migrations/.gitkeep +0 -0
- package/database/migrations/20260307_d0_hardening_down.sql +64 -0
- package/database/migrations/20260307_d0_hardening_up.sql +79 -0
- package/database/migrations/20260307_d1_terms_acceptance_down.sql +11 -0
- package/database/migrations/20260307_d1_terms_acceptance_up.sql +37 -0
- package/database/migrations/20260307_d2_auth_hardening_down.sql +75 -0
- package/database/migrations/20260307_d2_auth_hardening_up.sql +100 -0
- package/database/migrations/20260314_d7_canonical_sender_down.sql +53 -0
- package/database/migrations/20260314_d7_canonical_sender_up.sql +114 -0
- package/database/migrations/20260406_d30_security_analytics_down.sql +95 -0
- package/database/migrations/20260406_d30_security_analytics_up.sql +292 -0
- package/database/migrations/20260407_d31_web_google_session_token_hardening_down.sql +2 -0
- package/database/migrations/20260407_d31_web_google_session_token_hardening_up.sql +17 -0
- package/database/migrations/20260408_d32_ai_help_response_cache_down.sql +1 -0
- package/database/migrations/20260408_d32_ai_help_response_cache_up.sql +22 -0
- package/database/migrations/20260409_d33_ai_learning_tables_down.sql +4 -0
- package/database/migrations/20260409_d33_ai_learning_tables_up.sql +52 -0
- package/database/migrations/20260410_d34_command_config_enrichment_down.sql +3 -0
- package/database/migrations/20260410_d34_command_config_enrichment_up.sql +48 -0
- package/database/schema.sql +1186 -0
- package/docker-compose.yml +104 -0
- package/docs/audits/stickerCatalogController-out-of-scope.md +103 -0
- package/docs/audits/stickerCatalogController-symbols.md +58 -0
- package/docs/compliance/acceptable-use-policy-2026-03-07.md +35 -0
- package/docs/compliance/dpa-b2b-standard-2026-03-07.md +80 -0
- package/docs/compliance/monthly-compliance-checklist-2026-03-07.md +88 -0
- package/docs/compliance/notice-and-takedown-policy-2026-03-07.md +34 -0
- package/docs/compliance/privacy-policy-2026-03-07.md +75 -0
- package/docs/compliance/subprocessors-inventory-2026-03-07.md +16 -0
- package/docs/database/production-db-evolution-runbook-2026q1.md +365 -0
- package/docs/security/dsar-lgpd-runbook-2026-03-07.md +86 -0
- package/docs/security/incident-response-lgpd-anpd-runbook-2026-03-07.md +77 -0
- package/docs/security/network-hardening-runbook-2026-03-07.md +137 -0
- package/docs/seo/omnizap-seo-playbook-br-2026-02-28.md +238 -0
- package/docs/seo/satellite-page-template.md +116 -0
- package/docs/seo/satellite-pages-phase1.json +364 -0
- package/docs/wiki/Home.md +120 -0
- package/docs/wiki/pair-extraordinaire-2026-03-08.md +3 -0
- package/docs/wiki/recent-changes-2026-03-08.md +47 -0
- package/ecosystem.prod.config.cjs +135 -0
- package/eslint.config.js +89 -0
- package/index.js +488 -0
- package/ml/clip_classifier/Dockerfile +18 -0
- package/ml/clip_classifier/README.md +118 -0
- package/ml/clip_classifier/adaptive_scoring.py +40 -0
- package/ml/clip_classifier/classifier.py +654 -0
- package/ml/clip_classifier/embedding_store.py +481 -0
- package/ml/clip_classifier/env_loader.py +15 -0
- package/ml/clip_classifier/llm_label_expander.py +144 -0
- package/ml/clip_classifier/main.py +213 -0
- package/ml/clip_classifier/requirements.txt +10 -0
- package/ml/clip_classifier/similarity_engine.py +74 -0
- package/new-logo.png +0 -0
- package/observability/alert-rules.yml +60 -0
- package/observability/grafana/dashboards/omnizap-mysql.json +136 -0
- package/observability/grafana/dashboards/omnizap-overview.json +170 -0
- package/observability/grafana/provisioning/dashboards/dashboards.yml +11 -0
- package/observability/grafana/provisioning/datasources/datasources.yml +15 -0
- package/observability/loki-config.yml +38 -0
- package/observability/mysql-setup.sql +46 -0
- package/observability/prometheus.yml +35 -0
- package/observability/promtail-config.yml +84 -0
- package/observability/sticker-catalog-slo.md +83 -0
- package/observability/sticker-scale-hardening-rollout.md +128 -0
- package/package.json +144 -0
- package/public/apple-touch-icon.png +0 -0
- package/public/assets/css/commands-react.input.css +71 -0
- package/public/assets/css/create-pack-react.input.css +31 -0
- package/public/assets/css/home-react.input.css +106 -0
- package/public/assets/css/login-react.input.css +58 -0
- package/public/assets/css/stickers-react.input.css +18 -0
- package/public/assets/css/terms-react.input.css +115 -0
- package/public/assets/css/user-react.input.css +57 -0
- package/public/assets/images/brand-icon-192.png +0 -0
- package/public/assets/images/brand-logo-128.webp +0 -0
- package/public/assets/images/hero-banner-1280.jpg +0 -0
- package/public/comandos/commands-catalog.json +4517 -0
- package/public/css/api-docs.css +161 -0
- package/public/css/stickers-admin.css +1288 -0
- package/public/css/styles.css +679 -0
- package/public/css/systemadm/admin.css +474 -0
- package/public/css/systemadm/base.css +73 -0
- package/public/css/systemadm/components.css +662 -0
- package/public/css/systemadm/layout.css +229 -0
- package/public/css/systemadm/tokens.css +56 -0
- package/public/favicon-16x16.png +0 -0
- package/public/favicon-32x32.png +0 -0
- package/public/favicon.ico +0 -0
- package/public/js/apps/apiDocsApp.js +235 -0
- package/public/js/apps/commandsReactApp.js +528 -0
- package/public/js/apps/createPackApp.js +1646 -0
- package/public/js/apps/homeReactApp.js +942 -0
- package/public/js/apps/loginReactApp.js +496 -0
- package/public/js/apps/stickersAdminApp.js +1753 -0
- package/public/js/apps/stickersApp.js +3797 -0
- package/public/js/apps/termsReactApp.js +528 -0
- package/public/js/apps/userApp.js +2540 -0
- package/public/js/apps/userProfile/actions.js +66 -0
- package/public/js/apps/userReactApp.js +547 -0
- package/public/js/catalog.js +950 -0
- package/public/pages/api-docs.html +40 -0
- package/public/pages/aup.html +158 -0
- package/public/pages/comandos.html +41 -0
- package/public/pages/dpa.html +227 -0
- package/public/pages/home.html +45 -0
- package/public/pages/licenca.html +182 -0
- package/public/pages/login.html +40 -0
- package/public/pages/notice-and-takedown.html +234 -0
- package/public/pages/politica-de-privacidade.html +251 -0
- package/public/pages/seo-bot-whatsapp-para-grupo.html +350 -0
- package/public/pages/seo-bot-whatsapp-sem-programar.html +350 -0
- package/public/pages/seo-como-automatizar-avisos-no-whatsapp.html +350 -0
- package/public/pages/seo-como-criar-comandos-whatsapp.html +350 -0
- package/public/pages/seo-como-evitar-spam-no-whatsapp.html +350 -0
- package/public/pages/seo-como-moderar-grupo-whatsapp.html +350 -0
- package/public/pages/seo-como-organizar-comunidade-whatsapp.html +350 -0
- package/public/pages/seo-melhor-bot-whatsapp-para-grupos.html +350 -0
- package/public/pages/stickers-admin.html +31 -0
- package/public/pages/stickers-create.html +41 -0
- package/public/pages/stickers.html +45 -0
- package/public/pages/suboperadores.html +237 -0
- package/public/pages/termos-de-uso-texto-integral.html +241 -0
- package/public/pages/termos-de-uso.html +41 -0
- package/public/pages/user-password-reset.html +32 -0
- package/public/pages/user-systemadm.html +508 -0
- package/public/pages/user.html +39 -0
- package/public/robots.txt +9 -0
- package/public/site.webmanifest +24 -0
- package/public/sitemap.xml +98 -0
- package/schemas/command-config.schema.json +582 -0
- package/scripts/baileys-compat-smoke.mjs +12 -0
- package/scripts/cache-bust.mjs +142 -0
- package/scripts/deploy.sh +916 -0
- package/scripts/email-broadcast-terms-update.mjs +170 -0
- package/scripts/enrich-command-discovery-fields.mjs +286 -0
- package/scripts/generate-command-config-schema.mjs +273 -0
- package/scripts/generate-commands-catalog.mjs +308 -0
- package/scripts/generate-module-agents.mjs +631 -0
- package/scripts/generate-seo-satellite-pages.mjs +400 -0
- package/scripts/github-deploy-notify.mjs +174 -0
- package/scripts/github-release-notify.mjs +219 -0
- package/scripts/release.sh +599 -0
- package/scripts/run-codeql-local.sh +116 -0
- package/scripts/run-prettier-all.mjs +25 -0
- package/scripts/security-smoketest.mjs +581 -0
- package/scripts/sticker-catalog-loadtest.mjs +210 -0
- package/scripts/sticker-worker-task.mjs +119 -0
- package/scripts/sync-readme-snapshot.mjs +133 -0
- package/scripts/validate-command-config-schema.mjs +130 -0
- package/scripts/validate-command-configs.mjs +15 -0
- package/scripts/wiki-sync.sh +191 -0
- package/server/auth/googleWebAuth/googleWebAuthRuntime.js +62 -0
- package/server/auth/googleWebAuth/googleWebAuthService.js +807 -0
- package/server/auth/jwt/webJwtService.js +147 -0
- package/server/auth/stickerCatalogAuthContext.js +165 -0
- package/server/auth/termsAcceptance/termsAcceptanceHandler.js +189 -0
- package/server/auth/userPassword/index.js +14 -0
- package/server/auth/userPassword/userPasswordAuthService.js +422 -0
- package/server/auth/userPassword/userPasswordCrypto.js +199 -0
- package/server/auth/userPassword/userPasswordCrypto.test.js +76 -0
- package/server/auth/userPassword/userPasswordRecoveryService.js +728 -0
- package/server/auth/validation/authSchemas.js +236 -0
- package/server/auth/webAccount/webAccountHandlers.js +1434 -0
- package/server/controllers/admin/adminBanService.js +138 -0
- package/server/controllers/admin/adminPanelHandlers.js +2083 -0
- package/server/controllers/admin/stickerCatalogAdminContext.js +17 -0
- package/server/controllers/admin/systemAdminController.js +201 -0
- package/server/controllers/email/emailAutomationController.js +239 -0
- package/server/controllers/metricsController.js +21 -0
- package/server/controllers/seo/stickerCatalogSeoContext.js +514 -0
- package/server/controllers/sticker/nonCatalogHandlers.js +303 -0
- package/server/controllers/sticker/stickerCatalogController.js +4700 -0
- package/server/controllers/system/contactController.js +115 -0
- package/server/controllers/system/githubController.js +137 -0
- package/server/controllers/system/stickerCatalogSystemContext.js +758 -0
- package/server/controllers/system/storageController.js +154 -0
- package/server/controllers/system/systemController.js +135 -0
- package/server/controllers/system/systemMetricsController.js +156 -0
- package/server/controllers/system/visitController.js +90 -0
- package/server/controllers/userController.js +145 -0
- package/server/email/emailAutomationRuntime.js +225 -0
- package/server/email/emailAutomationService.js +125 -0
- package/server/email/emailOutboxRepository.js +282 -0
- package/server/email/emailTemplateService.js +480 -0
- package/server/email/emailTransportService.js +156 -0
- package/server/http/clientIp.js +95 -0
- package/server/http/httpRequestUtils.js +262 -0
- package/server/http/httpRequestUtils.test.js +80 -0
- package/server/http/httpServer.js +180 -0
- package/server/http/requestContext.js +20 -0
- package/server/http/siteRoutingUtils.js +87 -0
- package/server/index.js +1 -0
- package/server/middleware/cachePolicy.js +26 -0
- package/server/middleware/cachePolicyHelpers.js +1 -0
- package/server/middleware/endpointRateLimit.js +181 -0
- package/server/middleware/rateLimit.js +70 -0
- package/server/middleware/requireAdminAuth.js +48 -0
- package/server/middleware/securityHeaders.js +97 -0
- package/server/routes/admin/systemAdminRouter.js +64 -0
- package/server/routes/email/emailAutomationRouter.js +46 -0
- package/server/routes/health/healthRouter.js +41 -0
- package/server/routes/indexRouter.js +234 -0
- package/server/routes/metrics/metricsRouter.js +58 -0
- package/server/routes/static/staticPageRouter.js +134 -0
- package/server/routes/sticker/catalogHandlers/catalogAdminHttp.js +105 -0
- package/server/routes/sticker/catalogHandlers/catalogAuthHttp.js +77 -0
- package/server/routes/sticker/catalogHandlers/catalogPublicHttp.js +120 -0
- package/server/routes/sticker/catalogHandlers/catalogUploadHttp.js +83 -0
- package/server/routes/sticker/catalogRouter.js +77 -0
- package/server/routes/sticker/stickerApiRouter.js +84 -0
- package/server/routes/sticker/stickerDataRouter.js +145 -0
- package/server/routes/sticker/stickerSiteRouter.js +43 -0
- package/server/routes/user/userApiPaths.js +66 -0
- package/server/routes/user/userRouter.js +65 -0
- package/server/utils/safePath.js +26 -0
- package/utils/logger/loggerModule.js +35 -0
- package/vite.config.mjs +38 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
import { executeQuery, TABLES } from '../../../database/index.js';
|
|
2
|
+
import { STICKER_DOMAIN_EVENTS } from './domainEvents.js';
|
|
3
|
+
import { publishStickerDomainEvent } from './stickerDomainEventBus.js';
|
|
4
|
+
|
|
5
|
+
const CATALOG_COMPLETE_PACK_TARGET = Math.max(1, Number(process.env.STICKER_PACK_MAX_ITEMS) || 30);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Normaliza linha da tabela de packs para formato usado no domínio.
|
|
9
|
+
*
|
|
10
|
+
* @param {Record<string, unknown>|null|undefined} row Linha retornada da query.
|
|
11
|
+
* @returns {object|null} Pack normalizado.
|
|
12
|
+
*/
|
|
13
|
+
const normalizeStickerPackRow = (row) => {
|
|
14
|
+
if (!row) return null;
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
id: row.id,
|
|
18
|
+
owner_jid: row.owner_jid,
|
|
19
|
+
name: row.name,
|
|
20
|
+
publisher: row.publisher,
|
|
21
|
+
description: row.description,
|
|
22
|
+
pack_key: row.pack_key,
|
|
23
|
+
cover_sticker_id: row.cover_sticker_id,
|
|
24
|
+
visibility: row.visibility,
|
|
25
|
+
status: row.status || 'published',
|
|
26
|
+
pack_status: row.pack_status || 'ready',
|
|
27
|
+
pack_theme_key: row.pack_theme_key || null,
|
|
28
|
+
pack_volume: row.pack_volume !== null && row.pack_volume !== undefined ? Number(row.pack_volume) : null,
|
|
29
|
+
is_auto_pack: row.is_auto_pack === 1 || row.is_auto_pack === true,
|
|
30
|
+
last_rebalanced_at: row.last_rebalanced_at || null,
|
|
31
|
+
version: Number(row.version || 1),
|
|
32
|
+
created_at: row.created_at,
|
|
33
|
+
updated_at: row.updated_at,
|
|
34
|
+
deleted_at: row.deleted_at,
|
|
35
|
+
sticker_count: row.sticker_count !== null && row.sticker_count !== undefined ? Number(row.sticker_count) : undefined,
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Busca pack por ID.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} packId ID interno do pack.
|
|
43
|
+
* @param {{ includeDeleted?: boolean, connection?: import('mysql2/promise').PoolConnection|null }} [options]
|
|
44
|
+
* @returns {Promise<object|null>} Pack encontrado.
|
|
45
|
+
*/
|
|
46
|
+
export async function findStickerPackById(packId, { includeDeleted = false, connection = null } = {}) {
|
|
47
|
+
const rows = await executeQuery(
|
|
48
|
+
`SELECT p.*,
|
|
49
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
50
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
51
|
+
WHERE p.id = ? ${includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
|
|
52
|
+
LIMIT 1`,
|
|
53
|
+
[packId],
|
|
54
|
+
connection,
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
return normalizeStickerPackRow(rows?.[0] || null);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Busca pack por chave pública (pack_key).
|
|
62
|
+
*
|
|
63
|
+
* @param {string} packKey Chave pública do pack.
|
|
64
|
+
* @param {{ includeDeleted?: boolean, connection?: import('mysql2/promise').PoolConnection|null }} [options]
|
|
65
|
+
* @returns {Promise<object|null>} Pack encontrado.
|
|
66
|
+
*/
|
|
67
|
+
export async function findStickerPackByPackKey(packKey, { includeDeleted = false, connection = null } = {}) {
|
|
68
|
+
const rows = await executeQuery(
|
|
69
|
+
`SELECT p.*,
|
|
70
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
71
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
72
|
+
WHERE p.pack_key = ? ${includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
|
|
73
|
+
LIMIT 1`,
|
|
74
|
+
[packKey],
|
|
75
|
+
connection,
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
return normalizeStickerPackRow(rows?.[0] || null);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Busca pack do dono por ID, pack_key ou nome.
|
|
83
|
+
*
|
|
84
|
+
* @param {string} ownerJid JID do dono.
|
|
85
|
+
* @param {string} identifier ID, chave ou nome do pack.
|
|
86
|
+
* @param {{ includeDeleted?: boolean, connection?: import('mysql2/promise').PoolConnection|null }} [options]
|
|
87
|
+
* @returns {Promise<object|null>} Pack encontrado.
|
|
88
|
+
*/
|
|
89
|
+
export async function findStickerPackByOwnerAndIdentifier(ownerJid, identifier, { includeDeleted = false, connection = null } = {}) {
|
|
90
|
+
if (!identifier) return null;
|
|
91
|
+
|
|
92
|
+
const idOrPack = await executeQuery(
|
|
93
|
+
`SELECT p.*,
|
|
94
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
95
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
96
|
+
WHERE p.owner_jid = ?
|
|
97
|
+
${includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
|
|
98
|
+
AND (p.id = ? OR p.pack_key = ?)
|
|
99
|
+
ORDER BY p.updated_at DESC
|
|
100
|
+
LIMIT 1`,
|
|
101
|
+
[ownerJid, identifier, identifier],
|
|
102
|
+
connection,
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
if (idOrPack?.[0]) {
|
|
106
|
+
return normalizeStickerPackRow(idOrPack[0]);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const byName = await executeQuery(
|
|
110
|
+
`SELECT p.*,
|
|
111
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
112
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
113
|
+
WHERE p.owner_jid = ?
|
|
114
|
+
${includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
|
|
115
|
+
AND LOWER(p.name) = LOWER(?)
|
|
116
|
+
ORDER BY p.updated_at DESC
|
|
117
|
+
LIMIT 1`,
|
|
118
|
+
[ownerJid, identifier],
|
|
119
|
+
connection,
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
return normalizeStickerPackRow(byName?.[0] || null);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Lista packs de um usuário com paginação simples.
|
|
127
|
+
*
|
|
128
|
+
* @param {string} ownerJid JID do dono.
|
|
129
|
+
* @param {{ includeDeleted?: boolean, limit?: number, offset?: number, connection?: import('mysql2/promise').PoolConnection|null }} [options]
|
|
130
|
+
* @returns {Promise<object[]>} Lista de packs.
|
|
131
|
+
*/
|
|
132
|
+
export async function listStickerPacksByOwner(ownerJid, { includeDeleted = false, limit = 50, offset = 0, connection = null } = {}) {
|
|
133
|
+
const safeLimit = Math.max(1, Number(limit) || 50);
|
|
134
|
+
const safeOffset = Math.max(0, Number(offset) || 0);
|
|
135
|
+
|
|
136
|
+
const rows = await executeQuery(
|
|
137
|
+
`SELECT p.*,
|
|
138
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
139
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
140
|
+
WHERE p.owner_jid = ? ${includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
|
|
141
|
+
ORDER BY p.updated_at DESC
|
|
142
|
+
LIMIT ${safeLimit} OFFSET ${safeOffset}`,
|
|
143
|
+
[ownerJid],
|
|
144
|
+
connection,
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
return rows.map((row) => normalizeStickerPackRow(row));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Lista packs automáticos de curadoria para um conjunto de owners.
|
|
152
|
+
*
|
|
153
|
+
* @param {{
|
|
154
|
+
* ownerJids?: string[],
|
|
155
|
+
* includeArchived?: boolean,
|
|
156
|
+
* themeKey?: string,
|
|
157
|
+
* limit?: number,
|
|
158
|
+
* offset?: number,
|
|
159
|
+
* connection?: import('mysql2/promise').PoolConnection|null,
|
|
160
|
+
* }} [options]
|
|
161
|
+
* @returns {Promise<object[]>}
|
|
162
|
+
*/
|
|
163
|
+
export async function listStickerAutoPacksForCuration({ ownerJids = [], includeArchived = true, themeKey = '', includeLegacyMarkers = true, limit = 2000, offset = 0, connection = null } = {}) {
|
|
164
|
+
const owners = Array.from(new Set((Array.isArray(ownerJids) ? ownerJids : []).filter(Boolean)));
|
|
165
|
+
if (!owners.length) return [];
|
|
166
|
+
|
|
167
|
+
const safeLimit = Math.max(1, Math.min(5000, Number(limit) || 2000));
|
|
168
|
+
const safeOffset = Math.max(0, Number(offset) || 0);
|
|
169
|
+
const ownerPlaceholders = owners.map(() => '?').join(', ');
|
|
170
|
+
|
|
171
|
+
const whereClauses = ['p.deleted_at IS NULL', `p.owner_jid IN (${ownerPlaceholders})`];
|
|
172
|
+
const params = [...owners];
|
|
173
|
+
|
|
174
|
+
if (includeLegacyMarkers) {
|
|
175
|
+
whereClauses.push("(p.is_auto_pack = 1 OR p.description LIKE '%[auto-theme:%' OR p.description LIKE '%[auto-tag:%')");
|
|
176
|
+
} else {
|
|
177
|
+
whereClauses.push('p.is_auto_pack = 1');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const normalizedThemeKey = String(themeKey || '')
|
|
181
|
+
.trim()
|
|
182
|
+
.toLowerCase();
|
|
183
|
+
if (normalizedThemeKey) {
|
|
184
|
+
whereClauses.push("LOWER(COALESCE(p.pack_theme_key, '')) = ?");
|
|
185
|
+
params.push(normalizedThemeKey);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (!includeArchived) {
|
|
189
|
+
whereClauses.push("COALESCE(p.pack_status, 'ready') <> 'archived'");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const rows = await executeQuery(
|
|
193
|
+
`SELECT p.*,
|
|
194
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
195
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
196
|
+
WHERE ${whereClauses.join(' AND ')}
|
|
197
|
+
ORDER BY
|
|
198
|
+
COALESCE(p.pack_theme_key, '') ASC,
|
|
199
|
+
COALESCE(p.pack_volume, 0) ASC,
|
|
200
|
+
p.updated_at DESC
|
|
201
|
+
LIMIT ${safeLimit} OFFSET ${safeOffset}`,
|
|
202
|
+
params,
|
|
203
|
+
connection,
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
return rows.map((row) => normalizeStickerPackRow(row));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Lista packs públicos para catálogo web com busca e paginação.
|
|
211
|
+
*
|
|
212
|
+
* @param {{
|
|
213
|
+
* visibility?: 'public'|'unlisted'|'all',
|
|
214
|
+
* search?: string,
|
|
215
|
+
* limit?: number,
|
|
216
|
+
* offset?: number,
|
|
217
|
+
* connection?: import('mysql2/promise').PoolConnection|null,
|
|
218
|
+
* }} [options] Filtros de listagem.
|
|
219
|
+
* @returns {Promise<{ packs: object[], hasMore: boolean }>} Resultado paginado.
|
|
220
|
+
*/
|
|
221
|
+
export async function listStickerPacksForCatalog({ visibility = 'public', search = '', limit = 24, offset = 0, connection = null } = {}) {
|
|
222
|
+
const safeLimit = Math.max(1, Math.min(60, Number(limit) || 24));
|
|
223
|
+
const safeOffset = Math.max(0, Number(offset) || 0);
|
|
224
|
+
const safeLimitWithSentinel = safeLimit + 1;
|
|
225
|
+
|
|
226
|
+
const normalizedVisibility = String(visibility || 'public')
|
|
227
|
+
.trim()
|
|
228
|
+
.toLowerCase();
|
|
229
|
+
const visibilityValues = normalizedVisibility === 'all' ? ['public', 'unlisted'] : normalizedVisibility === 'unlisted' ? ['unlisted'] : ['public'];
|
|
230
|
+
|
|
231
|
+
const normalizedSearch = String(search || '')
|
|
232
|
+
.trim()
|
|
233
|
+
.toLowerCase()
|
|
234
|
+
.slice(0, 120);
|
|
235
|
+
const params = [...visibilityValues];
|
|
236
|
+
const whereClauses = ['p.deleted_at IS NULL', "p.status = 'published'", "COALESCE(p.pack_status, 'ready') = 'ready'", `p.visibility IN (${visibilityValues.map(() => '?').join(', ')})`];
|
|
237
|
+
|
|
238
|
+
if (normalizedSearch) {
|
|
239
|
+
const like = `%${normalizedSearch}%`;
|
|
240
|
+
whereClauses.push("(LOWER(p.name) LIKE ? OR LOWER(p.publisher) LIKE ? OR LOWER(COALESCE(p.description, '')) LIKE ? OR LOWER(p.pack_key) LIKE ?)");
|
|
241
|
+
params.push(like, like, like, like);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const rows = await executeQuery(
|
|
245
|
+
`SELECT p.*,
|
|
246
|
+
(SELECT COUNT(*) FROM ${TABLES.STICKER_PACK_ITEM} i WHERE i.pack_id = p.id) AS sticker_count
|
|
247
|
+
FROM ${TABLES.STICKER_PACK} p
|
|
248
|
+
WHERE ${whereClauses.join(' AND ')}
|
|
249
|
+
ORDER BY
|
|
250
|
+
(sticker_count >= ${CATALOG_COMPLETE_PACK_TARGET}) DESC,
|
|
251
|
+
sticker_count DESC,
|
|
252
|
+
p.updated_at DESC
|
|
253
|
+
LIMIT ${safeLimitWithSentinel} OFFSET ${safeOffset}`,
|
|
254
|
+
params,
|
|
255
|
+
connection,
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
const hasMore = rows.length > safeLimit;
|
|
259
|
+
return {
|
|
260
|
+
packs: rows.slice(0, safeLimit).map((row) => normalizeStickerPackRow(row)),
|
|
261
|
+
hasMore,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Cria um registro de pack.
|
|
267
|
+
*
|
|
268
|
+
* @param {object} pack Dados do pack.
|
|
269
|
+
* @param {import('mysql2/promise').PoolConnection|null} [connection=null] Conexão transacional opcional.
|
|
270
|
+
* @returns {Promise<object|null>} Pack criado.
|
|
271
|
+
*/
|
|
272
|
+
export async function createStickerPack(pack, connection = null) {
|
|
273
|
+
await executeQuery(
|
|
274
|
+
`INSERT INTO ${TABLES.STICKER_PACK}
|
|
275
|
+
(
|
|
276
|
+
id,
|
|
277
|
+
owner_jid,
|
|
278
|
+
name,
|
|
279
|
+
publisher,
|
|
280
|
+
description,
|
|
281
|
+
pack_key,
|
|
282
|
+
cover_sticker_id,
|
|
283
|
+
visibility,
|
|
284
|
+
status,
|
|
285
|
+
pack_status,
|
|
286
|
+
pack_theme_key,
|
|
287
|
+
pack_volume,
|
|
288
|
+
is_auto_pack,
|
|
289
|
+
last_rebalanced_at,
|
|
290
|
+
version
|
|
291
|
+
)
|
|
292
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
293
|
+
[pack.id, pack.owner_jid, pack.name, pack.publisher, pack.description ?? null, pack.pack_key, pack.cover_sticker_id ?? null, pack.visibility, pack.status ?? 'published', pack.pack_status ?? 'ready', pack.pack_theme_key ?? null, pack.pack_volume ?? null, pack.is_auto_pack ? 1 : 0, pack.last_rebalanced_at ?? null, pack.version ?? 1],
|
|
294
|
+
connection,
|
|
295
|
+
);
|
|
296
|
+
|
|
297
|
+
await publishStickerDomainEvent(
|
|
298
|
+
{
|
|
299
|
+
eventType: STICKER_DOMAIN_EVENTS.PACK_UPDATED,
|
|
300
|
+
aggregateType: 'sticker_pack',
|
|
301
|
+
aggregateId: pack.id,
|
|
302
|
+
payload: {
|
|
303
|
+
action: 'created',
|
|
304
|
+
pack_id: pack.id,
|
|
305
|
+
pack_key: pack.pack_key,
|
|
306
|
+
owner_jid: pack.owner_jid,
|
|
307
|
+
visibility: pack.visibility,
|
|
308
|
+
},
|
|
309
|
+
priority: 75,
|
|
310
|
+
idempotencyKey: `pack_created:${pack.id}`,
|
|
311
|
+
},
|
|
312
|
+
{ connection },
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
return findStickerPackById(pack.id, { includeDeleted: true, connection });
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const UPDATE_FIELD_MAP = {
|
|
319
|
+
name: 'name',
|
|
320
|
+
publisher: 'publisher',
|
|
321
|
+
description: 'description',
|
|
322
|
+
pack_key: 'pack_key',
|
|
323
|
+
cover_sticker_id: 'cover_sticker_id',
|
|
324
|
+
visibility: 'visibility',
|
|
325
|
+
status: 'status',
|
|
326
|
+
pack_status: 'pack_status',
|
|
327
|
+
pack_theme_key: 'pack_theme_key',
|
|
328
|
+
pack_volume: 'pack_volume',
|
|
329
|
+
is_auto_pack: 'is_auto_pack',
|
|
330
|
+
last_rebalanced_at: 'last_rebalanced_at',
|
|
331
|
+
deleted_at: 'deleted_at',
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Atualiza campos permitidos de um pack.
|
|
336
|
+
*
|
|
337
|
+
* @param {string} packId ID do pack.
|
|
338
|
+
* @param {Record<string, unknown>} fields Campos para atualização.
|
|
339
|
+
* @param {import('mysql2/promise').PoolConnection|null} [connection=null] Conexão transacional opcional.
|
|
340
|
+
* @returns {Promise<object|null>} Pack atualizado.
|
|
341
|
+
*/
|
|
342
|
+
export async function updateStickerPackFields(packId, fields, connection = null) {
|
|
343
|
+
const setClauses = [];
|
|
344
|
+
const params = [];
|
|
345
|
+
|
|
346
|
+
for (const [field, column] of Object.entries(UPDATE_FIELD_MAP)) {
|
|
347
|
+
if (!(field in fields)) continue;
|
|
348
|
+
setClauses.push(`${column} = ?`);
|
|
349
|
+
params.push(fields[field]);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (!setClauses.length) {
|
|
353
|
+
return findStickerPackById(packId, { includeDeleted: true, connection });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
setClauses.push('version = version + 1');
|
|
357
|
+
setClauses.push('updated_at = CURRENT_TIMESTAMP');
|
|
358
|
+
|
|
359
|
+
await executeQuery(
|
|
360
|
+
`UPDATE ${TABLES.STICKER_PACK}
|
|
361
|
+
SET ${setClauses.join(', ')}
|
|
362
|
+
WHERE id = ?`,
|
|
363
|
+
[...params, packId],
|
|
364
|
+
connection,
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
await publishStickerDomainEvent(
|
|
368
|
+
{
|
|
369
|
+
eventType: STICKER_DOMAIN_EVENTS.PACK_UPDATED,
|
|
370
|
+
aggregateType: 'sticker_pack',
|
|
371
|
+
aggregateId: packId,
|
|
372
|
+
payload: {
|
|
373
|
+
action: 'updated',
|
|
374
|
+
pack_id: packId,
|
|
375
|
+
fields: Object.keys(fields || {}).slice(0, 30),
|
|
376
|
+
},
|
|
377
|
+
priority: 70,
|
|
378
|
+
idempotencyKey: `pack_updated:${packId}:${Object.keys(fields || {})
|
|
379
|
+
.sort()
|
|
380
|
+
.join(',')}`,
|
|
381
|
+
},
|
|
382
|
+
{ connection },
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
return findStickerPackById(packId, { includeDeleted: true, connection });
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Marca um pack como deletado sem remover dados físicos.
|
|
390
|
+
*
|
|
391
|
+
* @param {string} packId ID do pack.
|
|
392
|
+
* @param {import('mysql2/promise').PoolConnection|null} [connection=null] Conexão transacional opcional.
|
|
393
|
+
* @returns {Promise<object|null>} Pack atualizado.
|
|
394
|
+
*/
|
|
395
|
+
export async function softDeleteStickerPack(packId, connection = null) {
|
|
396
|
+
return updateStickerPackFields(
|
|
397
|
+
packId,
|
|
398
|
+
{
|
|
399
|
+
deleted_at: new Date(),
|
|
400
|
+
},
|
|
401
|
+
connection,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Verifica se a chave pública (pack_key) está disponível.
|
|
407
|
+
*
|
|
408
|
+
* @param {string} packKey Chave candidata.
|
|
409
|
+
* @param {import('mysql2/promise').PoolConnection|null} [connection=null] Conexão transacional opcional.
|
|
410
|
+
* @returns {Promise<boolean>} `true` quando não existe pack com essa chave.
|
|
411
|
+
*/
|
|
412
|
+
export async function ensureUniquePackKey(packKey, connection = null) {
|
|
413
|
+
const existing = await findStickerPackByPackKey(packKey, { includeDeleted: true, connection });
|
|
414
|
+
return !existing;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Incrementa versão e timestamp de atualização do pack.
|
|
419
|
+
*
|
|
420
|
+
* @param {string} packId ID do pack.
|
|
421
|
+
* @param {import('mysql2/promise').PoolConnection|null} [connection=null] Conexão transacional opcional.
|
|
422
|
+
* @returns {Promise<object|null>} Pack atualizado.
|
|
423
|
+
*/
|
|
424
|
+
export async function bumpStickerPackVersion(packId, connection = null) {
|
|
425
|
+
await executeQuery(
|
|
426
|
+
`UPDATE ${TABLES.STICKER_PACK}
|
|
427
|
+
SET version = version + 1,
|
|
428
|
+
updated_at = CURRENT_TIMESTAMP
|
|
429
|
+
WHERE id = ?`,
|
|
430
|
+
[packId],
|
|
431
|
+
connection,
|
|
432
|
+
);
|
|
433
|
+
|
|
434
|
+
await publishStickerDomainEvent(
|
|
435
|
+
{
|
|
436
|
+
eventType: STICKER_DOMAIN_EVENTS.PACK_UPDATED,
|
|
437
|
+
aggregateType: 'sticker_pack',
|
|
438
|
+
aggregateId: packId,
|
|
439
|
+
payload: {
|
|
440
|
+
action: 'version_bumped',
|
|
441
|
+
pack_id: packId,
|
|
442
|
+
},
|
|
443
|
+
priority: 65,
|
|
444
|
+
idempotencyKey: `pack_version_bumped:${packId}`,
|
|
445
|
+
},
|
|
446
|
+
{ connection },
|
|
447
|
+
);
|
|
448
|
+
|
|
449
|
+
return findStickerPackById(packId, { includeDeleted: true, connection });
|
|
450
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { executeQuery, TABLES } from '../../../database/index.js';
|
|
2
|
+
|
|
3
|
+
const parseJson = (value, fallback = null) => {
|
|
4
|
+
if (value === null || value === undefined) return fallback;
|
|
5
|
+
if (typeof value === 'object') return value;
|
|
6
|
+
if (Buffer.isBuffer(value)) {
|
|
7
|
+
try {
|
|
8
|
+
return JSON.parse(value.toString('utf8'));
|
|
9
|
+
} catch {
|
|
10
|
+
return fallback;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
if (typeof value === 'string') {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(value);
|
|
16
|
+
} catch {
|
|
17
|
+
return fallback;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return fallback;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const clampScore = (value) => {
|
|
24
|
+
const numeric = Number(value);
|
|
25
|
+
if (!Number.isFinite(numeric)) return 0;
|
|
26
|
+
return Number(numeric.toFixed(6));
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const normalizeNsfwLevel = (value) => {
|
|
30
|
+
const normalized = String(value || '')
|
|
31
|
+
.trim()
|
|
32
|
+
.toLowerCase();
|
|
33
|
+
if (['safe', 'suggestive', 'explicit'].includes(normalized)) return normalized;
|
|
34
|
+
return 'safe';
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const normalizeRow = (row) => {
|
|
38
|
+
if (!row) return null;
|
|
39
|
+
const scoresFromJson = parseJson(row.scores_json, {}) || {};
|
|
40
|
+
return {
|
|
41
|
+
pack_id: row.pack_id,
|
|
42
|
+
ranking_score: clampScore(row.ranking_score),
|
|
43
|
+
pack_score: clampScore(row.pack_score),
|
|
44
|
+
trend_score: clampScore(row.trend_score),
|
|
45
|
+
quality_score: clampScore(row.quality_score),
|
|
46
|
+
engagement_score: clampScore(row.engagement_score),
|
|
47
|
+
diversity_score: clampScore(row.diversity_score),
|
|
48
|
+
cohesion_score: clampScore(row.cohesion_score),
|
|
49
|
+
sensitive_content: row.sensitive_content === 1 || row.sensitive_content === true,
|
|
50
|
+
nsfw_level: normalizeNsfwLevel(row.nsfw_level),
|
|
51
|
+
sticker_count: Number(row.sticker_count || 0),
|
|
52
|
+
tags: Array.isArray(parseJson(row.tags, [])) ? parseJson(row.tags, []) : [],
|
|
53
|
+
source_version: row.source_version || 'v1',
|
|
54
|
+
refreshed_at: row.refreshed_at || null,
|
|
55
|
+
updated_at: row.updated_at || null,
|
|
56
|
+
signals: {
|
|
57
|
+
...scoresFromJson,
|
|
58
|
+
quality_score: clampScore(row.quality_score),
|
|
59
|
+
engagement_score: clampScore(row.engagement_score),
|
|
60
|
+
diversity_score: clampScore(row.diversity_score),
|
|
61
|
+
cohesion_score: clampScore(row.cohesion_score),
|
|
62
|
+
trend_score: clampScore(row.trend_score),
|
|
63
|
+
pack_score: clampScore(row.pack_score),
|
|
64
|
+
ranking_score: clampScore(row.ranking_score),
|
|
65
|
+
nsfw_level: normalizeNsfwLevel(row.nsfw_level),
|
|
66
|
+
sensitive_content: row.sensitive_content === 1 || row.sensitive_content === true,
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const normalizeSnapshotInput = (entry) => {
|
|
72
|
+
if (!entry?.pack_id) return null;
|
|
73
|
+
const signals = entry?.signals && typeof entry.signals === 'object' ? entry.signals : {};
|
|
74
|
+
return {
|
|
75
|
+
pack_id: String(entry.pack_id),
|
|
76
|
+
ranking_score: clampScore(signals.ranking_score),
|
|
77
|
+
pack_score: clampScore(signals.pack_score),
|
|
78
|
+
trend_score: clampScore(signals.trend_score),
|
|
79
|
+
quality_score: clampScore(signals.quality_score),
|
|
80
|
+
engagement_score: clampScore(signals.engagement_score),
|
|
81
|
+
diversity_score: clampScore(signals.diversity_score),
|
|
82
|
+
cohesion_score: clampScore(signals.cohesion_score),
|
|
83
|
+
sensitive_content: signals.sensitive_content === true || signals.sensitive_content === 1 ? 1 : 0,
|
|
84
|
+
nsfw_level: normalizeNsfwLevel(signals.nsfw_level),
|
|
85
|
+
sticker_count: Math.max(0, Number(entry.sticker_count || 0)),
|
|
86
|
+
tags: Array.isArray(entry.tags) ? entry.tags.slice(0, 30) : [],
|
|
87
|
+
source_version:
|
|
88
|
+
String(entry.source_version || 'v1')
|
|
89
|
+
.trim()
|
|
90
|
+
.slice(0, 32) || 'v1',
|
|
91
|
+
scores_json: signals,
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export async function upsertStickerPackScoreSnapshots(entries = [], connection = null) {
|
|
96
|
+
const normalized = (Array.isArray(entries) ? entries : []).map((entry) => normalizeSnapshotInput(entry)).filter(Boolean);
|
|
97
|
+
if (!normalized.length) return 0;
|
|
98
|
+
|
|
99
|
+
let written = 0;
|
|
100
|
+
for (let offset = 0; offset < normalized.length; offset += 100) {
|
|
101
|
+
const chunk = normalized.slice(offset, offset + 100);
|
|
102
|
+
const placeholders = chunk.map(() => '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP())').join(', ');
|
|
103
|
+
const params = chunk.flatMap((entry) => [entry.pack_id, entry.ranking_score, entry.pack_score, entry.trend_score, entry.quality_score, entry.engagement_score, entry.diversity_score, entry.cohesion_score, entry.sensitive_content, entry.nsfw_level, entry.sticker_count, JSON.stringify(entry.tags || []), JSON.stringify(entry.scores_json || {}), entry.source_version]);
|
|
104
|
+
const result = await executeQuery(
|
|
105
|
+
`INSERT INTO ${TABLES.STICKER_PACK_SCORE_SNAPSHOT}
|
|
106
|
+
(
|
|
107
|
+
pack_id,
|
|
108
|
+
ranking_score,
|
|
109
|
+
pack_score,
|
|
110
|
+
trend_score,
|
|
111
|
+
quality_score,
|
|
112
|
+
engagement_score,
|
|
113
|
+
diversity_score,
|
|
114
|
+
cohesion_score,
|
|
115
|
+
sensitive_content,
|
|
116
|
+
nsfw_level,
|
|
117
|
+
sticker_count,
|
|
118
|
+
tags,
|
|
119
|
+
scores_json,
|
|
120
|
+
source_version,
|
|
121
|
+
refreshed_at
|
|
122
|
+
)
|
|
123
|
+
VALUES ${placeholders}
|
|
124
|
+
ON DUPLICATE KEY UPDATE
|
|
125
|
+
ranking_score = VALUES(ranking_score),
|
|
126
|
+
pack_score = VALUES(pack_score),
|
|
127
|
+
trend_score = VALUES(trend_score),
|
|
128
|
+
quality_score = VALUES(quality_score),
|
|
129
|
+
engagement_score = VALUES(engagement_score),
|
|
130
|
+
diversity_score = VALUES(diversity_score),
|
|
131
|
+
cohesion_score = VALUES(cohesion_score),
|
|
132
|
+
sensitive_content = VALUES(sensitive_content),
|
|
133
|
+
nsfw_level = VALUES(nsfw_level),
|
|
134
|
+
sticker_count = VALUES(sticker_count),
|
|
135
|
+
tags = VALUES(tags),
|
|
136
|
+
scores_json = VALUES(scores_json),
|
|
137
|
+
source_version = VALUES(source_version),
|
|
138
|
+
refreshed_at = UTC_TIMESTAMP(),
|
|
139
|
+
updated_at = CURRENT_TIMESTAMP`,
|
|
140
|
+
params,
|
|
141
|
+
connection,
|
|
142
|
+
);
|
|
143
|
+
written += Number(result?.affectedRows || 0);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return written;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export async function listStickerPackScoreSnapshotsByPackIds(packIds = [], connection = null) {
|
|
150
|
+
const ids = Array.from(new Set((Array.isArray(packIds) ? packIds : []).filter(Boolean)));
|
|
151
|
+
if (!ids.length) return new Map();
|
|
152
|
+
const placeholders = ids.map(() => '?').join(', ');
|
|
153
|
+
const rows = await executeQuery(
|
|
154
|
+
`SELECT *
|
|
155
|
+
FROM ${TABLES.STICKER_PACK_SCORE_SNAPSHOT}
|
|
156
|
+
WHERE pack_id IN (${placeholders})`,
|
|
157
|
+
ids,
|
|
158
|
+
connection,
|
|
159
|
+
);
|
|
160
|
+
const byPackId = new Map();
|
|
161
|
+
(Array.isArray(rows) ? rows : []).forEach((row) => {
|
|
162
|
+
const normalized = normalizeRow(row);
|
|
163
|
+
if (!normalized?.pack_id) return;
|
|
164
|
+
byPackId.set(normalized.pack_id, normalized);
|
|
165
|
+
});
|
|
166
|
+
return byPackId;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function removeSnapshotsForDeletedPacks(connection = null) {
|
|
170
|
+
const result = await executeQuery(
|
|
171
|
+
`DELETE s
|
|
172
|
+
FROM ${TABLES.STICKER_PACK_SCORE_SNAPSHOT} s
|
|
173
|
+
LEFT JOIN ${TABLES.STICKER_PACK} p ON p.id = s.pack_id
|
|
174
|
+
WHERE p.id IS NULL OR p.deleted_at IS NOT NULL`,
|
|
175
|
+
[],
|
|
176
|
+
connection,
|
|
177
|
+
);
|
|
178
|
+
return Number(result?.affectedRows || 0);
|
|
179
|
+
}
|