UNPKG

dt-common-device

Version:

A secure and robust device management library for IoT applications

402 lines (401 loc) 19.3 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuditUtils = void 0; const property_1 = require("../entities/property"); const redis_utils_1 = require("../utils/redis.utils"); const services_1 = require("../entities/device/local/services"); const typedi_1 = __importStar(require("typedi")); const pms_1 = require("../entities/pms"); const admin_1 = require("../entities/admin"); const config_1 = require("../config/config"); let AuditUtils = (() => { let _classDecorators = [(0, typedi_1.Service)()]; let _classDescriptor; let _classExtraInitializers = []; let _classThis; var AuditUtils = _classThis = class { constructor() { this.CACHE_TTL = 24 * 60 * 60; // 24 hours in seconds this.CACHE_PREFIX = "audit:entity"; this.AUDIT_FIELDS = [ "resource", "propertyId", "propertyName", "userId", "userName", "guestId", "guestName", "deviceId", "deviceName", "zoneId", "zoneName", "accessGroupId", "accessGroupName", "scheduleId", "scheduleStartDate", "scheduleEndDate", "scheduleDuration", "scheduleSource", "scheduleStatus", "eventData", ]; this.redisUtils = new redis_utils_1.RedisUtils(); } async buildAuditProperties(input) { // Normalize keys to camelCase for matching const normalized = { ...input }; // Build the audit object with all standard fields const audit = {}; for (const field of this.AUDIT_FIELDS) { // Try to find a matching key in input (case-insensitive) const foundKey = Object.keys(normalized).find((k) => k.toLowerCase() === field.toLowerCase()); audit[field] = foundKey ? normalized[foundKey] : undefined; } // Merge in all other event-specific data (but don't overwrite audit fields) for (const key of Object.keys(normalized)) { if (!audit.hasOwnProperty(key)) { audit[key] = normalized[key]; } } // Util Function that will take all id Fields and get related information from database and add to audit await this.populateAuditFields(audit); return audit; } async populateAuditFields(audit) { try { const { propertyId, propertyName, userId, userName, guestId, guestName, deviceId, deviceName, zoneId, zoneName, accessGroupId, accessGroupName, scheduleId, referenceId, } = audit; if (propertyId && !propertyName) { (0, config_1.getLogger)().info(`Property ID: ${propertyId}`); if (propertyId === "triggered_externally") { audit.propertyName = "Triggered Externally"; } else if (propertyId === "property_not_found") { (0, config_1.getLogger)().info(`Property ID: ${propertyId}`); audit.propertyName = "Property Not Found"; } else { (0, config_1.getLogger)().info(`Property ID: ${propertyId}`); audit.propertyName = await this.getPropertyName(propertyId); } } if (!propertyId && deviceId) { audit.propertyId = await this.getFieldFromDevice(deviceId, "propertyId"); audit.propertyName = await this.getPropertyName(audit.propertyId); } if (zoneId && !zoneName) audit.zoneName = await this.getZoneName(zoneId); if (!zoneId && deviceId) { audit.zoneId = await this.getFieldFromDevice(deviceId, "zoneId"); audit.zoneName = await this.getZoneName(audit.zoneId); } if (userId && !userName) audit.userName = await this.getUserName(userId); if (guestId && !guestName) audit.guestName = await this.getGuestName(guestId); if (deviceId && !deviceName) { audit.deviceName = await this.getDeviceName(deviceId); } if (accessGroupId && !accessGroupName) audit.accessGroupName = await this.getAccessGroupName(accessGroupId); if (referenceId && !scheduleId) audit.scheduleId = await this.getScheduleId(referenceId); if (scheduleId && !referenceId) audit.referenceId = await this.getReferenceId(scheduleId); // if (scheduleId) { // const { // scheduleStartDate, // scheduleEndDate, // scheduleDuration, // scheduleSource, // scheduleStatus, // referenceId, // } = await this.getScheduleDetails(scheduleId); // audit.scheduleStartDate = scheduleStartDate; // audit.scheduleEndDate = scheduleEndDate; // audit.scheduleDuration = scheduleDuration; // audit.scheduleSource = scheduleSource; // audit.scheduleStatus = scheduleStatus; // audit.referenceId = referenceId; // } } catch (error) { (0, config_1.getLogger)().error(`Error in populateAuditFields: ${error instanceof Error ? error.message : error}`); } } /** * Generic utility to get cached entity data from Redis using individual keys */ async getCachedEntityData(entityType, entityId, fetchFunction) { try { const cacheKey = `${this.CACHE_PREFIX}:${entityType}:${entityId}`; // Try to get from cache first const cachedData = await this.redisUtils.get(cacheKey); if (cachedData && JSON.parse(cachedData)) { return JSON.parse(cachedData); } // If not in cache, fetch from database and cache it const entityData = await fetchFunction(); await this.redisUtils.set(cacheKey, JSON.stringify(entityData), this.CACHE_TTL); return entityData; } catch (error) { (0, config_1.getLogger)().error(`Error in getCachedEntityData: ${error instanceof Error ? error.message : error}`); throw error; } } /** * Utility to calculate schedule duration in days */ calculateScheduleDuration(startTime, endTime) { const duration = new Date(endTime).getTime() - new Date(startTime).getTime(); return Math.ceil(duration / (1000 * 60 * 60 * 24)); } async getPropertyName(propertyId) { try { return await this.getCachedEntityData("property", propertyId, async () => { const property = await typedi_1.default.get(property_1.LocalPropertyService).getProperty(propertyId); return property?.name || "property_not_found"; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getPropertyName: ${error instanceof Error ? error.message : error}`); return ""; } } async getFieldFromDevice(deviceId, field) { try { const redisKey = `device:${deviceId}`; const redisDevice = await this.redisUtils.hget(redisKey, "device"); if (redisDevice) { return redisDevice[field]; } else { const device = await typedi_1.default.get(services_1.LocalDeviceService).getDevice(deviceId); await this.redisUtils.hset(redisKey, "device", JSON.stringify(device)); await this.redisUtils.expire(redisKey, this.CACHE_TTL); return device[field]; } } catch (error) { (0, config_1.getLogger)().error(`Error in getFieldFromDevice: ${error instanceof Error ? error.message : error}`); return ""; } } async getUserName(userId) { try { return await this.getCachedEntityData("user", userId, async () => { const user = await typedi_1.default.get(admin_1.AdminService).getUser(userId); if (!user) return "user_not_found"; return `${user?.firstName || ""} ${user?.lastName || ""}`.trim(); }); } catch (error) { (0, config_1.getLogger)().error(`Error in getUserName: ${error instanceof Error ? error.message : error}`); return ""; } } async getGuestName(guestId) { try { return await this.getCachedEntityData("guest", guestId, async () => { const guest = await typedi_1.default.get(pms_1.PmsService).getGuest(guestId); if (!guest) return ""; return `${guest?.firstName || ""} ${guest?.lastName || ""}`.trim(); }); } catch (error) { (0, config_1.getLogger)().error(`Error in getGuestName: ${error instanceof Error ? error.message : error}`); return ""; } } async getDeviceName(deviceId) { try { return await this.getCachedEntityData("device", deviceId, async () => { const device = await typedi_1.default.get(services_1.LocalDeviceService).querySelect({ deviceId }, ["name"]); if (!device) return ""; return device[0]?.name || ""; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getDeviceName: ${error instanceof Error ? error.message : error}`); return ""; } } async getZoneName(zoneId) { try { return await this.getCachedEntityData("zone", zoneId, async () => { const zone = await typedi_1.default.get(admin_1.AdminService).getZone(zoneId); if (!zone) return ""; return zone?.name || ""; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getZoneName: ${error instanceof Error ? error.message : error}`); return ""; } } async getAccessGroupName(accessGroupId) { try { return await this.getCachedEntityData("accessGroup", accessGroupId, async () => { const accessGroup = await typedi_1.default.get(admin_1.AdminService).getAccessGroup(accessGroupId); if (!accessGroup) return ""; return accessGroup?.name || ""; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getAccessGroupName: ${error instanceof Error ? error.message : error}`); return ""; } } async getScheduleId(referenceId) { try { return await this.getCachedEntityData("scheduleId", referenceId, async () => { const schedule = await typedi_1.default.get(pms_1.PmsService).getScheduleByReferenceId(referenceId); if (!schedule) return ""; return schedule?.id || ""; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getScheduleId: ${error instanceof Error ? error.message : error}`); return ""; } } async getReferenceId(scheduleId) { try { return await this.getCachedEntityData("referenceId", scheduleId, async () => { const schedule = await typedi_1.default.get(pms_1.PmsService).getSchedule(scheduleId); if (!schedule) return ""; return schedule?.referenceId || ""; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getReferenceId: ${error instanceof Error ? error.message : error}`); return ""; } } async getScheduleDetails(scheduleId) { try { return await this.getCachedEntityData("schedule", scheduleId, async () => { const schedule = await typedi_1.default.get(pms_1.PmsService).getSchedule(scheduleId); if (!schedule) { return { scheduleStartDate: "", scheduleEndDate: "", scheduleDuration: 0, scheduleSource: "", scheduleStatus: "", referenceId: "", }; } const scheduleDuration = this.calculateScheduleDuration(schedule.startTime, schedule.endTime); return { scheduleStartDate: schedule.startTime, scheduleEndDate: schedule.endTime, scheduleDuration, scheduleSource: schedule.source, scheduleStatus: schedule.status, referenceId: schedule.referenceId, }; }); } catch (error) { (0, config_1.getLogger)().error(`Error in getScheduleDetails: ${error instanceof Error ? error.message : error}`); return { scheduleStartDate: "", scheduleEndDate: "", scheduleDuration: 0, scheduleSource: "", scheduleStatus: "", referenceId: "", }; } } }; __setFunctionName(_classThis, "AuditUtils"); (() => { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); AuditUtils = _classThis = _classDescriptor.value; if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); __runInitializers(_classThis, _classExtraInitializers); })(); return AuditUtils = _classThis; })(); exports.AuditUtils = AuditUtils;