From 795b4afbcfd0a3fdac41dd80ce76e5ccc167b178 Mon Sep 17 00:00:00 2001 From: AntonSeleznev Date: Fri, 31 Jan 2025 12:59:42 +0200 Subject: [PATCH] Di imp Contact/File/OpLogs/PushNotif (#152) * update DI * fix contact specs * add Push Event/Subscription DI * refactor * File to DI * Op Logs DI --- APIs/JSON/controllers/contacts.js | 65 +---- APIs/JSON/controllers/files.js | 37 +-- APIs/JSON/controllers/operations_log.js | 17 +- APIs/JSON/controllers/push_notifications.js | 89 ++----- APIs/XMPP | 2 +- app/cluster/cluster_syncer.js | 43 ++-- app/lib/push_queue/base.js | 15 +- app/models/base.js | 232 +++--------------- app/{new_models => models}/blocked_user.js | 2 +- app/models/cluster_node.js | 6 +- app/models/contact.js | 4 - app/{new_models => models}/conversation.js | 0 .../conversation_participants.js | 0 app/models/file.js | 10 +- app/{new_models => models}/message.js | 0 app/{new_models => models}/message_status.js | 0 app/models/operations_log.js | 6 +- app/models/push_event.js | 7 +- app/models/push_subscription.js | 11 +- app/{new_models => models}/user.js | 0 app/{new_models => models}/user_token.js | 2 +- app/networking/packet_manager.js | 5 +- app/new_models/base.js | 67 ----- app/new_models/file.js | 13 - app/providers/index.js | 48 ++++ .../operations/contact/create/Provider.js | 15 ++ .../operations/contact/create/index.js | 43 ++++ .../operations/contact/delete/Provider.js | 15 ++ .../operations/contact/delete/index.js | 15 ++ .../operations/contact/edit/Provider.js | 15 ++ .../operations/contact/edit/index.js | 27 ++ .../operations/contact/list/Provider.js | 15 ++ .../operations/contact/list/index.js | 18 ++ .../operations/file/create/Provider.js | 15 ++ app/providers/operations/file/create/index.js | 22 ++ .../operations/file/download/Provider.js | 15 ++ .../operations/file/download/index.js | 24 ++ .../operation_logs/list/Provider.js | 15 ++ .../operations/operation_logs/list/index.js | 18 ++ .../create_event/Provider.js | 16 ++ .../push_notifications/create_event/index.js | 29 +++ .../create_subscription/Provider.js | 18 ++ .../create_subscription/index.js | 22 ++ .../delete_subscription/Provider.js | 18 ++ .../delete_subscription/index.js | 24 ++ .../list_subscriptions/Provider.js | 18 ++ .../list_subscriptions/index.js | 16 ++ .../operations/user/create/Provider.js | 5 +- .../operations/user/delete/Provider.js | 5 +- .../operations/user/edit/Provider.js | 5 +- app/providers/repositories/base.js | 12 +- .../repositories/blocked_user/Provider.js | 2 +- .../repositories/cluster_node/Provider.js | 16 ++ .../repositories/cluster_node/index.js | 9 + .../repositories/contact/Provider.js | 16 ++ app/providers/repositories/contact/index.js | 46 ++++ .../repositories/conversation/Provider.js | 2 +- .../conversation_participants/Provider.js | 2 +- app/providers/repositories/file/Provider.js | 2 +- .../repositories/message/Provider.js | 2 +- .../repositories/message_status/Provider.js | 2 +- .../repositories/operations_log/Provider.js | 16 ++ .../repositories/operations_log/index.js | 22 ++ .../repositories/push_event/Provider.js | 16 ++ .../repositories/push_event/index.js | 15 ++ .../push_subscriptions/Provider.js | 19 ++ .../repositories/push_subscriptions/index.js | 23 ++ app/providers/repositories/user/Provider.js | 2 +- .../repositories/user_token/Provider.js | 2 +- .../services/cluster_node/Provider.js | 14 ++ app/providers/services/cluster_node/index.js | 33 +++ app/providers/services/contacts/Provider.js | 15 ++ .../services/contacts/index.js} | 196 +++++++-------- .../services/operation_logs/Provider.js | 14 ++ .../services/operation_logs/index.js | 19 ++ .../services/push_notifications/Provider.js | 16 ++ .../services/push_notifications/index.js | 55 +++++ app/repositories/base.js | 5 - app/repositories/file_repository.js | 21 -- app/repositories/operations_log_repository.js | 12 - .../push_notifications_repository.js | 39 --- test/attachments.js | 11 +- test/contacts.js | 4 +- test/operations_log.js | 13 +- test/push_notifications.js | 10 +- 85 files changed, 1098 insertions(+), 734 deletions(-) rename app/{new_models => models}/blocked_user.js (67%) rename app/{new_models => models}/conversation.js (100%) rename app/{new_models => models}/conversation_participants.js (100%) rename app/{new_models => models}/message.js (100%) rename app/{new_models => models}/message_status.js (100%) rename app/{new_models => models}/user.js (100%) rename app/{new_models => models}/user_token.js (69%) delete mode 100644 app/new_models/base.js delete mode 100644 app/new_models/file.js create mode 100644 app/providers/operations/contact/create/Provider.js create mode 100644 app/providers/operations/contact/create/index.js create mode 100644 app/providers/operations/contact/delete/Provider.js create mode 100644 app/providers/operations/contact/delete/index.js create mode 100644 app/providers/operations/contact/edit/Provider.js create mode 100644 app/providers/operations/contact/edit/index.js create mode 100644 app/providers/operations/contact/list/Provider.js create mode 100644 app/providers/operations/contact/list/index.js create mode 100644 app/providers/operations/file/create/Provider.js create mode 100644 app/providers/operations/file/create/index.js create mode 100644 app/providers/operations/file/download/Provider.js create mode 100644 app/providers/operations/file/download/index.js create mode 100644 app/providers/operations/operation_logs/list/Provider.js create mode 100644 app/providers/operations/operation_logs/list/index.js create mode 100644 app/providers/operations/push_notifications/create_event/Provider.js create mode 100644 app/providers/operations/push_notifications/create_event/index.js create mode 100644 app/providers/operations/push_notifications/create_subscription/Provider.js create mode 100644 app/providers/operations/push_notifications/create_subscription/index.js create mode 100644 app/providers/operations/push_notifications/delete_subscription/Provider.js create mode 100644 app/providers/operations/push_notifications/delete_subscription/index.js create mode 100644 app/providers/operations/push_notifications/list_subscriptions/Provider.js create mode 100644 app/providers/operations/push_notifications/list_subscriptions/index.js create mode 100644 app/providers/repositories/cluster_node/Provider.js create mode 100644 app/providers/repositories/cluster_node/index.js create mode 100644 app/providers/repositories/contact/Provider.js create mode 100644 app/providers/repositories/contact/index.js create mode 100644 app/providers/repositories/operations_log/Provider.js create mode 100644 app/providers/repositories/operations_log/index.js create mode 100644 app/providers/repositories/push_event/Provider.js create mode 100644 app/providers/repositories/push_event/index.js create mode 100644 app/providers/repositories/push_subscriptions/Provider.js create mode 100644 app/providers/repositories/push_subscriptions/index.js create mode 100644 app/providers/services/cluster_node/Provider.js create mode 100644 app/providers/services/cluster_node/index.js create mode 100644 app/providers/services/contacts/Provider.js rename app/{repositories/contact_match_repository.js => providers/services/contacts/index.js} (52%) create mode 100644 app/providers/services/operation_logs/Provider.js create mode 100644 app/providers/services/operation_logs/index.js create mode 100644 app/providers/services/push_notifications/Provider.js create mode 100644 app/providers/services/push_notifications/index.js delete mode 100644 app/repositories/base.js delete mode 100644 app/repositories/file_repository.js delete mode 100644 app/repositories/operations_log_repository.js delete mode 100644 app/repositories/push_notifications_repository.js diff --git a/APIs/JSON/controllers/contacts.js b/APIs/JSON/controllers/contacts.js index eb4ed7bc..135264bb 100644 --- a/APIs/JSON/controllers/contacts.js +++ b/APIs/JSON/controllers/contacts.js @@ -1,30 +1,16 @@ import BaseJSONController from "./base.js" -import { ERROR_STATUES } from "@sama/constants/errors.js" - import ServiceLocatorContainer from "@sama/common/ServiceLocatorContainer.js" -import Contact from "@sama/models/contact.js" - -import contactsMatchRepository from "@sama/repositories/contact_match_repository.js" - -import { ObjectId } from "@sama/lib/db.js" - import Response from "@sama/networking/models/Response.js" class ContactsController extends BaseJSONController { async contact_add(ws, data) { const { id: requestId, contact_add: contactData } = data - const sessionService = ServiceLocatorContainer.use("SessionService") - - const currentUser = sessionService.getSessionUserId(ws) - - await contactsMatchRepository.matchContactWithUser(contactData) - contactData.user_id = ObjectId(currentUser) + const contactAddOperation = ServiceLocatorContainer.use("ContactAddOperation") - const contact = new Contact(contactData) - await contact.save() + const contact = await contactAddOperation.perform(ws, contactData, false) return new Response().addBackMessage({ response: { id: requestId, contact: contact.visibleParams() } }) } @@ -35,66 +21,39 @@ class ContactsController extends BaseJSONController { contact_batch_add: { contacts }, } = data - const contactsList = [] - for (let u of contacts) { - if (!u.email || !u.phone) { - continue - } + const contactAddOperation = ServiceLocatorContainer.use("ContactAddOperation") - const contact = (await this.contact_add(ws, { contact_add: u, id: "contact_batch_add" })).backMessages.at(0) - .response.contact - contactsList.push(contact) - } + const contactsList = await contactAddOperation.perform(ws, contacts, true) return new Response().addBackMessage({ response: { id: requestId, contacts: contactsList } }) } async contact_update(ws, data) { const { id: requestId, contact_update: updatedData } = data - const recordId = updatedData.id - delete updatedData["id"] - await contactsMatchRepository.matchContactWithUser(updatedData) + const contactEditOperation = ServiceLocatorContainer.use("ContactEditOperation") - const updatedResult = await Contact.findOneAndUpdate({ _id: recordId }, { $set: updatedData }) + const updatedContact = await contactEditOperation.perform(ws, updatedData) - if (!updatedResult.ok) { - throw new Error(ERROR_STATUES.CONTACT_NOT_FOUND.message, { - cause: ERROR_STATUES.CONTACT_NOT_FOUND, - }) - } - - return new Response().addBackMessage({ response: { id: requestId, contact: updatedResult.value } }) + return new Response().addBackMessage({ response: { id: requestId, contact: updatedContact } }) } async contact_list(ws, data) { const { id: requestId, contact_list: query } = data - const sessionService = ServiceLocatorContainer.use("SessionService") - - const currentUser = sessionService.getSessionUserId(ws).toString() - - const queryParams = { user_id: currentUser.toString() } - if (query.updated_at) { - queryParams.updated_at = { $gt: new Date(query.updated_at) } - } + const contactListOperation = ServiceLocatorContainer.use("ContactListOperation") - const contacts = await Contact.findAll(queryParams, null, query.limit) + const contacts = await contactListOperation.perform(ws, query) return new Response().addBackMessage({ response: { id: requestId, contacts } }) } async contact_delete(ws, data) { - const { - id: requestId, - contact_delete: { id }, - } = data + const { id: requestId, contact_delete } = data - const sessionService = ServiceLocatorContainer.use("SessionService") + const contactDeleteOperation = ServiceLocatorContainer.use("ContactDeleteOperation") - const userId = sessionService.getSessionUserId(ws) - const contact = await Contact.findOne({ _id: id, user_id: userId }) - contact && (await contact.delete()) + await contactDeleteOperation.perform(ws, contact_delete) return new Response().addBackMessage({ response: { id: requestId, success: true } }) } diff --git a/APIs/JSON/controllers/files.js b/APIs/JSON/controllers/files.js index 0501ca3b..92593e15 100644 --- a/APIs/JSON/controllers/files.js +++ b/APIs/JSON/controllers/files.js @@ -6,44 +6,23 @@ import Response from "@sama/networking/models/Response.js" class FilesController extends BaseJSONController { async create_url(ws, data) { - const { id: requestId, create_files: reqFiles } = data + const { id: requestId, create_files } = data - const sessionService = ServiceLocatorContainer.use("SessionService") - const storageService = ServiceLocatorContainer.use("StorageService") + const fileCreateOperation = ServiceLocatorContainer.use("FileCreateOperation") - const currentUserId = sessionService.getSessionUserId(ws) + const createdFiles = await fileCreateOperation.perform(ws, create_files) - const resFiles = [] - - for (const reqFile of reqFiles) { - const { file, upload_url } = await storageService.createFile(currentUserId, reqFile) - - resFiles.push({ ...file, upload_url }) - } - - return new Response().addBackMessage({ response: { id: requestId, files: resFiles } }) + return new Response().addBackMessage({ response: { id: requestId, files: createdFiles } }) } async get_download_url(ws, data) { - const { - id: requestId, - get_file_urls: { file_ids: objectIds }, - } = data - - const sessionService = ServiceLocatorContainer.use("SessionService") - const storageService = ServiceLocatorContainer.use("StorageService") - - const currentUserId = sessionService.getSessionUserId(ws) - - const urls = {} + const { id: requestId, get_file_urls } = data - for (const fileObjectId of objectIds) { - const downloadUrl = await storageService.getFileDownloadUrl(currentUserId, fileObjectId) + const fileDownloadOperation = ServiceLocatorContainer.use("FileDownloadOperation") - urls[fileObjectId] = downloadUrl - } + const downloadUrls = await fileDownloadOperation.perform(ws, get_file_urls) - return new Response().addBackMessage({ response: { id: requestId, file_urls: urls } }) + return new Response().addBackMessage({ response: { id: requestId, file_urls: downloadUrls } }) } } diff --git a/APIs/JSON/controllers/operations_log.js b/APIs/JSON/controllers/operations_log.js index a68ac366..ee58f403 100644 --- a/APIs/JSON/controllers/operations_log.js +++ b/APIs/JSON/controllers/operations_log.js @@ -22,23 +22,12 @@ const mapOpLogsMessage = async function (mapper) { class OperationsLogController extends BaseJSONController { async logs(ws, data) { - const { - id: requestId, - op_log_list: { - created_at: { gt, lt }, - }, - } = data + const { id: requestId, op_log_list } = data - const sessionService = ServiceLocatorContainer.use("SessionService") + const opLogsListOperation = ServiceLocatorContainer.use("OpLogsListOperation") - const currentUserId = sessionService.getSessionUserId(ws) + const opLogs = await opLogsListOperation.perform(ws, op_log_list) - const query = { - user_id: currentUserId, - created_at: gt ? { $gt: new Date(gt) } : { $lt: new Date(lt) }, - } - - const opLogs = await OpLog.findAll(query, ["user_id", "packet"]) const packet = { response: { id: requestId, logs: opLogs } } return new Response().addBackMessage(new MappableMessage(packet, mapOpLogsMessage)) diff --git a/APIs/JSON/controllers/push_notifications.js b/APIs/JSON/controllers/push_notifications.js index 0037acbb..9c911873 100644 --- a/APIs/JSON/controllers/push_notifications.js +++ b/APIs/JSON/controllers/push_notifications.js @@ -1,41 +1,16 @@ import BaseJSONController from "./base.js" -import { ERROR_STATUES } from "@sama/constants/errors.js" - -import RuntimeDefinedContext from "@sama/store/RuntimeDefinedContext.js" import ServiceLocatorContainer from "@sama/common/ServiceLocatorContainer.js" -import PushSubscription from "@sama/models/push_subscription.js" - -import { ObjectId } from "@sama/lib/db.js" - import Response from "@sama/networking/models/Response.js" -import CreatePushEventOptions from "@sama/lib/push_queue/models/CreatePushEventOptions.js" class PushNotificationsController extends BaseJSONController { async push_subscription_create(ws, data) { - const { - id: requestId, - push_subscription_create: { web_endpoint, web_key_auth, web_key_p256dh, device_token, device_udid }, - } = data - - const sessionService = ServiceLocatorContainer.use("SessionService") - - const userId = sessionService.getSessionUserId(ws) - let pushSubscription = new PushSubscription( - ( - await PushSubscription.findOneAndUpdate( - { user_id: userId, device_udid }, - { $set: { web_endpoint, web_key_auth, web_key_p256dh, device_token } } - ) - )?.value - ) - - if (!pushSubscription.params) { - data.push_subscription_create["user_id"] = new ObjectId(userId) - pushSubscription = new PushSubscription(data.push_subscription_create) - await pushSubscription.save() - } + const { id: requestId, push_subscription_create } = data + + const pushSubscriptionCreateOperation = ServiceLocatorContainer.use("PushSubscriptionCreateOperation") + + const pushSubscription = await pushSubscriptionCreateOperation.perform(ws, push_subscription_create) return new Response().addBackMessage({ response: { @@ -46,65 +21,31 @@ class PushNotificationsController extends BaseJSONController { } async push_subscription_list(ws, data) { - const { - id: requestId, - push_subscription_list: { user_id }, - } = data + const { id: requestId } = data + + const pushSubscriptionListOperation = ServiceLocatorContainer.use("PushSubscriptionListOperation") - const subscriptions = await PushSubscription.findAll({ user_id }) + const subscriptions = await pushSubscriptionListOperation.perform(ws, {}) return new Response().addBackMessage({ response: { id: requestId, subscriptions } }) } async push_subscription_delete(ws, data) { - const { - id: requestId, - push_subscription_delete: { device_udid }, - } = data - - const sessionService = ServiceLocatorContainer.use("SessionService") + const { id: requestId, push_subscription_delete } = data - const userId = sessionService.getSessionUserId(ws) - const pushSubscriptionRecord = await PushSubscription.findOne({ - device_udid, - user_id: userId, - }) - if (!pushSubscriptionRecord) { - throw new Error(ERROR_STATUES.NOTIFICATION_NOT_FOUND.message, { - cause: ERROR_STATUES.NOTIFICATION_NOT_FOUND, - }) - } + const pushSubscriptionDeleteOperation = ServiceLocatorContainer.use("PushSubscriptionDeleteOperation") - await pushSubscriptionRecord.delete() + await pushSubscriptionDeleteOperation.perform(ws, push_subscription_delete) return new Response().addBackMessage({ response: { id: requestId, success: true } }) } async push_event_create(ws, data) { - const { - id: requestId, - push_event_create: { recipients_ids, message }, - } = data - - const userService = ServiceLocatorContainer.use("UserService") - - const recipients = await userService.userRepo.retrieveExistedIds(recipients_ids) - - if (!recipients.length) { - throw new Error(ERROR_STATUES.RECIPIENTS_NOT_FOUND.message, { - cause: ERROR_STATUES.RECIPIENTS_NOT_FOUND, - }) - } + const { id: requestId, push_event_create } = data - const sessionService = ServiceLocatorContainer.use("SessionService") - - const userId = sessionService.getSessionUserId(ws) - - const createPushEventOptions = new CreatePushEventOptions(userId, message, { - user_ids: recipients_ids, - }) + const pushEventCreateOperation = ServiceLocatorContainer.use("PushEventCreateOperation") - const pushEvent = await RuntimeDefinedContext.PUSH_QUEUE_DRIVER.createPushEvent(createPushEventOptions) + const pushEvent = await pushEventCreateOperation.perform(ws, push_event_create) return new Response().addBackMessage({ response: { id: requestId, event: pushEvent.visibleParams() } }) } diff --git a/APIs/XMPP b/APIs/XMPP index c3006862..aa7ac7aa 160000 --- a/APIs/XMPP +++ b/APIs/XMPP @@ -1 +1 @@ -Subproject commit c30068629026edbbdc3b86aaccae9be36a717038 +Subproject commit aa7ac7aaffcceefe9bd5e0d89c139678719d77cd diff --git a/app/cluster/cluster_syncer.js b/app/cluster/cluster_syncer.js index a53177d0..498fe16e 100644 --- a/app/cluster/cluster_syncer.js +++ b/app/cluster/cluster_syncer.js @@ -2,8 +2,6 @@ import RuntimeDefinedContext from "../store/RuntimeDefinedContext.js" import clusterManager from "./cluster_manager.js" -import ClusterNode from "../models/cluster_node.js" - import ServiceLocatorContainer from "@sama/common/ServiceLocatorContainer.js" class ClusterSyncer { @@ -31,7 +29,8 @@ class ClusterSyncer { } async #retrieveExistingClusterNodes() { - const nodeList = await ClusterNode.findAll({}, ["ip_address", "hostname", "port"]) + const clusterNodeService = ServiceLocatorContainer.use("ClusterNodeService") + const nodeList = await clusterNodeService.retrieveAll() // initiate connect to other node nodeList.forEach(async (n) => { @@ -52,36 +51,26 @@ class ClusterSyncer { // if some node is gone, we may need to do some cleaning ? } - async #storeCurrentNode({ ip_address, hostname, port, users_count }) { - if (await ClusterNode.findOne({ ip_address, hostname, port })) { - await ClusterNode.updateOne( - { ip_address, hostname, port }, - { - $set: { updated_at: new Date(), users_count }, - } - ) - } else { - const newNode = new ClusterNode({ - ip_address, - hostname, - port, - users_count, - }) - await newNode.save() - } - } - - async #syncCluster() { - const sessionService = ServiceLocatorContainer.use("SessionService") + async #storeCurrentNode(usersCount) { + const clusterNodeService = ServiceLocatorContainer.use("ClusterNodeService") - const clusterNodeParams = { + const addressParams = { ip_address: RuntimeDefinedContext.APP_IP, hostname: RuntimeDefinedContext.APP_HOSTNAME, port: RuntimeDefinedContext.CLUSTER_PORT, - users_count: sessionService.sessionsTotal, } - await this.#storeCurrentNode(clusterNodeParams) + const optionalParams = { + users_count: usersCount, + } + + await clusterNodeService.create(addressParams, optionalParams) + } + + async #syncCluster() { + const sessionService = ServiceLocatorContainer.use("SessionService") + + await this.#storeCurrentNode(sessionService.sessionsTotal) await this.#retrieveExistingClusterNodes() } diff --git a/app/lib/push_queue/base.js b/app/lib/push_queue/base.js index a8eafd80..bffef532 100644 --- a/app/lib/push_queue/base.js +++ b/app/lib/push_queue/base.js @@ -1,22 +1,21 @@ -import pushNotificationsRepository from "../../repositories/push_notifications_repository.js" +import ServiceLocatorContainer from "@sama/common/ServiceLocatorContainer.js" import CreateChatAlertEventOptions from "./models/CreateChatAlertEventOptions.js" import CreatePushEventOptions from "./models/CreatePushEventOptions.js" export default class BasePushQueue { async buildPushEvent(createPushEventOptions) { - const pushEvent = await pushNotificationsRepository.createPushEvent( - createPushEventOptions.user_id, - createPushEventOptions.user_ids, - createPushEventOptions.payload, - {} - ) + const pushEventRepository = ServiceLocatorContainer.use("PushEventRepository") + + const pushEvent = await pushEventRepository.create(createPushEventOptions) return pushEvent } async getSubscriptionsByUid(user_id) { - return await pushNotificationsRepository.getSubscriptionsByUid(user_id) + const pushSubscriptionRepo = ServiceLocatorContainer.use("PushSubscriptionsRepository") + + return await pushSubscriptionRepo.findAll({ user_id: user_id }) } async createPush(pushQueueMessage) { diff --git a/app/models/base.js b/app/models/base.js index 78dfa63c..3669f879 100644 --- a/app/models/base.js +++ b/app/models/base.js @@ -1,10 +1,9 @@ -import { getDb, ObjectId } from "../lib/db.js" import { slice } from "../utils/req_res_utils.js" -export default class BaseModel { - constructor(params) { - this.params = params - this.hooks = {} +class BaseModel { + constructor(params, mappedParams) { + this.params = params ?? {} + this.mappedParams = mappedParams ?? {} } static get collection() { @@ -15,205 +14,54 @@ export default class BaseModel { throw new Error("Not implemented") } - async save() { - if (this.hooks.beforeSave) { - await this.hooks.beforeSave() - } - - const currentDate = new Date() - const insertParams = { - ...this.params, - created_at: currentDate, - updated_at: currentDate, - } - - try { - const result = await getDb().collection(this.constructor.collection).insertOne(insertParams) - this.params = { _id: result.insertedId, ...insertParams } - } catch (e) { - return e - } - } - - static async insertMany(data) { - try { - const currentDate = new Date() - await getDb() - .collection(this.collection) - .insertMany( - data.map((obj) => { - return { ...obj, created_at: currentDate, updated_at: currentDate } - }) - ) - } catch (e) { - return e - } - } - - static async findAll(query, returnParams, limit, sortParams) { - try { - if (query.cid) { - query.cid = new ObjectId(query.cid) - } - if (query._id) { - query._id.$nin && (query._id.$nin = query._id.$nin.map((id) => new ObjectId(id))) - query._id.$in && (query._id.$in = query._id.$in.map((id) => new ObjectId(id))) - } - if (query.user_id && !query.user_id.$ne) { - query.user_id.$in - ? (query.user_id.$in = query.user_id.$in.map((id) => new ObjectId(id))) - : (query.user_id = new ObjectId(query.user_id)) - } - if (query.conversation_id) { - query.conversation_id.$in - ? (query.conversation_id.$in = query.conversation_id.$in.map((id) => new ObjectId(id))) - : (query.conversation_id = new ObjectId(query.conversation_id)) - } - if (query.from?.$ne) { - query.from.$ne = new ObjectId(query.from.$ne) - } - - const projection = returnParams?.reduce((acc, p) => { - return { ...acc, [p]: 1 } - }, {}) - - return await getDb() - .collection(this.collection) - .find(query, { limit: limit || 100 }) - .project(projection) - .sort(sortParams || { $natural: -1 }) - .toArray() - } catch (e) { - return null - } - } - - static async findOne(query) { - try { - if (query._id) { - query._id = new ObjectId(query._id) - } - if (query.user_id) { - query.user_id = new ObjectId(query.user_id) - } - if (query.conversation_id) { - query.conversation_id = new ObjectId(query.conversation_id) - } - - const record = await getDb().collection(this.collection).findOne(query) - const obj = record ? new this(record) : null - return obj - } catch (e) { - return null - } - } - - static async clearCollection() { - try { - await getDb().collection(this.collection).deleteMany({}) - } catch (e) { - return null - } + static get originalFields() { + throw new Error("Not implemented") } - static async count(query) { - try { - if (query.conversation_id) { - query.conversation_id = new ObjectId(query.conversation_id) - } - if (query.user_id && !query.user_id.$ne) { - query.user_id = new ObjectId(query.user_id) - } - if (query.user_id?.$ne) { - query.user_id.$ne = new ObjectId(query.user_id.$ne) - } - if (query.from?.$ne) { - query.from.$ne = new ObjectId(query.from.$ne) - } - return await getDb().collection(this.collection).count(query) - } catch (e) { - return null - } + visibleParams() { + return slice(this, this.constructor.visibleFields) } - static async updateOne(query, update) { - try { - if (query._id) { - query._id = new ObjectId(query._id) - } - return await getDb().collection(this.collection).updateOne(query, update) - } catch (e) { - return null - } + set(propName, value) { + return (this.mappedParams[propName] = value) } - static async findOneAndUpdate(query, update) { - try { - if (query._id) { - query._id = new ObjectId(query._id) - } - if (query.user_id) { - query.user_id = new ObjectId(query.user_id) - } - return await getDb().collection(this.collection).findOneAndUpdate(query, update, { returnDocument: "after" }) - } catch (e) { - return e - } - } + static createInstance(...params) { + const origModel = new this(...params) - static async updateMany(query, update) { - try { - return await getDb().collection(this.collection).updateMany(query, update) - } catch (e) { - return null - } - } + const proxyModel = new Proxy(origModel, { + get(model, propName) { + const origVal = model[propName] + if (origVal !== void 0) { + return origVal + } - static async getAllIdsBy(query) { - try { - if (query) { - query._id.$in = query._id.$in.map((id) => new ObjectId(id)) - } - const obj = [] - await getDb() - .collection(this.collection) - .find(query) - .project({ _id: 1 }) - .forEach((el) => { - obj.push(el._id) - }) - return obj - } catch (e) { - return null - } - } + if (propName in model.mappedParams) { + return model.mappedParams[propName] + } - static async aggregate(query) { - try { - return await getDb().collection(this.collection).aggregate(query).toArray() - } catch (e) { - console.log(e) - return null - } - } + if (propName in model.params) { + return model.params[propName] + } - async delete() { - await getDb().collection(this.constructor.collection).deleteOne({ _id: this.params._id }) - } + return model[propName] + }, - static async deleteMany(query) { - try { - return await getDb().collection(this.collection).deleteMany(query) - } catch (e) { - return null - } - } + ownKeys(model) { + const keys = Object.keys(model.mappedParams).concat(Object.keys(model.params)) + return [...new Set(keys)] + }, - toJSON() { - return JSON.stringify(this.visibleParams()) - } + getOwnPropertyDescriptor(model) { + return { + enumerable: true, + configurable: true, + } + }, + }) - visibleParams() { - return slice(this.params, this.constructor.visibleFields) + return proxyModel } } + +export default BaseModel diff --git a/app/new_models/blocked_user.js b/app/models/blocked_user.js similarity index 67% rename from app/new_models/blocked_user.js rename to app/models/blocked_user.js index ad41d106..de285637 100644 --- a/app/new_models/blocked_user.js +++ b/app/models/blocked_user.js @@ -6,6 +6,6 @@ export default class BlockedUser extends BaseModel { } static get visibleFields() { - return ["_id", "created_at", "updated_at", "enabled", "user_id", "blocked_user_id"] + return ["_id", "enabled", "user_id", "blocked_user_id", "created_at", "updated_at"] } } diff --git a/app/models/cluster_node.js b/app/models/cluster_node.js index a5fac6eb..5c9f4086 100644 --- a/app/models/cluster_node.js +++ b/app/models/cluster_node.js @@ -1,15 +1,11 @@ import BaseModel from "./base.js" export default class ClusterNode extends BaseModel { - constructor(params) { - super(params) - } - static get collection() { return "cluster_nodes" } static get visibleFields() { - return ["_id", "created_at", "updated_at", "ip_address", "hostname", "port", "users_count"] + return ["_id", "ip_address", "hostname", "port", "users_count", "created_at", "updated_at"] } } diff --git a/app/models/contact.js b/app/models/contact.js index 6984c4e2..216e5b27 100644 --- a/app/models/contact.js +++ b/app/models/contact.js @@ -1,10 +1,6 @@ import BaseModel from "./base.js" export default class Contact extends BaseModel { - constructor(params) { - super(params) - } - static get collection() { return "contacts" } diff --git a/app/new_models/conversation.js b/app/models/conversation.js similarity index 100% rename from app/new_models/conversation.js rename to app/models/conversation.js diff --git a/app/new_models/conversation_participants.js b/app/models/conversation_participants.js similarity index 100% rename from app/new_models/conversation_participants.js rename to app/models/conversation_participants.js diff --git a/app/models/file.js b/app/models/file.js index 5bf9b1d6..0b26e2a0 100644 --- a/app/models/file.js +++ b/app/models/file.js @@ -1,15 +1,13 @@ import BaseModel from "./base.js" -export default class File extends BaseModel { - constructor(params) { - super(params) - } - +class File extends BaseModel { static get collection() { return "files" } static get visibleFields() { - return ["_id", "name", "size", "content_type", "object_id"] + return ["_id", "name", "size", "content_type", "object_id", "created_at", "updated_at"] } } + +export default File diff --git a/app/new_models/message.js b/app/models/message.js similarity index 100% rename from app/new_models/message.js rename to app/models/message.js diff --git a/app/new_models/message_status.js b/app/models/message_status.js similarity index 100% rename from app/new_models/message_status.js rename to app/models/message_status.js diff --git a/app/models/operations_log.js b/app/models/operations_log.js index e5b8b626..4579072c 100644 --- a/app/models/operations_log.js +++ b/app/models/operations_log.js @@ -1,15 +1,11 @@ import BaseModel from "./base.js" export default class OpLog extends BaseModel { - constructor(params) { - super(params) - } - static get collection() { return "operations_log" } static get visibleFields() { - return ["_id", "created_at", "updated_at", "user_id", "packet"] + return ["_id", "user_id", "packet", "created_at", "updated_at"] } } diff --git a/app/models/push_event.js b/app/models/push_event.js index 225c6a10..24bd13e7 100644 --- a/app/models/push_event.js +++ b/app/models/push_event.js @@ -1,14 +1,11 @@ -import BaseModel from "@sama/models/base.js" +import BaseModel from "./base.js" export default class PushEvent extends BaseModel { - constructor(params) { - super(params) - } static get collection() { return "push_events" } static get visibleFields() { - return ["_id", "created_at", "updated_at", "platform", "user_id", "user_ids", "message"] + return ["_id", "platform", "user_id", "user_ids", "message", "created_at", "updated_at"] } } diff --git a/app/models/push_subscription.js b/app/models/push_subscription.js index ef1614f6..b819d28b 100644 --- a/app/models/push_subscription.js +++ b/app/models/push_subscription.js @@ -1,9 +1,6 @@ -import BaseModel from "@sama/models/base.js" +import BaseModel from "./base.js" export default class PushSubscription extends BaseModel { - constructor(params) { - super(params) - } static get collection() { return "push_subscriptions" } @@ -11,8 +8,7 @@ export default class PushSubscription extends BaseModel { static get visibleFields() { return [ "_id", - "created_at", - "updated_at", + "user_id", "platform", "web_endpoint", @@ -20,6 +16,9 @@ export default class PushSubscription extends BaseModel { "web_key_p256dh", "device_udid", "device_token", + + "created_at", + "updated_at", ] } } diff --git a/app/new_models/user.js b/app/models/user.js similarity index 100% rename from app/new_models/user.js rename to app/models/user.js diff --git a/app/new_models/user_token.js b/app/models/user_token.js similarity index 69% rename from app/new_models/user_token.js rename to app/models/user_token.js index 3e9dd272..da75cb0a 100644 --- a/app/new_models/user_token.js +++ b/app/models/user_token.js @@ -6,6 +6,6 @@ export default class UserToken extends BaseModel { } static get visibleFields() { - return ["_id", "created_at", "updated_at", "user_id", "device_id", "token"] + return ["_id", "user_id", "device_id", "token", "created_at", "updated_at"] } } diff --git a/app/networking/packet_manager.js b/app/networking/packet_manager.js index 5e41c52c..c12a28e2 100644 --- a/app/networking/packet_manager.js +++ b/app/networking/packet_manager.js @@ -2,8 +2,6 @@ import RuntimeDefinedContext from "../store/RuntimeDefinedContext.js" import ServiceLocatorContainer from "@sama/common/ServiceLocatorContainer.js" -import operationsLogRepository from "../repositories/operations_log_repository.js" - import clusterManager from "../cluster/cluster_manager.js" import packetMapper from "./packet_mapper.js" @@ -89,6 +87,7 @@ class PacketManager { async deliverToUserOrUsers(ws, packet, pushQueueMessage, usersIds, notSaveInOfflineStorage) { const sessionService = ServiceLocatorContainer.use("SessionService") + const opLogsService = ServiceLocatorContainer.use("OperationLogsService") if (!usersIds?.length) { return @@ -102,7 +101,7 @@ class PacketManager { if (isNoConnections) { if (!notSaveInOfflineStorage) { - operationsLogRepository.savePacket(userId, packet) + opLogsService.savePacket(userId, packet) } offlineUsersByPackets.push(userId) diff --git a/app/new_models/base.js b/app/new_models/base.js deleted file mode 100644 index 3669f879..00000000 --- a/app/new_models/base.js +++ /dev/null @@ -1,67 +0,0 @@ -import { slice } from "../utils/req_res_utils.js" - -class BaseModel { - constructor(params, mappedParams) { - this.params = params ?? {} - this.mappedParams = mappedParams ?? {} - } - - static get collection() { - throw new Error("Not implemented") - } - - static get visibleFields() { - throw new Error("Not implemented") - } - - static get originalFields() { - throw new Error("Not implemented") - } - - visibleParams() { - return slice(this, this.constructor.visibleFields) - } - - set(propName, value) { - return (this.mappedParams[propName] = value) - } - - static createInstance(...params) { - const origModel = new this(...params) - - const proxyModel = new Proxy(origModel, { - get(model, propName) { - const origVal = model[propName] - if (origVal !== void 0) { - return origVal - } - - if (propName in model.mappedParams) { - return model.mappedParams[propName] - } - - if (propName in model.params) { - return model.params[propName] - } - - return model[propName] - }, - - ownKeys(model) { - const keys = Object.keys(model.mappedParams).concat(Object.keys(model.params)) - return [...new Set(keys)] - }, - - getOwnPropertyDescriptor(model) { - return { - enumerable: true, - configurable: true, - } - }, - }) - - return proxyModel - } -} - -export default BaseModel diff --git a/app/new_models/file.js b/app/new_models/file.js deleted file mode 100644 index e9a422a7..00000000 --- a/app/new_models/file.js +++ /dev/null @@ -1,13 +0,0 @@ -import BaseModel from "./base.js" - -class File extends BaseModel { - static get collection() { - return "files" - } - - static get visibleFields() { - return ["_id", "created_at", "updated_at", "name", "size", "content_type", "object_id"] - } -} - -export default File diff --git a/app/providers/index.js b/app/providers/index.js index 56d2419d..03fe6005 100644 --- a/app/providers/index.js +++ b/app/providers/index.js @@ -5,6 +5,7 @@ import UserMapperProvider from "./utils/mappers/user/Provider.js" import ConversationMapperProvider from "./utils/mappers/conversation/Provider.js" import MessageMapperProvider from "./utils/mappers/message/Provider.js" +import ClusterNodeRepositoryProvider from "./repositories/cluster_node/Provider.js" import UserRepoProvider from "./repositories/user/Provider.js" import UserTokenRepoProvider from "./repositories/user_token/Provider.js" import BlockedUserRepoProvider from "./repositories/blocked_user/Provider.js" @@ -13,15 +14,23 @@ import ConversationRepoProvider from "./repositories/conversation/Provider.js" import ConversationParticipantRepoProvider from "./repositories/conversation_participants/Provider.js" import MessageRepoProvider from "./repositories/message/Provider.js" import MessageStatusRepoProvider from "./repositories/message_status/Provider.js" +import ContactRepositoryProvider from "./repositories/contact/Provider.js" +import OperationsLogRepositoryProvider from "./repositories/operations_log/Provider.js" +import PushEventRepositoryProvider from "./repositories/push_event/Provider.js" +import PushSubscriptionRepositoryProvider from "./repositories/push_subscriptions/Provider.js" +import ClusterNodeServiceProvider from "./services/cluster_node/Provider.js" import SessionServiceProvider from "./services/session/Provider.js" import UserServiceProvider from "./services/user/Provider.js" import BlockListServiceProvider from "./services/block_list/Provider.js" import StorageServiceProvider from "./services/storage/Provider.js" +import OperationsLogServiceProvider from "./services/operation_logs/Provider.js" import ActivityManagerServiceProvider from "./services/activity_manager/Provider.js" import ConversationServiceProvider from "./services/conversation/Provider.js" import MessageServiceProvider from "./services/message/Provider.js" import ConversationNotificationProvider from "./services/conversation_notification/Provider.js" +import ContactServiceProvider from "./services/contacts/Provider.js" +import PushNotificationServiceProvider from "./services/push_notifications/Provider.js" import UserAuthOperationProvider from "./operations/user/auth/Provider.js" import UserLogoutOperationProvider from "./operations/user/logout/Provider.js" @@ -37,6 +46,9 @@ import BlockListUnblockOperationProvider from "./operations/block_list/unblock/P import BlockListEnableOperationProvider from "./operations/block_list/enable/Provider.js" import BlockListRetrieveOperationProvider from "./operations/block_list/list/Provider.js" +import FileCreateOperationProvider from "./operations/file/create/Provider.js" +import FileDownloadOperationProvider from "./operations/file/download/Provider.js" + import ActivityUserRetrieveOperationProvider from "./operations/activity/retrieve/Provider.js" import ActivityUserSubscribeOperationProvider from "./operations/activity/subscribe/Provider.js" import ActivityUserUnsubscribeOperationProvider from "./operations/activity/unsubscribe/Provider.js" @@ -55,8 +67,20 @@ import MessageDeleteOperationProvider from "./operations/message/delete/Provider import MessageListOperationProvider from "./operations/message/list/Provider.js" import MessageSendSystemOperationProvider from "./operations/message/system/Provider.js" +import OpLogsListOperationProvider from "./operations/operation_logs/list/Provider.js" + import StatusTypingOperationProvider from "./operations/status/typing/Provider.js" +import ContactCreateOperationProvider from "./operations/contact/create/Provider.js" +import ContactEditOperationProvider from "./operations/contact/edit/Provider.js" +import ContactListOperationProvider from "./operations/contact/list/Provider.js" +import ContactDeleteOperationProvider from "./operations/contact/delete/Provider.js" + +import PushEventCreateOperationProvider from "./operations/push_notifications/create_event/Provider.js" +import PushSubscriptionCreateOperationProvider from "./operations/push_notifications/create_subscription/Provider.js" +import PushSubscriptionDeleteOperationProvider from "./operations/push_notifications/delete_subscription/Provider.js" +import PushSubscriptionListOperationProvider from "./operations/push_notifications/list_subscriptions/Provider.js" + const providers = [ HelpersProvider, @@ -65,6 +89,7 @@ const providers = [ ConversationMapperProvider, MessageMapperProvider, + ClusterNodeRepositoryProvider, UserRepoProvider, UserTokenRepoProvider, BlockedUserRepoProvider, @@ -73,15 +98,23 @@ const providers = [ ConversationParticipantRepoProvider, MessageRepoProvider, MessageStatusRepoProvider, + ContactRepositoryProvider, + OperationsLogRepositoryProvider, + PushEventRepositoryProvider, + PushSubscriptionRepositoryProvider, + ClusterNodeServiceProvider, SessionServiceProvider, UserServiceProvider, BlockListServiceProvider, StorageServiceProvider, + OperationsLogServiceProvider, ActivityManagerServiceProvider, ConversationServiceProvider, MessageServiceProvider, ConversationNotificationProvider, + ContactServiceProvider, + PushNotificationServiceProvider, UserAuthOperationProvider, UserLogoutOperationProvider, @@ -97,6 +130,9 @@ const providers = [ BlockListEnableOperationProvider, BlockListRetrieveOperationProvider, + FileCreateOperationProvider, + FileDownloadOperationProvider, + ActivityUserRetrieveOperationProvider, ActivityUserSubscribeOperationProvider, ActivityUserUnsubscribeOperationProvider, @@ -115,7 +151,19 @@ const providers = [ MessageListOperationProvider, MessageSendSystemOperationProvider, + OpLogsListOperationProvider, + StatusTypingOperationProvider, + + ContactCreateOperationProvider, + ContactEditOperationProvider, + ContactListOperationProvider, + ContactDeleteOperationProvider, + + PushEventCreateOperationProvider, + PushSubscriptionCreateOperationProvider, + PushSubscriptionDeleteOperationProvider, + PushSubscriptionListOperationProvider, ] export default providers diff --git a/app/providers/operations/contact/create/Provider.js b/app/providers/operations/contact/create/Provider.js new file mode 100644 index 00000000..2d96dac5 --- /dev/null +++ b/app/providers/operations/contact/create/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import ContactAddOperation from "./index.js" + +const name = "ContactAddOperation" + +class ContactAddOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const contactService = slc.use("ContactService") + + return new ContactAddOperation(sessionService, contactService) + } +} + +export default new ContactAddOperationRegisterProvider({ name, implementationName: ContactAddOperation.name }) diff --git a/app/providers/operations/contact/create/index.js b/app/providers/operations/contact/create/index.js new file mode 100644 index 00000000..7631765c --- /dev/null +++ b/app/providers/operations/contact/create/index.js @@ -0,0 +1,43 @@ +class ContactAddOperation { + constructor(sessionService, contactService) { + this.sessionService = sessionService + this.contactService = contactService + } + + async perform(ws, contactData, isBatch) { + const currentUserId = this.sessionService.getSessionUserId(ws) + + if (!isBatch) { + return this.singleAdd(currentUserId, contactData) + } else { + return this.batchAdd(currentUserId, contactData) + } + } + + async singleAdd(currentUserId, contactData) { + await this.contactService.matchContactWithUser(contactData) + contactData.user_id = currentUserId + + const contact = await this.contactService.create(contactData) + + return contact + } + + async batchAdd(currentUserId, contactsData) { + const contactsList = [] + + for (const contactData of contactsData) { + if (!contactData.email || !contactData.phone) { + continue + } + + const contact = await this.singleAdd(currentUserId, contactData) + + contactsList.push(contact) + } + + return contactsList + } +} + +export default ContactAddOperation diff --git a/app/providers/operations/contact/delete/Provider.js b/app/providers/operations/contact/delete/Provider.js new file mode 100644 index 00000000..b22c1524 --- /dev/null +++ b/app/providers/operations/contact/delete/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import ContactDeleteOperation from "./index.js" + +const name = "ContactDeleteOperation" + +class ContactDeleteOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const contactService = slc.use("ContactService") + + return new ContactDeleteOperation(sessionService, contactService) + } +} + +export default new ContactDeleteOperationRegisterProvider({ name, implementationName: ContactDeleteOperation.name }) diff --git a/app/providers/operations/contact/delete/index.js b/app/providers/operations/contact/delete/index.js new file mode 100644 index 00000000..87a4aa20 --- /dev/null +++ b/app/providers/operations/contact/delete/index.js @@ -0,0 +1,15 @@ +class ContactDeleteOperation { + constructor(sessionService, contactService) { + this.sessionService = sessionService + this.contactService = contactService + } + + async perform(ws, contactDeleteOptions) { + const { id } = contactDeleteOptions + const userId = this.sessionService.getSessionUserId(ws) + + await this.contactService.delete(userId, id) + } +} + +export default ContactDeleteOperation diff --git a/app/providers/operations/contact/edit/Provider.js b/app/providers/operations/contact/edit/Provider.js new file mode 100644 index 00000000..56a2e35c --- /dev/null +++ b/app/providers/operations/contact/edit/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import ContactEditOperation from "./index.js" + +const name = "ContactEditOperation" + +class ContactEditOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const contactService = slc.use("ContactService") + + return new ContactEditOperation(sessionService, contactService) + } +} + +export default new ContactEditOperationRegisterProvider({ name, implementationName: ContactEditOperation.name }) diff --git a/app/providers/operations/contact/edit/index.js b/app/providers/operations/contact/edit/index.js new file mode 100644 index 00000000..d715ac22 --- /dev/null +++ b/app/providers/operations/contact/edit/index.js @@ -0,0 +1,27 @@ +import { ERROR_STATUES } from "../../../../constants/errors.js" + +class ContactEditOperation { + constructor(sessionService, contactService) { + this.sessionService = sessionService + this.contactService = contactService + } + + async perform(ws, contactUpdate) { + const contactId = contactUpdate.id + delete contactUpdate["id"] + + await this.contactService.matchContactWithUser(contactUpdate) + + const updatedContact = await this.contactService.findByIdAndUpdate(contactId, contactUpdate) + + if (!updatedContact) { + throw new Error(ERROR_STATUES.CONTACT_NOT_FOUND.message, { + cause: ERROR_STATUES.CONTACT_NOT_FOUND, + }) + } + + return updatedContact + } +} + +export default ContactEditOperation diff --git a/app/providers/operations/contact/list/Provider.js b/app/providers/operations/contact/list/Provider.js new file mode 100644 index 00000000..82cf6dfc --- /dev/null +++ b/app/providers/operations/contact/list/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import ContactListOperation from "./index.js" + +const name = "ContactListOperation" + +class ContactListOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const contactService = slc.use("ContactService") + + return new ContactListOperation(sessionService, contactService) + } +} + +export default new ContactListOperationRegisterProvider({ name, implementationName: ContactListOperation.name }) diff --git a/app/providers/operations/contact/list/index.js b/app/providers/operations/contact/list/index.js new file mode 100644 index 00000000..80293682 --- /dev/null +++ b/app/providers/operations/contact/list/index.js @@ -0,0 +1,18 @@ +class ContactListOperation { + constructor(sessionService, contactService) { + this.sessionService = sessionService + this.contactService = contactService + } + + async perform(ws, options) { + const currentUserId = this.sessionService.getSessionUserId(ws) + + const { limit, ...queryParams } = options + + const contacts = await this.contactService.list(currentUserId, queryParams, limit) + + return contacts + } +} + +export default ContactListOperation diff --git a/app/providers/operations/file/create/Provider.js b/app/providers/operations/file/create/Provider.js new file mode 100644 index 00000000..786043c1 --- /dev/null +++ b/app/providers/operations/file/create/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import FileCreateOperation from "./index.js" + +const name = "FileCreateOperation" + +class FileCreateOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const storageService = slc.use("StorageService") + + return new FileCreateOperation(sessionService, storageService) + } +} + +export default new FileCreateOperationRegisterProvider({ name, implementationName: FileCreateOperation.name }) diff --git a/app/providers/operations/file/create/index.js b/app/providers/operations/file/create/index.js new file mode 100644 index 00000000..16cdf0e8 --- /dev/null +++ b/app/providers/operations/file/create/index.js @@ -0,0 +1,22 @@ +class FileCreateOperation { + constructor(sessionService, storageService) { + this.sessionService = sessionService + this.storageService = storageService + } + + async perform(ws, createFiles) { + const currentUserId = this.sessionService.getSessionUserId(ws) + + const fileUploadInfo = [] + + for (const createFile of createFiles) { + const { file, upload_url } = await this.storageService.createFile(currentUserId, createFile) + + fileUploadInfo.push({ ...file, upload_url }) + } + + return fileUploadInfo + } +} + +export default FileCreateOperation diff --git a/app/providers/operations/file/download/Provider.js b/app/providers/operations/file/download/Provider.js new file mode 100644 index 00000000..d8806281 --- /dev/null +++ b/app/providers/operations/file/download/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import FileDownloadOperation from "./index.js" + +const name = "FileDownloadOperation" + +class FileDownloadOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const storageService = slc.use("StorageService") + + return new FileDownloadOperation(sessionService, storageService) + } +} + +export default new FileDownloadOperationRegisterProvider({ name, implementationName: FileDownloadOperation.name }) diff --git a/app/providers/operations/file/download/index.js b/app/providers/operations/file/download/index.js new file mode 100644 index 00000000..ecb02118 --- /dev/null +++ b/app/providers/operations/file/download/index.js @@ -0,0 +1,24 @@ +class FileDownloadOperation { + constructor(sessionService, storageService) { + this.sessionService = sessionService + this.storageService = storageService + } + + async perform(ws, files) { + const { file_ids: objectIds } = files + + const currentUserId = this.sessionService.getSessionUserId(ws) + + const downloadUrls = {} + + for (const fileObjectId of objectIds) { + const downloadUrl = await this.storageService.getFileDownloadUrl(currentUserId, fileObjectId) + + downloadUrls[fileObjectId] = downloadUrl + } + + return downloadUrls + } +} + +export default FileDownloadOperation diff --git a/app/providers/operations/operation_logs/list/Provider.js b/app/providers/operations/operation_logs/list/Provider.js new file mode 100644 index 00000000..1dd9e72b --- /dev/null +++ b/app/providers/operations/operation_logs/list/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import OpLogsListOperation from "./index.js" + +const name = "OpLogsListOperation" + +class OpLogsListOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const opLogsService = slc.use("OperationLogsService") + + return new OpLogsListOperation(sessionService, opLogsService) + } +} + +export default new OpLogsListOperationRegisterProvider({ name, implementationName: OpLogsListOperation.name }) diff --git a/app/providers/operations/operation_logs/list/index.js b/app/providers/operations/operation_logs/list/index.js new file mode 100644 index 00000000..08bd0352 --- /dev/null +++ b/app/providers/operations/operation_logs/list/index.js @@ -0,0 +1,18 @@ +class OpLogsListOperation { + constructor(sessionService, opLogsService) { + this.sessionService = sessionService + this.opLogsService = opLogsService + } + + async perform(ws, opLogListOptions) { + const { created_at } = opLogListOptions + + const currentUserId = this.sessionService.getSessionUserId(ws) + + const opLogs = await this.opLogsService.list(currentUserId, created_at) + + return opLogs + } +} + +export default OpLogsListOperation diff --git a/app/providers/operations/push_notifications/create_event/Provider.js b/app/providers/operations/push_notifications/create_event/Provider.js new file mode 100644 index 00000000..7dd91377 --- /dev/null +++ b/app/providers/operations/push_notifications/create_event/Provider.js @@ -0,0 +1,16 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import PushEventCreateOperation from "./index.js" + +const name = "PushEventCreateOperation" + +class PushEventCreateOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const userService = slc.use("UserService") + const pushNotificationService = slc.use("PushNotificationService") + + return new PushEventCreateOperation(sessionService, userService, pushNotificationService) + } +} + +export default new PushEventCreateOperationRegisterProvider({ name, implementationName: PushEventCreateOperation.name }) diff --git a/app/providers/operations/push_notifications/create_event/index.js b/app/providers/operations/push_notifications/create_event/index.js new file mode 100644 index 00000000..6e4825af --- /dev/null +++ b/app/providers/operations/push_notifications/create_event/index.js @@ -0,0 +1,29 @@ +import { ERROR_STATUES } from "../../../../constants/errors.js" + +class PushEventCreateOperation { + constructor(sessionService, userService, pushNotificationService) { + this.sessionService = sessionService + this.userService = userService + this.pushNotificationService = pushNotificationService + } + + async perform(ws, createPushEventParams) { + const { recipients_ids, message } = createPushEventParams + + const currentUserId = this.sessionService.getSessionUserId(ws) + + const recipients = await this.userService.userRepo.retrieveExistedIds(recipients_ids) + + if (!recipients.length) { + throw new Error(ERROR_STATUES.RECIPIENTS_NOT_FOUND.message, { + cause: ERROR_STATUES.RECIPIENTS_NOT_FOUND, + }) + } + + const pushEvent = await this.pushNotificationService.createEvent(currentUserId, recipients_ids, message) + + return pushEvent + } +} + +export default PushEventCreateOperation diff --git a/app/providers/operations/push_notifications/create_subscription/Provider.js b/app/providers/operations/push_notifications/create_subscription/Provider.js new file mode 100644 index 00000000..c0d7dc2c --- /dev/null +++ b/app/providers/operations/push_notifications/create_subscription/Provider.js @@ -0,0 +1,18 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import PushSubscriptionCreateOperation from "./index.js" + +const name = "PushSubscriptionCreateOperation" + +class PushSubscriptionCreateOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const pushNotificationService = slc.use("PushNotificationService") + + return new PushSubscriptionCreateOperation(sessionService, pushNotificationService) + } +} + +export default new PushSubscriptionCreateOperationRegisterProvider({ + name, + implementationName: PushSubscriptionCreateOperation.name, +}) diff --git a/app/providers/operations/push_notifications/create_subscription/index.js b/app/providers/operations/push_notifications/create_subscription/index.js new file mode 100644 index 00000000..8d038eff --- /dev/null +++ b/app/providers/operations/push_notifications/create_subscription/index.js @@ -0,0 +1,22 @@ +class PushSubscriptionCreateOperation { + constructor(sessionService, pushNotificationService) { + this.sessionService = sessionService + this.pushNotificationService = pushNotificationService + } + + async perform(ws, createSubscriptionParams) { + const { device_udid } = createSubscriptionParams + + const currentUserId = this.sessionService.getSessionUserId(ws) + + const upsertSubscription = await this.pushNotificationService.upsertSubscription( + currentUserId, + device_udid, + createSubscriptionParams + ) + + return upsertSubscription + } +} + +export default PushSubscriptionCreateOperation diff --git a/app/providers/operations/push_notifications/delete_subscription/Provider.js b/app/providers/operations/push_notifications/delete_subscription/Provider.js new file mode 100644 index 00000000..be32320f --- /dev/null +++ b/app/providers/operations/push_notifications/delete_subscription/Provider.js @@ -0,0 +1,18 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import PushSubscriptionDeleteOperation from "./index.js" + +const name = "PushSubscriptionDeleteOperation" + +class PushSubscriptionDeleteOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const pushNotificationService = slc.use("PushNotificationService") + + return new PushSubscriptionDeleteOperation(sessionService, pushNotificationService) + } +} + +export default new PushSubscriptionDeleteOperationRegisterProvider({ + name, + implementationName: PushSubscriptionDeleteOperation.name, +}) diff --git a/app/providers/operations/push_notifications/delete_subscription/index.js b/app/providers/operations/push_notifications/delete_subscription/index.js new file mode 100644 index 00000000..0a731df7 --- /dev/null +++ b/app/providers/operations/push_notifications/delete_subscription/index.js @@ -0,0 +1,24 @@ +import { ERROR_STATUES } from "../../../../constants/errors.js" + +class PushSubscriptionDeleteOperation { + constructor(sessionService, pushNotificationService) { + this.sessionService = sessionService + this.pushNotificationService = pushNotificationService + } + + async perform(ws, createSubscriptionParams) { + const { device_udid } = createSubscriptionParams + + const currentUserId = this.sessionService.getSessionUserId(ws) + + const subscription = await this.pushNotificationService.findAndDeleteSubscription(currentUserId, device_udid) + + if (!subscription) { + throw new Error(ERROR_STATUES.NOTIFICATION_NOT_FOUND.message, { + cause: ERROR_STATUES.NOTIFICATION_NOT_FOUND, + }) + } + } +} + +export default PushSubscriptionDeleteOperation diff --git a/app/providers/operations/push_notifications/list_subscriptions/Provider.js b/app/providers/operations/push_notifications/list_subscriptions/Provider.js new file mode 100644 index 00000000..d9eea5a8 --- /dev/null +++ b/app/providers/operations/push_notifications/list_subscriptions/Provider.js @@ -0,0 +1,18 @@ +import RegisterProvider from "../../../../common/RegisterProvider.js" +import PushSubscriptionListOperation from "./index.js" + +const name = "PushSubscriptionListOperation" + +class PushSubscriptionListOperationRegisterProvider extends RegisterProvider { + register(slc) { + const sessionService = slc.use("SessionService") + const pushNotificationService = slc.use("PushNotificationService") + + return new PushSubscriptionListOperation(sessionService, pushNotificationService) + } +} + +export default new PushSubscriptionListOperationRegisterProvider({ + name, + implementationName: PushSubscriptionListOperation.name, +}) diff --git a/app/providers/operations/push_notifications/list_subscriptions/index.js b/app/providers/operations/push_notifications/list_subscriptions/index.js new file mode 100644 index 00000000..f78ff744 --- /dev/null +++ b/app/providers/operations/push_notifications/list_subscriptions/index.js @@ -0,0 +1,16 @@ +class PushSubscriptionListOperation { + constructor(sessionService, pushNotificationService) { + this.sessionService = sessionService + this.pushNotificationService = pushNotificationService + } + + async perform(ws, queryParams) { + const currentUserId = this.sessionService.getSessionUserId(ws) + + const pushSubscriptions = await this.pushNotificationService.listSubscriptions(currentUserId) + + return pushSubscriptions + } +} + +export default PushSubscriptionListOperation diff --git a/app/providers/operations/user/create/Provider.js b/app/providers/operations/user/create/Provider.js index 7a191e5d..e6c25d19 100644 --- a/app/providers/operations/user/create/Provider.js +++ b/app/providers/operations/user/create/Provider.js @@ -1,15 +1,14 @@ import RegisterProvider from "../../../../common/RegisterProvider.js" import UserCreateOperation from "./index.js" -import contactsMatchRepository from "../../../../repositories/contact_match_repository.js" - const name = "UserCreateOperation" class UserCreateOperationRegisterProvider extends RegisterProvider { register(slc) { const userService = slc.use("UserService") + const contactService = slc.use("ContactService") - return new UserCreateOperation(userService, contactsMatchRepository) + return new UserCreateOperation(userService, contactService) } } diff --git a/app/providers/operations/user/delete/Provider.js b/app/providers/operations/user/delete/Provider.js index 6a976574..e218a51b 100644 --- a/app/providers/operations/user/delete/Provider.js +++ b/app/providers/operations/user/delete/Provider.js @@ -1,8 +1,6 @@ import RegisterProvider from "../../../../common/RegisterProvider.js" import UserDeleteOperation from "./index.js" -import contactsMatchRepository from "../../../../repositories/contact_match_repository.js" - const name = "UserDeleteOperation" class UserDeleteOperationRegisterProvider extends RegisterProvider { @@ -11,13 +9,14 @@ class UserDeleteOperationRegisterProvider extends RegisterProvider { const userService = slc.use("UserService") const activityManagerService = slc.use("ActivityManagerService") const blockListService = slc.use("BlockListService") + const contactService = slc.use("ContactService") return new UserDeleteOperation( sessionService, userService, activityManagerService, blockListService, - contactsMatchRepository + contactService ) } } diff --git a/app/providers/operations/user/edit/Provider.js b/app/providers/operations/user/edit/Provider.js index 8b824410..589cb6ed 100644 --- a/app/providers/operations/user/edit/Provider.js +++ b/app/providers/operations/user/edit/Provider.js @@ -1,16 +1,15 @@ import RegisterProvider from "../../../../common/RegisterProvider.js" import UserEditOperation from "./index.js" -import contactsMatchRepository from "../../../../repositories/contact_match_repository.js" - const name = "UserEditOperation" class UserEditOperationRegisterProvider extends RegisterProvider { register(slc) { const sessionService = slc.use("SessionService") const userService = slc.use("UserService") + const contactService = slc.use("ContactService") - return new UserEditOperation(sessionService, userService, contactsMatchRepository) + return new UserEditOperation(sessionService, userService, contactService) } } diff --git a/app/providers/repositories/base.js b/app/providers/repositories/base.js index ec1a3f84..6b725726 100644 --- a/app/providers/repositories/base.js +++ b/app/providers/repositories/base.js @@ -183,7 +183,7 @@ export default class BaseRepository { .findOneAndUpdate(query, update, { returnDocument: "after" }) .catch((error) => error) - const model = record.ok ? this.wrapRawRecordInModel(record.value) : null + const model = record.ok && record.value ? this.wrapRawRecordInModel(record.value) : null return model } @@ -219,6 +219,16 @@ export default class BaseRepository { } async deleteMany(query) { + if (query._id) { + if (query._id.$in) { + query._id.$in = this.castObjectIds(query._id.$in) + } + query._id = this.castObjectId(query._id) + } + if (query.user_id) { + query.user_id = this.castObjectId(query.user_id) + } + await this.collectionCursor.deleteMany(query) } diff --git a/app/providers/repositories/blocked_user/Provider.js b/app/providers/repositories/blocked_user/Provider.js index 7be720c7..34c08919 100644 --- a/app/providers/repositories/blocked_user/Provider.js +++ b/app/providers/repositories/blocked_user/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import BlockedUser from "../../../new_models/blocked_user.js" +import BlockedUser from "../../../models/blocked_user.js" import BlockedUserRepository from "./index.js" const name = "BlockedUserRepository" diff --git a/app/providers/repositories/cluster_node/Provider.js b/app/providers/repositories/cluster_node/Provider.js new file mode 100644 index 00000000..a5b5b7ef --- /dev/null +++ b/app/providers/repositories/cluster_node/Provider.js @@ -0,0 +1,16 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import ClusterNode from "../../../models/cluster_node.js" +import ClusterNodeRepository from "./index.js" + +const name = "ClusterNodeRepository" + +class ClusterNodeRepositoryRegisterProvider extends RegisterProvider { + register(slc) { + const mongoConnection = slc.use("MongoConnection") + const baseMapper = slc.use("BaseMapper") + + return new ClusterNodeRepository(mongoConnection, ClusterNode, baseMapper) + } +} + +export default new ClusterNodeRepositoryRegisterProvider({ name, implementationName: ClusterNodeRepository.name }) diff --git a/app/providers/repositories/cluster_node/index.js b/app/providers/repositories/cluster_node/index.js new file mode 100644 index 00000000..15603951 --- /dev/null +++ b/app/providers/repositories/cluster_node/index.js @@ -0,0 +1,9 @@ +import BaseRepository from "../base.js" + +class ClusterNodeRepository extends BaseRepository { + async updateStats(_id, stats) { + await this.updateOne({ _id }, { $set: { ...stats } }) + } +} + +export default ClusterNodeRepository diff --git a/app/providers/repositories/contact/Provider.js b/app/providers/repositories/contact/Provider.js new file mode 100644 index 00000000..d3bbf630 --- /dev/null +++ b/app/providers/repositories/contact/Provider.js @@ -0,0 +1,16 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import Contact from "../../../models/contact.js" +import ContactRepository from "./index.js" + +const name = "ContactRepository" + +class ContactRepositoryRegisterProvider extends RegisterProvider { + register(slc) { + const mongoConnection = slc.use("MongoConnection") + const baseMapper = slc.use("BaseMapper") + + return new ContactRepository(mongoConnection, Contact, baseMapper) + } +} + +export default new ContactRepositoryRegisterProvider({ name, implementationName: ContactRepository.name }) diff --git a/app/providers/repositories/contact/index.js b/app/providers/repositories/contact/index.js new file mode 100644 index 00000000..b3a28e64 --- /dev/null +++ b/app/providers/repositories/contact/index.js @@ -0,0 +1,46 @@ +import BaseRepository from "../base.js" + +class ContactRepository extends BaseRepository { + async prepareParams(params) { + params.user_id = this.castObjectId(params.user_id) + + return await super.prepareParams(params) + } + + async findByIdAndUpdate(contactId, updateParams) { + const contact = await this.findOneAndUpdate({ _id: contactId }, { $set: updateParams }) + + return contact + } + + async findByEmailPhone(email, phone, limit) { + const query = { $or: [] } + + email && query.$or.push({ [`phone.value`]: phone }) + phone && query.$or.push({ [`email.value`]: email }) + + const contacts = await this.findAll(query, null, limit, { sort: -1 }) + + return contacts + } + + async findAllUserContacts(ownerId, query, limit) { + const queryParams = { user_id: ownerId } + + if (query.updated_at) { + queryParams.updated_at = { $gt: new Date(query.updated_at) } + } + + const contacts = await this.findAll(queryParams, null, limit) + + return contacts + } + + async deleteUserContact(ownerId, contactId) { + const query = { _id: contactId, user_id: ownerId } + + await this.deleteMany(query) + } +} + +export default ContactRepository diff --git a/app/providers/repositories/conversation/Provider.js b/app/providers/repositories/conversation/Provider.js index 14eb759a..4d81bb55 100644 --- a/app/providers/repositories/conversation/Provider.js +++ b/app/providers/repositories/conversation/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import Conversation from "../../../new_models/conversation.js" +import Conversation from "../../../models/conversation.js" import ConversationRepository from "./index.js" const name = "ConversationRepository" diff --git a/app/providers/repositories/conversation_participants/Provider.js b/app/providers/repositories/conversation_participants/Provider.js index badb1c91..f447c68e 100644 --- a/app/providers/repositories/conversation_participants/Provider.js +++ b/app/providers/repositories/conversation_participants/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import ConversationParticipant from "../../../new_models/conversation_participants.js" +import ConversationParticipant from "../../../models/conversation_participants.js" import ConversationParticipantRepository from "./index.js" const name = "ConversationParticipantRepository" diff --git a/app/providers/repositories/file/Provider.js b/app/providers/repositories/file/Provider.js index 98d6f425..3c35a318 100644 --- a/app/providers/repositories/file/Provider.js +++ b/app/providers/repositories/file/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import File from "../../../new_models/file.js" +import File from "../../../models/file.js" import FileRepository from "./index.js" const name = "FileRepository" diff --git a/app/providers/repositories/message/Provider.js b/app/providers/repositories/message/Provider.js index 814ea5e1..8aa1df14 100644 --- a/app/providers/repositories/message/Provider.js +++ b/app/providers/repositories/message/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import Message from "../../../new_models/message.js" +import Message from "../../../models/message.js" import MessageRepository from "./index.js" const name = "MessageRepository" diff --git a/app/providers/repositories/message_status/Provider.js b/app/providers/repositories/message_status/Provider.js index f61075fd..4e6ac598 100644 --- a/app/providers/repositories/message_status/Provider.js +++ b/app/providers/repositories/message_status/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import MessageStatus from "../../../new_models/message_status.js" +import MessageStatus from "../../../models/message_status.js" import MessageStatusRepository from "./index.js" const name = "MessageStatusRepository" diff --git a/app/providers/repositories/operations_log/Provider.js b/app/providers/repositories/operations_log/Provider.js new file mode 100644 index 00000000..3e6932f5 --- /dev/null +++ b/app/providers/repositories/operations_log/Provider.js @@ -0,0 +1,16 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import OperationsLogModel from "../../../models/operations_log.js" +import OperationsLogRepository from "./index.js" + +const name = "OperationsLogRepository" + +class OperationsLogRepositoryRegisterProvider extends RegisterProvider { + register(slc) { + const mongoConnection = slc.use("MongoConnection") + const baseMapper = slc.use("BaseMapper") + + return new OperationsLogRepository(mongoConnection, OperationsLogModel, baseMapper) + } +} + +export default new OperationsLogRepositoryRegisterProvider({ name, implementationName: OperationsLogRepository.name }) diff --git a/app/providers/repositories/operations_log/index.js b/app/providers/repositories/operations_log/index.js new file mode 100644 index 00000000..6c3ab2b5 --- /dev/null +++ b/app/providers/repositories/operations_log/index.js @@ -0,0 +1,22 @@ +import BaseRepository from "../base.js" + +class OperationsLogRepository extends BaseRepository { + async prepareParams(params) { + params.user_id = this.castObjectId(params.user_id) + + return await super.prepareParams(params) + } + + async list(userId, createdAt) { + const query = { + user_id: userId, + created_at: createdAt.gt ? { $gt: new Date(createdAt.gt) } : { $lt: new Date(createdAt.lt) }, + } + + const opLogs = await this.findAll(query) + + return opLogs + } +} + +export default OperationsLogRepository diff --git a/app/providers/repositories/push_event/Provider.js b/app/providers/repositories/push_event/Provider.js new file mode 100644 index 00000000..a32d75eb --- /dev/null +++ b/app/providers/repositories/push_event/Provider.js @@ -0,0 +1,16 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import PushEvent from "../../../models/push_event.js" +import PushEventRepository from "./index.js" + +const name = "PushEventRepository" + +class PushEventRepositoryRegisterProvider extends RegisterProvider { + register(slc) { + const mongoConnection = slc.use("MongoConnection") + const baseMapper = slc.use("BaseMapper") + + return new PushEventRepository(mongoConnection, PushEvent, baseMapper) + } +} + +export default new PushEventRepositoryRegisterProvider({ name, implementationName: PushEventRepository.name }) diff --git a/app/providers/repositories/push_event/index.js b/app/providers/repositories/push_event/index.js new file mode 100644 index 00000000..4e1cdec5 --- /dev/null +++ b/app/providers/repositories/push_event/index.js @@ -0,0 +1,15 @@ +import BaseRepository from "../base.js" + +class PushEventRepository extends BaseRepository { + async prepareParams(params) { + params.user_id = this.castObjectId(params.user_id) + params.user_ids = this.castObjectIds(params.user_ids) + + params.message = Buffer.from(JSON.stringify(params.payload)).toString("base64") + delete params.payload + + return await super.prepareParams(params) + } +} + +export default PushEventRepository diff --git a/app/providers/repositories/push_subscriptions/Provider.js b/app/providers/repositories/push_subscriptions/Provider.js new file mode 100644 index 00000000..97f94105 --- /dev/null +++ b/app/providers/repositories/push_subscriptions/Provider.js @@ -0,0 +1,19 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import PushSubscriptions from "../../../models/push_subscription.js" +import PushSubscriptionsRepository from "./index.js" + +const name = "PushSubscriptionsRepository" + +class PushSubscriptionsRepositoryRegisterProvider extends RegisterProvider { + register(slc) { + const mongoConnection = slc.use("MongoConnection") + const baseMapper = slc.use("BaseMapper") + + return new PushSubscriptionsRepository(mongoConnection, PushSubscriptions, baseMapper) + } +} + +export default new PushSubscriptionsRepositoryRegisterProvider({ + name, + implementationName: PushSubscriptionsRepository.name, +}) diff --git a/app/providers/repositories/push_subscriptions/index.js b/app/providers/repositories/push_subscriptions/index.js new file mode 100644 index 00000000..f0b50c51 --- /dev/null +++ b/app/providers/repositories/push_subscriptions/index.js @@ -0,0 +1,23 @@ +import BaseRepository from "../base.js" + +class PushSubscriptionsRepository extends BaseRepository { + async prepareParams(params) { + params.user_id = this.castObjectId(params.user_id) + + return await super.prepareParams(params) + } + + async findAndUpdate(userId, deviceId, updateParams) { + const subscription = await this.findOneAndUpdate({ user_id: userId, device_udid: deviceId }, { $set: updateParams }) + + return subscription + } + + async findUserSubscription(userId, deviceId) { + const subscription = await this.findOne({ user_id: userId, device_udid: deviceId }) + + return subscription + } +} + +export default PushSubscriptionsRepository diff --git a/app/providers/repositories/user/Provider.js b/app/providers/repositories/user/Provider.js index ac995c89..15b75535 100644 --- a/app/providers/repositories/user/Provider.js +++ b/app/providers/repositories/user/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import User from "../../../new_models/user.js" +import User from "../../../models/user.js" import UserRepository from "./index.js" const name = "UserRepository" diff --git a/app/providers/repositories/user_token/Provider.js b/app/providers/repositories/user_token/Provider.js index a1edb20a..bf69725d 100644 --- a/app/providers/repositories/user_token/Provider.js +++ b/app/providers/repositories/user_token/Provider.js @@ -1,5 +1,5 @@ import RegisterProvider from "../../../common/RegisterProvider.js" -import UserToken from "../../../new_models/user_token.js" +import UserToken from "../../../models/user_token.js" import UserTokenRepository from "./index.js" const name = "UserTokenRepository" diff --git a/app/providers/services/cluster_node/Provider.js b/app/providers/services/cluster_node/Provider.js new file mode 100644 index 00000000..9a65b09e --- /dev/null +++ b/app/providers/services/cluster_node/Provider.js @@ -0,0 +1,14 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import ClusterNodeService from "./index.js" + +const name = "ClusterNodeService" + +class ClusterNodeServiceRegisterProvider extends RegisterProvider { + register(slc) { + const clusterNodeRepo = slc.use("ClusterNodeRepository") + + return new ClusterNodeService(clusterNodeRepo) + } +} + +export default new ClusterNodeServiceRegisterProvider({ name, implementationName: ClusterNodeService.name }) diff --git a/app/providers/services/cluster_node/index.js b/app/providers/services/cluster_node/index.js new file mode 100644 index 00000000..2f95e762 --- /dev/null +++ b/app/providers/services/cluster_node/index.js @@ -0,0 +1,33 @@ +class ClusterNodeService { + constructor(clusterNodeRepo) { + this.clusterNodeRepo = clusterNodeRepo + } + + async retrieveAll() { + const clusterNodes = await this.clusterNodeRepo.findAll({}) + + return clusterNodes + } + + async create(addressParams, optionalParams) { + const clusterNodeParams = Object.assign({}, addressParams, optionalParams) + + const clusterNode = await this.clusterNodeRepo.create(clusterNodeParams) + + return clusterNode + } + + async upsert(addressParams, optionalParams) { + const existedNode = await this.clusterNodeRepo.findOne(addressParams) + + if (existedNode) { + await this.clusterNodeRepo.updateStats(existedNode._id, optionalParams) + + return + } + + await this.create(addressParams, optionalParams) + } +} + +export default ClusterNodeService diff --git a/app/providers/services/contacts/Provider.js b/app/providers/services/contacts/Provider.js new file mode 100644 index 00000000..b1eff465 --- /dev/null +++ b/app/providers/services/contacts/Provider.js @@ -0,0 +1,15 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import ContactService from "./index.js" + +const name = "ContactService" + +class ContactServiceRegisterProvider extends RegisterProvider { + register(slc) { + const contactRepo = slc.use("ContactRepository") + const userRepo = slc.use("UserRepository") + + return new ContactService(contactRepo, userRepo) + } +} + +export default new ContactServiceRegisterProvider({ name, implementationName: ContactService.name }) diff --git a/app/repositories/contact_match_repository.js b/app/providers/services/contacts/index.js similarity index 52% rename from app/repositories/contact_match_repository.js rename to app/providers/services/contacts/index.js index 4c761e8d..f7c17a38 100644 --- a/app/repositories/contact_match_repository.js +++ b/app/providers/services/contacts/index.js @@ -1,42 +1,57 @@ -import BaseRepository from "./base.js" - -import ServiceLocatorContainer from "../common/ServiceLocatorContainer.js" +class ContactService { + constructor(contactRepo, userRepo) { + this.contactRepo = contactRepo + this.userRepo = userRepo + } -import Contact from "../models/contact.js" + async create(contactData) { + const contact = await this.contactRepo.create(contactData) -class ContactsMatchRepository extends BaseRepository { - async #getRecords(query) { - if (!query?.$or?.length) { - return [] - } + return contact + } - const records = [] - let [tmpRecords, timeParam] = [[], null] + async delete(ownerId, contactId) { + await this.contactRepo.deleteUserContact(ownerId, contactId) + } - do { - if (timeParam) { - query["created_at"] = { $gt: timeParam } - } - tmpRecords = await this.Model.findAll(query) + async list(ownerId, queryParams, limit) { + const contacts = this.contactRepo.findAllUserContacts(ownerId, queryParams, limit) - if (!tmpRecords.length) { - break - } + return contacts + } - records.push(...tmpRecords) - timeParam = tmpRecords[tmpRecords.length - 1].created_at - } while (tmpRecords.length === 100) + async findByIdAndUpdate(contactId, updateParams) { + const contact = await this.contactRepo.findByIdAndUpdate(contactId, updateParams) - return records + return contact } - async #updateFieldOnCreate(data, userId, value) { - return data.map((el) => { - if (el.value === value) { - el["matched_user_id"] = userId + async matchContactWithUser(contactData) { + const fields = [] + + contactData.email && fields.push("email") + contactData.phone && fields.push("phone") + + if (!fields.length) { + return + } + + const emails = contactData.email?.map((email) => email.value) + const phones = contactData.phone?.map((phone) => phone.value) + const foundUsersList = await this.userRepo.matchUserContact(emails, phones) + + for (const field of fields) { + const foundUsersObj = {} + for (const user of foundUsersList) { + foundUsersObj[user[field]] = user.params._id } - return el - }) + + contactData[field].forEach((obj) => { + if (foundUsersObj[obj.value]) { + obj["matched_user_id"] = foundUsersObj[obj.value] + } + }) + } } async matchUserWithContactOnCreate(userId, phone, email) { @@ -44,78 +59,49 @@ class ContactsMatchRepository extends BaseRepository { return } - const query = { $or: [] } - phone && query.$or.push({ [`phone.value`]: phone }) - email && query.$or.push({ [`email.value`]: email }) - - const records = await this.#getRecords(query) - if (!records.length) { + const contacts = await this.contactRepo.findByEmailPhone(email, phone) + if (!contacts.length) { return } - for (const r of records) { + for (const contact of contacts) { const updateParam = {} - if (!(r.email && r.phone)) { + if (!(contact.email && contact.phone)) { continue } - email && (updateParam["email"] = await this.#updateFieldOnCreate(r.email, userId, email)) - phone && (updateParam["phone"] = await this.#updateFieldOnCreate(r.phone, userId, phone)) + email && (updateParam["email"] = await this.#updateFieldOnCreate(contact.email, userId, email)) + phone && (updateParam["phone"] = await this.#updateFieldOnCreate(contact.phone, userId, phone)) - await this.Model.updateOne({ _id: r._id.toString() }, { $set: updateParam }) + await this.contactRepo.findByIdAndUpdate(contact._id, updateParam) } } - async #updateFieldOnUpdate(data, userId, value, oldValue) { - return data.map((el) => { - if (el.value === oldValue) { - el.value = value - } - if (el.value === value) { - el["matched_user_id"] = userId - } - return el - }) - } - async matchUserWithContactOnUpdate(userId, phone, email, oldPhone, oldEmail) { if (!((email && oldEmail) || (phone && oldPhone))) { return } - const query = { $or: [] } - phone && query.$or.push({ [`phone.value`]: phone }, { [`phone.value`]: oldPhone }) - email && query.$or.push({ [`email.value`]: email }, { [`email.value`]: oldEmail }) - - const records = await this.#getRecords(query) - if (!records.length) { + const contacts = await this.contactRepo.findByEmailPhone(email, phone) + if (!contacts.length) { return } - for (const r of records) { + for (const contact of contacts) { const updateParam = {} - if (!(r.email && r.phone)) { + if (!(contact.email && contact.phone)) { continue } - email && (updateParam["email"] = await this.#updateFieldOnUpdate(r.email, userId, email, oldEmail)) - phone && (updateParam["phone"] = await this.#updateFieldOnUpdate(r.phone, userId, phone, oldPhone)) + email && (updateParam["email"] = await this.#updateFieldOnUpdate(contact.email, userId, email, oldEmail)) + phone && (updateParam["phone"] = await this.#updateFieldOnUpdate(contact.phone, userId, phone, oldPhone)) - await this.Model.updateOne({ _id: r._id.toString() }, { $set: updateParam }) + await this.contactRepo.findByIdAndUpdate(contact._id, updateParam) } } - async #updateFieldOnDelete(data, value) { - return data.map((el) => { - if (el.value === value) { - delete el["matched_user_id"] - } - return el - }) - } - async matchUserWithContactOnDelete(userId, phone, email) { if (!(email && phone)) { return @@ -125,54 +111,54 @@ class ContactsMatchRepository extends BaseRepository { phone && query.$or.push({ [`phone.value`]: phone }) email && query.$or.push({ [`email.value`]: email }) - const records = await this.#getRecords(query) - if (!records.length) { + const contacts = await this.contactRepo.findByEmailPhone(email, phone) + if (!contacts.length) { return } - for (const r of records) { + for (const contact of contacts) { const updateParam = {} - if (!(r.email && r.phone)) { + if (!(contact.email && contact.phone)) { continue } - email && (updateParam["email"] = await this.#updateFieldOnDelete(r.email, email)) - phone && (updateParam["phone"] = await this.#updateFieldOnDelete(r.phone, phone)) + email && (updateParam["email"] = await this.#updateFieldOnDelete(contact.email, email)) + phone && (updateParam["phone"] = await this.#updateFieldOnDelete(contact.phone, phone)) - await this.Model.updateOne({ _id: r._id.toString() }, { $set: updateParam }) + await this.contactRepo.findByIdAndUpdate(contact._id, updateParam) } } - async matchContactWithUser(contactData) { - const fields = [] - - contactData.email && fields.push("email") - contactData.phone && fields.push("phone") - - if (!fields.length) { - return - } - - const userService = ServiceLocatorContainer.use("UserService") - - const emails = contactData.email?.map((email) => email.value) - const phones = contactData.phone?.map((phone) => phone.value) - const foundUsersList = await userService.userRepo.matchUserContact(emails, phones) + async #updateFieldOnCreate(data, userId, value) { + return data.map((el) => { + if (el.value === value) { + el["matched_user_id"] = userId + } + return el + }) + } - for (const field of fields) { - const foundUsersObj = {} - for (const user of foundUsersList) { - foundUsersObj[user.params[field]] = user.params._id + async #updateFieldOnUpdate(data, userId, value, oldValue) { + return data.map((el) => { + if (el.value === oldValue) { + el.value = value + } + if (el.value === value) { + el["matched_user_id"] = userId } + return el + }) + } - contactData[field].forEach((obj) => { - if (foundUsersObj[obj.value]) { - obj["matched_user_id"] = foundUsersObj[obj.value] - } - }) - } + async #updateFieldOnDelete(data, value) { + return data.map((el) => { + if (el.value === value) { + delete el["matched_user_id"] + } + return el + }) } } -export default new ContactsMatchRepository(Contact) +export default ContactService diff --git a/app/providers/services/operation_logs/Provider.js b/app/providers/services/operation_logs/Provider.js new file mode 100644 index 00000000..56e8eb14 --- /dev/null +++ b/app/providers/services/operation_logs/Provider.js @@ -0,0 +1,14 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import OperationLogsService from "./index.js" + +const name = "OperationLogsService" + +class OperationLogsServiceRegisterProvider extends RegisterProvider { + register(slc) { + const opLogsRepo = slc.use("OperationsLogRepository") + + return new OperationLogsService(opLogsRepo) + } +} + +export default new OperationLogsServiceRegisterProvider({ name, implementationName: OperationLogsService.name }) diff --git a/app/providers/services/operation_logs/index.js b/app/providers/services/operation_logs/index.js new file mode 100644 index 00000000..d4582e6b --- /dev/null +++ b/app/providers/services/operation_logs/index.js @@ -0,0 +1,19 @@ +class OperationLogsService { + constructor(opLogsRepo) { + this.opLogsRepo = opLogsRepo + } + + async savePacket(user_id, packet) { + const opLog = await this.opLogsRepo.create({ user_id, packet }) + + return opLog + } + + async list(userId, createdAt) { + const opLogs = await this.opLogsRepo.list(userId, createdAt) + + return opLogs + } +} + +export default OperationLogsService diff --git a/app/providers/services/push_notifications/Provider.js b/app/providers/services/push_notifications/Provider.js new file mode 100644 index 00000000..7bbb011a --- /dev/null +++ b/app/providers/services/push_notifications/Provider.js @@ -0,0 +1,16 @@ +import RegisterProvider from "../../../common/RegisterProvider.js" +import PushNotificationService from "./index.js" + +const name = "PushNotificationService" + +class PushNotificationServiceRegisterProvider extends RegisterProvider { + register(slc) { + const RuntimeDefinedContext = slc.use("RuntimeDefinedContext") + const pushEventRepo = slc.use("PushEventRepository") + const pushSubscriptionsRepo = slc.use("PushSubscriptionsRepository") + + return new PushNotificationService(RuntimeDefinedContext, pushEventRepo, pushSubscriptionsRepo) + } +} + +export default new PushNotificationServiceRegisterProvider({ name, implementationName: PushNotificationService.name }) diff --git a/app/providers/services/push_notifications/index.js b/app/providers/services/push_notifications/index.js new file mode 100644 index 00000000..c3bf8f4e --- /dev/null +++ b/app/providers/services/push_notifications/index.js @@ -0,0 +1,55 @@ +import CreatePushEventOptions from "@sama/lib/push_queue/models/CreatePushEventOptions.js" + +class PushNotificationService { + constructor(RuntimeDefinedContext, pushEventRepo, pushSubscriptionsRepo) { + this.RuntimeDefinedContext = RuntimeDefinedContext + this.pushEventRepo = pushEventRepo + this.pushSubscriptionsRepo = pushSubscriptionsRepo + } + + async findSubscription(userId, deviceId) { + const subscription = await this.pushSubscriptionsRepo.findUserSubscription(userId, deviceId) + + return subscription + } + + async upsertSubscription(userId, deviceId, updateParams) { + let subscription = await this.pushSubscriptionsRepo.findAndUpdate(userId, deviceId, updateParams) + + if (!subscription) { + subscription = await this.pushSubscriptionsRepo.create( + Object.assign({}, { user_id: userId, device_udid: deviceId }, updateParams) + ) + } + + return subscription + } + + async listSubscriptions(userId) { + const subscriptions = await this.pushSubscriptionsRepo.findAll({ user_id: userId }) + + return subscriptions + } + + async findAndDeleteSubscription(userId, deviceId) { + const subscription = await this.findSubscription(userId, deviceId) + + if (subscription) { + await this.pushSubscriptionsRepo.deleteById(subscription._id) + } + + return subscription + } + + async createEvent(userId, recipientIds, message) { + const createPushEventOptions = new CreatePushEventOptions(userId, message, { + user_ids: recipientIds, + }) + + const pushEvent = await this.RuntimeDefinedContext.PUSH_QUEUE_DRIVER.createPushEvent(createPushEventOptions) + + return pushEvent + } +} + +export default PushNotificationService diff --git a/app/repositories/base.js b/app/repositories/base.js deleted file mode 100644 index 57adc819..00000000 --- a/app/repositories/base.js +++ /dev/null @@ -1,5 +0,0 @@ -export default class BaseRepository { - constructor(Model) { - this.Model = Model - } -} diff --git a/app/repositories/file_repository.js b/app/repositories/file_repository.js deleted file mode 100644 index 7e0d99e1..00000000 --- a/app/repositories/file_repository.js +++ /dev/null @@ -1,21 +0,0 @@ -import BaseRepository from "./base.js" - -import RedisClient from "../lib/redis.js" - -class FileRepository extends BaseRepository { - #generateKey(fileId) { - return `file:${fileId}` - } - - async getFileUrl(fileId) { - const items = await RedisClient.client.sMembers(this.#generateKey(fileId)) - return items.at(0) - } - - async storeFileUrl(fileId, url) { - await RedisClient.client.sAdd(this.#generateKey(fileId), url) - await RedisClient.client.expire(this.#generateKey(fileId), 3600) - } -} - -export default new FileRepository(null) diff --git a/app/repositories/operations_log_repository.js b/app/repositories/operations_log_repository.js deleted file mode 100644 index f70d526c..00000000 --- a/app/repositories/operations_log_repository.js +++ /dev/null @@ -1,12 +0,0 @@ -import BaseRepository from "./base.js" - -import OpLog from "../models/operations_log.js" - -class OperationsLogRepository extends BaseRepository { - async savePacket(user_id, packet) { - const record = new this.Model({ user_id, packet }) - await record.save() - } -} - -export default new OperationsLogRepository(OpLog) diff --git a/app/repositories/push_notifications_repository.js b/app/repositories/push_notifications_repository.js deleted file mode 100644 index ef421af9..00000000 --- a/app/repositories/push_notifications_repository.js +++ /dev/null @@ -1,39 +0,0 @@ -import BaseRepository from "./base.js" - -import PushEvent from "../models/push_event.js" -import PushSubscription from "../models/push_subscription.js" - -class PushNotificationsRepository extends BaseRepository { - constructor(PushEventModel, PushSubscriptionModel) { - super(PushEventModel) - - this.PushSubscriptionModel = PushSubscriptionModel - } - - async getSubscriptionsByUid(user_id) { - return await this.PushSubscriptionModel.findAll({ user_id }, [ - "platform", - "web_endpoint", - "web_key_auth", - "web_key_p256dh", - "device_token", - ]) - } - - async createPushEvent(userId, userIds, payload, options) { - const base64Payload = Buffer.from(JSON.stringify(payload)).toString("base64") - - const pushEventParams = { - user_id: userId, - user_ids: userIds, - - message: base64Payload, - } - const pushEvent = new this.Model(pushEventParams) - await pushEvent.save() - - return pushEvent - } -} - -export default new PushNotificationsRepository(PushEvent, PushSubscription) diff --git a/test/attachments.js b/test/attachments.js index e6e1e2b5..870faba0 100644 --- a/test/attachments.js +++ b/test/attachments.js @@ -2,8 +2,6 @@ import assert from "assert" import ServiceLocatorContainer from "../app/common/ServiceLocatorContainer.js" -import File from "../app/models/file.js" -import OpLog from "./../app/models/operations_log.js" import { createConversation, createUserArray, mockedWS, sendLogin, sendLogout } from "./utils.js" import packetJsonProcessor from "../APIs/JSON/routes/packet_processor.js" @@ -12,6 +10,8 @@ const conversationRepo = ServiceLocatorContainer.use("ConversationRepository") const conversationParticipantRepo = ServiceLocatorContainer.use("ConversationParticipantRepository") const messageRepo = ServiceLocatorContainer.use("MessageRepository") const messageStatusRepo = ServiceLocatorContainer.use("MessageStatusRepository") +const fileRepo = ServiceLocatorContainer.use("FileRepository") +const opLogsRepo = ServiceLocatorContainer.use("OperationsLogRepository") let currentUserToken = "" let usersIds = [] @@ -20,7 +20,7 @@ let files describe("Attachments", async () => { before(async () => { - await File.clearCollection() + await fileRepo.deleteMany({}) usersIds = await createUserArray(3) currentUserToken = (await sendLogin(mockedWS, "user_1")).response.user.token @@ -267,9 +267,8 @@ describe("Attachments", async () => { await messageStatusRepo.deleteMany({}) await conversationRepo.deleteMany({}) await conversationParticipantRepo.deleteMany({}) - - await File.clearCollection() - await OpLog.clearCollection() + await fileRepo.deleteMany({}) + await opLogsRepo.deleteMany({}) usersIds = [] }) diff --git a/test/contacts.js b/test/contacts.js index bf31ef6c..7dde4f98 100644 --- a/test/contacts.js +++ b/test/contacts.js @@ -2,11 +2,11 @@ import assert from "assert" import ServiceLocatorContainer from "../app/common/ServiceLocatorContainer.js" -import Contact from "./../app/models/contact.js" import { createUserArray, mockedWS, sendLogin, sendLogout } from "./utils.js" import packetJsonProcessor from "../APIs/JSON/routes/packet_processor.js" const userRepo = ServiceLocatorContainer.use("UserRepository") +const contactRepo = ServiceLocatorContainer.use("ContactRepository") let usersIds = [] let contactIdToUpdate = "" @@ -679,7 +679,7 @@ describe("Contacts functions", async () => { after(async () => { await userRepo.deleteMany({}) - await Contact.clearCollection() + await contactRepo.deleteMany({}) usersIds = [] }) diff --git a/test/operations_log.js b/test/operations_log.js index 95e44fc0..15511b67 100644 --- a/test/operations_log.js +++ b/test/operations_log.js @@ -2,26 +2,25 @@ import assert from "assert" import ServiceLocatorContainer from "../app/common/ServiceLocatorContainer.js" -import OpLog from "./../app/models/operations_log.js" -import operationsLogRepository from "./../app/repositories/operations_log_repository.js" - import { createUserArray, mockedWS, sendLogin } from "./utils.js" import packetJsonProcessor from "../APIs/JSON/routes/packet_processor.js" const userRepo = ServiceLocatorContainer.use("UserRepository") +const opLogsService = ServiceLocatorContainer.use("OperationLogsService") +const opLogRepository = ServiceLocatorContainer.use("OperationsLogRepository") let timeWhenUserOff = null let usersIds = [] describe("Operations Log functions", async () => { before(async () => { - await OpLog.clearCollection() + await opLogRepository.deleteMany({}) usersIds = await createUserArray(2) await sendLogin(mockedWS, "user_1") for (let i = 0; i < 2; i++) { - await operationsLogRepository.savePacket( + await opLogsService.savePacket( usersIds[1], JSON.stringify({ message_update: { @@ -78,7 +77,7 @@ describe("Operations Log functions", async () => { responseData = responseData.backMessages.at(0).packet for (let i = 2; i < 6; i++) { - await operationsLogRepository.savePacket( + await opLogsService.savePacket( usersIds[1], JSON.stringify({ message_update: { @@ -118,7 +117,7 @@ describe("Operations Log functions", async () => { after(async () => { await userRepo.deleteMany({}) - await OpLog.clearCollection() + await opLogRepository.deleteMany({}) usersIds = [] }) diff --git a/test/push_notifications.js b/test/push_notifications.js index 09108bfe..ade509fd 100644 --- a/test/push_notifications.js +++ b/test/push_notifications.js @@ -2,13 +2,13 @@ import assert from "assert" import ServiceLocatorContainer from "../app/common/ServiceLocatorContainer.js" -import PushEvent from "./../app/models/push_event.js" -import PushSubscription from "./../app/models/push_subscription.js" import packetJsonProcessor from "../APIs/JSON/routes/packet_processor.js" import { createUserArray, mockedWS, sendLogin } from "./utils.js" const userRepo = ServiceLocatorContainer.use("UserRepository") +const pushEventRepo = ServiceLocatorContainer.use("PushEventRepository") +const pushSubscriptionRepo = ServiceLocatorContainer.use("PushSubscriptionsRepository") let usersIds = [] @@ -545,7 +545,7 @@ describe("PushNotification functions", async () => { const event = responseData.response.event assert.strictEqual(requestData.request.id, responseData.response.id) - assert.strictEqual(event.user_ids[0], usersIds[0].toString()) + assert.strictEqual(event.user_ids[0].toString(), usersIds[0].toString()) }) it("should fail, recipients ids not found", async () => { @@ -578,8 +578,8 @@ describe("PushNotification functions", async () => { after(async () => { await userRepo.deleteMany({}) - await PushSubscription.clearCollection() - await PushEvent.clearCollection() + await pushEventRepo.deleteMany({}) + await pushSubscriptionRepo.deleteMany({}) usersIds = [] })