|
| 1 | +import { configService, PapiLicense } from '@config/env.config'; |
| 2 | +import { Logger } from '@config/logger.config'; |
| 3 | + |
| 4 | +import licenseManager from '../../../papi/lib/License/licenseManager.js'; |
| 5 | + |
| 6 | +export class LicenseService { |
| 7 | + private logger = new Logger('LICENSE'); |
| 8 | + private initialized = false; |
| 9 | + private initializing = false; |
| 10 | + |
| 11 | + /** |
| 12 | + * Initialize license manager with environment variables (lazy initialization) |
| 13 | + * Only initializes when interactive messages are actually used |
| 14 | + */ |
| 15 | + private async ensureInitialized(): Promise<void> { |
| 16 | + // Se já está inicializado, retorna |
| 17 | + if (this.initialized) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + // Se já está inicializando, aguarda |
| 22 | + if (this.initializing) { |
| 23 | + // Aguarda até 5 segundos para a inicialização completar |
| 24 | + let attempts = 0; |
| 25 | + while (this.initializing && attempts < 50) { |
| 26 | + await new Promise((resolve) => setTimeout(resolve, 100)); |
| 27 | + attempts++; |
| 28 | + } |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + this.initializing = true; |
| 33 | + |
| 34 | + try { |
| 35 | + const licenseConfig = configService.get<PapiLicense>('PAPI_LICENSE'); |
| 36 | + |
| 37 | + // Se não há configuração de licença, bloqueia mensagens interativas |
| 38 | + if (!licenseConfig.KEY || !licenseConfig.ADMIN_URL) { |
| 39 | + this.logger.warn( |
| 40 | + '⚠️ PAPI License not configured - Interactive messages (buttons, lists, carousel) will be BLOCKED', |
| 41 | + ); |
| 42 | + this.logger.warn( |
| 43 | + 'To enable interactive messages, configure PAPI_LICENSE_KEY and PAPI_LICENSE_ADMIN_URL in your .env file', |
| 44 | + ); |
| 45 | + this.logger.warn('Get your license key at: https://padmin.intrategica.com.br/register.html'); |
| 46 | + this.initializing = false; |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + this.logger.verbose('Initializing PAPI License Manager...'); |
| 51 | + |
| 52 | + await licenseManager.initialize(licenseConfig.KEY, licenseConfig.ADMIN_URL); |
| 53 | + |
| 54 | + // Set callback for when license is blocked |
| 55 | + licenseManager.onBlock(() => { |
| 56 | + this.logger.error('⚠️ PAPI License has been BLOCKED - Interactive messages are now disabled'); |
| 57 | + }); |
| 58 | + |
| 59 | + const initialStatus = licenseManager.getStatus(); |
| 60 | + |
| 61 | + if (initialStatus.status === 'PENDING_ACTIVATION') { |
| 62 | + this.logger.warn( |
| 63 | + '⏳ PAPI License is pending activation - Interactive messages will be blocked until activation', |
| 64 | + ); |
| 65 | + } else if (initialStatus.status === 'MACHINE_MISMATCH') { |
| 66 | + this.logger.error('❌ PAPI License is bound to another server - Interactive messages are disabled'); |
| 67 | + } else if (initialStatus.status === 'ACTIVE') { |
| 68 | + this.logger.info(`✓ PAPI License is ACTIVE - Interactive messages enabled`); |
| 69 | + } else { |
| 70 | + this.logger.warn(`PAPI License status: ${initialStatus.status} - ${initialStatus.message}`); |
| 71 | + } |
| 72 | + |
| 73 | + this.initialized = true; |
| 74 | + } catch (error) { |
| 75 | + this.logger.error(`Failed to initialize PAPI License Manager: ${error}`); |
| 76 | + // Não bloqueia a inicialização, mas marca como não inicializado |
| 77 | + } finally { |
| 78 | + this.initializing = false; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Check if interactive messages are allowed (buttons, lists, carousel) |
| 84 | + * Initializes license manager on first use (lazy initialization) |
| 85 | + * Updates instance count when checking (replaces periodic updates) |
| 86 | + */ |
| 87 | + public async isAllowed(instancesCount?: number): Promise<boolean> { |
| 88 | + const licenseConfig = configService.get<PapiLicense>('PAPI_LICENSE'); |
| 89 | + |
| 90 | + // Se não há configuração de licença, bloqueia mensagens interativas |
| 91 | + if (!licenseConfig.KEY || !licenseConfig.ADMIN_URL) { |
| 92 | + return false; |
| 93 | + } |
| 94 | + |
| 95 | + // Inicializa se ainda não foi inicializado (lazy initialization) |
| 96 | + await this.ensureInitialized(); |
| 97 | + |
| 98 | + // Se não foi inicializado após tentativa, bloqueia por segurança |
| 99 | + if (!this.initialized) { |
| 100 | + return false; |
| 101 | + } |
| 102 | + |
| 103 | + // Atualiza contagem de instâncias quando verificar (substitui atualização periódica) |
| 104 | + if (instancesCount !== undefined) { |
| 105 | + licenseManager.setInstancesCount(instancesCount); |
| 106 | + } |
| 107 | + |
| 108 | + return licenseManager.isAllowed(); |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Get current license status |
| 113 | + * Initializes license manager on first use (lazy initialization) |
| 114 | + */ |
| 115 | + public async getStatus() { |
| 116 | + const licenseConfig = configService.get<PapiLicense>('PAPI_LICENSE'); |
| 117 | + |
| 118 | + if (!licenseConfig.KEY || !licenseConfig.ADMIN_URL) { |
| 119 | + return { |
| 120 | + isValid: false, |
| 121 | + status: 'NOT_CONFIGURED' as const, |
| 122 | + message: 'License key and admin URL must be configured', |
| 123 | + }; |
| 124 | + } |
| 125 | + |
| 126 | + // Inicializa se ainda não foi inicializado (lazy initialization) |
| 127 | + await this.ensureInitialized(); |
| 128 | + |
| 129 | + if (!this.initialized) { |
| 130 | + return { |
| 131 | + isValid: false, |
| 132 | + status: 'NOT_INITIALIZED' as const, |
| 133 | + message: 'License manager not initialized', |
| 134 | + }; |
| 135 | + } |
| 136 | + |
| 137 | + return licenseManager.getStatus(); |
| 138 | + } |
| 139 | + |
| 140 | + /** |
| 141 | + * Update instances count for heartbeat |
| 142 | + * Called only when interactive messages are used (not periodically) |
| 143 | + * @deprecated Use isAllowed(instancesCount) instead |
| 144 | + */ |
| 145 | + public setInstancesCount(count: number): void { |
| 146 | + if (this.initialized) { |
| 147 | + licenseManager.setInstancesCount(count); |
| 148 | + } |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +export const licenseService = new LicenseService(); |
0 commit comments