From 3716e5eec1db2205761d127cbb249bce0ded9e92 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 24 Nov 2023 22:58:32 +0330 Subject: [PATCH 01/17] [NPM]: update packages --- package-lock.json | 345 ++++++++++++++++++++++++++-------------------- package.json | 6 +- 2 files changed, 202 insertions(+), 149 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1d79a4b1..45df096c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "ISC", "dependencies": { "@sentry/node": "^7.51.2", - "@togethercrew.dev/db": "^2.5.1", + "@togethercrew.dev/db": "^3.0.16", "@togethercrew.dev/tc-messagebroker": "^0.0.40", "babel-jest": "^29.5.0", "bullmq": "^3.14.0", @@ -41,7 +41,7 @@ "eslint-plugin-promise": "^6.1.1", "jest": "^29.5.0", "node-mocks-http": "^1.12.2", - "nodemon": "^2.0.22", + "nodemon": "^3.0.1", "prettier": "^2.8.8", "supertest": "^6.3.3", "ts-jest": "^29.1.0", @@ -715,11 +715,11 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.22.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", - "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.4.tgz", + "integrity": "sha512-r1IONyb6Ia+jYR2vvIDhdWdlTGhqbBoFqLTQidzZ4kepUFH15ejXvFHxCVbtl7BOXIudsIubf4E81xeA3h3IXA==", "dependencies": { - "@babel/highlight": "^7.22.13", + "@babel/highlight": "^7.23.4", "chalk": "^2.4.2" }, "engines": { @@ -764,11 +764,11 @@ } }, "node_modules/@babel/generator": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.22.15.tgz", - "integrity": "sha512-Zu9oWARBqeVOW0dZOjXc3JObrzuqothQ3y/n1kUtrjCoCPLkXUwMvOo/F/TCfoHMbWIFlWwpZtkZVb9ga4U2pA==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.4.tgz", + "integrity": "sha512-esuS49Cga3HcThFNebGhlgsrVLkvhqvYDTzgjfFFlHJcIfLe5jFmRRfCQ1KuBfc4Jrtn3ndLgKWAKjBE+IraYQ==", "dependencies": { - "@babel/types": "^7.22.15", + "@babel/types": "^7.23.4", "@jridgewell/gen-mapping": "^0.3.2", "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" @@ -801,12 +801,12 @@ } }, "node_modules/@babel/helper-function-name": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.22.5.tgz", - "integrity": "sha512-wtHSq6jMRE3uF2otvfuD3DIvVhOsSNshQl0Qrd7qC9oQJzHvOL4qQXlQn2916+CXGywIjpGuIkoyZRRxHPiNQQ==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dependencies": { - "@babel/template": "^7.22.5", - "@babel/types": "^7.22.5" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" }, "engines": { "node": ">=6.9.0" @@ -883,9 +883,9 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", - "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", "engines": { "node": ">=6.9.0" } @@ -920,9 +920,9 @@ } }, "node_modules/@babel/highlight": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", - "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", "dependencies": { "@babel/helper-validator-identifier": "^7.22.20", "chalk": "^2.4.2", @@ -933,9 +933,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.22.16", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.22.16.tgz", - "integrity": "sha512-+gPfKv8UWeKKeJTUxe59+OobVcrYHETCsORl61EmSkmgymguYk/X5bp7GuUIXaFsc6y++v8ZxPsLSSuujqDphA==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.4.tgz", + "integrity": "sha512-vf3Xna6UEprW+7t6EtOmFpHNAuxw3xqPZghy+brsnusscJRW5BMUzzHZc5ICjULee81WeUV2jjakG09MDglJXQ==", "bin": { "parser": "bin/babel-parser.js" }, @@ -1122,18 +1122,18 @@ } }, "node_modules/@babel/traverse": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.22.20.tgz", - "integrity": "sha512-eU260mPZbU7mZ0N+X10pxXhQFMGTeLb9eFS0mxehS8HZp9o1uSnFeWQuG1UPrlxgA7QoUzFhOnilHDp0AXCyHw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.4.tgz", + "integrity": "sha512-IYM8wSUwunWTB6tFC2dkKZhxbIjHoWemdK+3f8/wq8aKhbUscxD5MX72ubd90fxvFknaLPeGw5ycU84V1obHJg==", "dependencies": { - "@babel/code-frame": "^7.22.13", - "@babel/generator": "^7.22.15", + "@babel/code-frame": "^7.23.4", + "@babel/generator": "^7.23.4", "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.22.5", + "@babel/helper-function-name": "^7.23.0", "@babel/helper-hoist-variables": "^7.22.5", "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.22.16", - "@babel/types": "^7.22.19", + "@babel/parser": "^7.23.4", + "@babel/types": "^7.23.4", "debug": "^4.1.0", "globals": "^11.1.0" }, @@ -1142,12 +1142,12 @@ } }, "node_modules/@babel/types": { - "version": "7.22.19", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.22.19.tgz", - "integrity": "sha512-P7LAw/LbojPzkgp5oznjE6tQEIWbp4PkkfrZDINTro9zgBRtI324/EYsiSI7lhPbpIQ+DCeR2NNmMWANGGfZsg==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.4.tgz", + "integrity": "sha512-7uIFwVYpoplT5jp/kVv6EF93VaJ8H+Yn5IczYiaAi98ajzjfoZfslet/e0sLh+wVBjb2qqIut1b0S26VSafsSQ==", "dependencies": { - "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.19", + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" }, "engines": { @@ -1183,17 +1183,17 @@ } }, "node_modules/@discordjs/builders": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.6.5.tgz", - "integrity": "sha512-SdweyCs/+mHj+PNhGLLle7RrRFX9ZAhzynHahMCLqp5Zeq7np7XC6/mgzHc79QoVlQ1zZtOkTTiJpOZu5V8Ufg==", - "dependencies": { - "@discordjs/formatters": "^0.3.2", - "@discordjs/util": "^1.0.1", - "@sapphire/shapeshift": "^3.9.2", - "discord-api-types": "0.37.50", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.7.0.tgz", + "integrity": "sha512-GDtbKMkg433cOZur8Dv6c25EHxduNIBsxeHrsRoIM8+AwmEZ8r0tEpckx/sHwTLwQPOF3e2JWloZh9ofCaMfAw==", + "dependencies": { + "@discordjs/formatters": "^0.3.3", + "@discordjs/util": "^1.0.2", + "@sapphire/shapeshift": "^3.9.3", + "discord-api-types": "0.37.61", "fast-deep-equal": "^3.1.3", "ts-mixer": "^6.0.3", - "tslib": "^2.6.1" + "tslib": "^2.6.2" }, "engines": { "node": ">=16.11.0" @@ -1208,62 +1208,78 @@ } }, "node_modules/@discordjs/formatters": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.2.tgz", - "integrity": "sha512-lE++JZK8LSSDRM5nLjhuvWhGuKiXqu+JZ/DsOR89DVVia3z9fdCJVcHF2W/1Zxgq0re7kCzmAJlCMMX3tetKpA==", + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.3.tgz", + "integrity": "sha512-wTcI1Q5cps1eSGhl6+6AzzZkBBlVrBdc9IUhJbijRgVjCNIIIZPgqnUj3ntFODsHrdbGU8BEG9XmDQmgEEYn3w==", "dependencies": { - "discord-api-types": "0.37.50" + "discord-api-types": "0.37.61" }, "engines": { "node": ">=16.11.0" } }, "node_modules/@discordjs/rest": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.0.1.tgz", - "integrity": "sha512-/eWAdDRvwX/rIE2tuQUmKaxmWeHmGealttIzGzlYfI4+a7y9b6ZoMp8BG/jaohs8D8iEnCNYaZiOFLVFLQb8Zg==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.2.0.tgz", + "integrity": "sha512-nXm9wT8oqrYFRMEqTXQx9DUTeEtXUDMmnUKIhZn6O2EeDY9VCdwj23XCPq7fkqMPKdF7ldAfeVKyxxFdbZl59A==", "dependencies": { - "@discordjs/collection": "^1.5.3", - "@discordjs/util": "^1.0.1", + "@discordjs/collection": "^2.0.0", + "@discordjs/util": "^1.0.2", "@sapphire/async-queue": "^1.5.0", "@sapphire/snowflake": "^3.5.1", "@vladfrangu/async_event_emitter": "^2.2.2", - "discord-api-types": "0.37.50", - "magic-bytes.js": "^1.0.15", - "tslib": "^2.6.1", - "undici": "5.22.1" + "discord-api-types": "0.37.61", + "magic-bytes.js": "^1.5.0", + "tslib": "^2.6.2", + "undici": "5.27.2" }, "engines": { "node": ">=16.11.0" } }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, "node_modules/@discordjs/util": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.0.1.tgz", - "integrity": "sha512-d0N2yCxB8r4bn00/hvFZwM7goDcUhtViC5un4hPj73Ba4yrChLSJD8fy7Ps5jpTLg1fE9n4K0xBLc1y9WGwSsA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.0.2.tgz", + "integrity": "sha512-IRNbimrmfb75GMNEjyznqM1tkI7HrZOf14njX7tCAAUetyZM1Pr8hX/EK2lxBCOgWDRmigbp24fD1hdMfQK5lw==", "engines": { "node": ">=16.11.0" } }, "node_modules/@discordjs/ws": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.0.1.tgz", - "integrity": "sha512-avvAolBqN3yrSvdBPcJ/0j2g42ABzrv3PEL76e3YTp2WYMGH7cuspkjfSyNWaqYl1J+669dlLp+YFMxSVQyS5g==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.0.2.tgz", + "integrity": "sha512-+XI82Rm2hKnFwAySXEep4A7Kfoowt6weO6381jgW+wVdTpMS/56qCvoXyFRY0slcv7c/U8My2PwIB2/wEaAh7Q==", "dependencies": { - "@discordjs/collection": "^1.5.3", - "@discordjs/rest": "^2.0.1", - "@discordjs/util": "^1.0.1", + "@discordjs/collection": "^2.0.0", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", "@sapphire/async-queue": "^1.5.0", - "@types/ws": "^8.5.5", + "@types/ws": "^8.5.9", "@vladfrangu/async_event_emitter": "^2.2.2", - "discord-api-types": "0.37.50", - "tslib": "^2.6.1", - "ws": "^8.13.0" + "discord-api-types": "0.37.61", + "tslib": "^2.6.2", + "ws": "^8.14.2" }, "engines": { "node": ">=16.11.0" } }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", @@ -1365,6 +1381,14 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@fastify/busboy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.0.tgz", + "integrity": "sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==", + "engines": { + "node": ">=14" + } + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -2353,9 +2377,9 @@ } }, "node_modules/@sapphire/shapeshift": { - "version": "3.9.2", - "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.2.tgz", - "integrity": "sha512-YRbCXWy969oGIdqR/wha62eX8GNHsvyYi0Rfd4rNW6tSVVa8p0ELiMEuOH/k8rgtvRoM+EMV7Csqz77YdwiDpA==", + "version": "3.9.3", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.3.tgz", + "integrity": "sha512-WzKJSwDYloSkHoBbE8rkRW8UNKJiSRJ/P8NqJ5iVq7U2Yr/kriIBx2hW+wj2Z5e5EnXL1hgYomgaFsdK6b+zqQ==", "dependencies": { "fast-deep-equal": "^3.1.3", "lodash": "^4.17.21" @@ -3014,9 +3038,9 @@ } }, "node_modules/@togethercrew.dev/db": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/@togethercrew.dev/db/-/db-2.5.1.tgz", - "integrity": "sha512-I9rf6mMTrv3x0gt81UFzNY2ximsPo11nw1KLUC04IJm0nOuQO1hLlBqeM6izhsZhXVt4aVdbOEnY//YCbpZ8uQ==", + "version": "3.0.16", + "resolved": "https://registry.npmjs.org/@togethercrew.dev/db/-/db-3.0.16.tgz", + "integrity": "sha512-HzvK7ckkdNzpRhlj/94D1GLPUZqZGyozcZfkz2vN25mByMDe+NPE/IC2LK8RlcdZHLRjlUiyvfsbv+7+h9iqcA==", "dependencies": { "discord.js": "^14.7.1", "joi": "^17.7.0", @@ -3307,9 +3331,9 @@ } }, "node_modules/@types/ws": { - "version": "8.5.5", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz", - "integrity": "sha512-lwhs8hktwxSjf9UaZ9tG5M03PGogvFaH8gUgLNbN9HKIg0dvv6q+gkSuJ8HN4/VbyxkuLzCjlN7GquQ0gUJfIg==", + "version": "8.5.9", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.9.tgz", + "integrity": "sha512-jbdrY0a8lxfdTp/+r7Z4CkycbOFN8WX+IOchLJr3juT/xzbJ8URyTVSJ/hvNdadTgM1mnedb47n+Y31GsFnQlg==", "dependencies": { "@types/node": "*" } @@ -4323,17 +4347,6 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, - "node_modules/busboy": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", - "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", - "dependencies": { - "streamsearch": "^1.1.0" - }, - "engines": { - "node": ">=10.16.0" - } - }, "node_modules/call-bind": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", @@ -4885,29 +4898,29 @@ } }, "node_modules/discord-api-types": { - "version": "0.37.50", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.50.tgz", - "integrity": "sha512-X4CDiMnDbA3s3RaUXWXmgAIbY1uxab3fqe3qwzg5XutR3wjqi7M3IkgQbsIBzpqBN2YWr/Qdv7JrFRqSgb4TFg==" + "version": "0.37.61", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.61.tgz", + "integrity": "sha512-o/dXNFfhBpYHpQFdT6FWzeO7pKc838QeeZ9d91CfVAtpr5XLK4B/zYxQbYgPdoMiTDvJfzcsLW5naXgmHGDNXw==" }, "node_modules/discord.js": { - "version": "14.13.0", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.13.0.tgz", - "integrity": "sha512-Kufdvg7fpyTEwANGy9x7i4od4yu5c6gVddGi5CKm4Y5a6sF0VBODObI3o0Bh7TGCj0LfNT8Qp8z04wnLFzgnbA==", - "dependencies": { - "@discordjs/builders": "^1.6.5", - "@discordjs/collection": "^1.5.3", - "@discordjs/formatters": "^0.3.2", - "@discordjs/rest": "^2.0.1", - "@discordjs/util": "^1.0.1", - "@discordjs/ws": "^1.0.1", - "@sapphire/snowflake": "^3.5.1", - "@types/ws": "^8.5.5", - "discord-api-types": "0.37.50", - "fast-deep-equal": "^3.1.3", - "lodash.snakecase": "^4.1.1", - "tslib": "^2.6.1", - "undici": "5.22.1", - "ws": "^8.13.0" + "version": "14.14.1", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.14.1.tgz", + "integrity": "sha512-/hUVzkIerxKHyRKopJy5xejp4MYKDPTszAnpYxzVVv4qJYf+Tkt+jnT2N29PIPschicaEEpXwF2ARrTYHYwQ5w==", + "dependencies": { + "@discordjs/builders": "^1.7.0", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.3.3", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", + "@discordjs/ws": "^1.0.2", + "@sapphire/snowflake": "3.5.1", + "@types/ws": "8.5.9", + "discord-api-types": "0.37.61", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "tslib": "2.6.2", + "undici": "5.27.2", + "ws": "8.14.2" }, "engines": { "node": ">=16.11.0" @@ -8726,9 +8739,9 @@ } }, "node_modules/magic-bytes.js": { - "version": "1.0.17", - "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.0.17.tgz", - "integrity": "sha512-PEDpPzHpKe5AxkVmQrNPHFRvPN2ELkkj3eIg4IZO9JdhBiAY3aU53lgYXs9j8B7lpza+QiW0UA4QHCH7EskSeg==" + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.5.0.tgz", + "integrity": "sha512-wJkXvutRbNWcc37tt5j1HyOK1nosspdh3dj6LUYYAvF6JYNqs53IfRvK9oEpcwiDA1NdoIi64yAMfdivPeVAyw==" }, "node_modules/make-dir": { "version": "4.0.0", @@ -9320,9 +9333,9 @@ "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==" }, "node_modules/nodemon": { - "version": "2.0.22", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.22.tgz", - "integrity": "sha512-B8YqaKMmyuCO7BowF1Z1/mkPqLk6cs/l63Ojtd6otKjMx47Dq1utxfRxcavH1I7VSaL8n5BUaoutadnsX3AAVQ==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.1.tgz", + "integrity": "sha512-g9AZ7HmkhQkqXkRc20w+ZfQ73cHLbE8hnPbtaFbFtCumZsjyMhKk9LajQ07U5Ux28lvFjZ5X7HvWR1xzU8jHVw==", "dev": true, "dependencies": { "chokidar": "^3.5.2", @@ -9330,8 +9343,8 @@ "ignore-by-default": "^1.0.1", "minimatch": "^3.1.2", "pstree.remy": "^1.1.8", - "semver": "^5.7.1", - "simple-update-notifier": "^1.0.7", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", "supports-color": "^5.5.0", "touch": "^3.1.0", "undefsafe": "^2.0.5" @@ -9340,7 +9353,7 @@ "nodemon": "bin/nodemon.js" }, "engines": { - "node": ">=8.10.0" + "node": ">=10" }, "funding": { "type": "opencollective", @@ -9356,15 +9369,39 @@ "ms": "^2.1.1" } }, + "node_modules/nodemon/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/nodemon/node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, "bin": { - "semver": "bin/semver" + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, + "node_modules/nodemon/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, "node_modules/nopt": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", @@ -10307,26 +10344,50 @@ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, "node_modules/simple-update-notifier": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-1.1.0.tgz", - "integrity": "sha512-VpsrsJSUcJEseSbMHkrsrAVSdvVS5I96Qo1QAQ4FxQ9wXFcB+pjj7FB7/us9+GcgfW4ziHtYMc1J0PLczb55mg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", "dev": true, "dependencies": { - "semver": "~7.0.0" + "semver": "^7.5.3" }, "engines": { - "node": ">=8.10.0" + "node": ">=10" + } + }, + "node_modules/simple-update-notifier/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" } }, "node_modules/simple-update-notifier/node_modules/semver": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", - "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, "bin": { "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, + "node_modules/simple-update-notifier/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", @@ -10446,14 +10507,6 @@ "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" }, - "node_modules/streamsearch": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", - "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", - "engines": { - "node": ">=10.0.0" - } - }, "node_modules/string_decoder": { "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", @@ -11103,11 +11156,11 @@ "dev": true }, "node_modules/undici": { - "version": "5.22.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.22.1.tgz", - "integrity": "sha512-Ji2IJhFXZY0x/0tVBXeQwgPlLWw13GVzpsWPQ3rV50IFMMof2I55PZZxtm4P6iNq+L5znYN9nSTAq0ZyE6lSJw==", + "version": "5.27.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.27.2.tgz", + "integrity": "sha512-iS857PdOEy/y3wlM3yRp+6SNQQ6xU0mmZcwRSriqk+et/cwWAtwmIGf6WkoDN2EK/AMdCO/dfXzIwi+rFMrjjQ==", "dependencies": { - "busboy": "^1.6.0" + "@fastify/busboy": "^2.0.0" }, "engines": { "node": ">=14.0" diff --git a/package.json b/package.json index d40f9545..ee20b1d3 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "homepage": "https://github.com/Behzad-rabiei/tc-discordBot#readme", "dependencies": { "@sentry/node": "^7.51.2", - "@togethercrew.dev/db": "^2.5.1", + "@togethercrew.dev/db": "^3.0.16", "@togethercrew.dev/tc-messagebroker": "^0.0.40", "babel-jest": "^29.5.0", "bullmq": "^3.14.0", @@ -60,11 +60,11 @@ "eslint-plugin-promise": "^6.1.1", "jest": "^29.5.0", "node-mocks-http": "^1.12.2", - "nodemon": "^2.0.22", + "nodemon": "^3.0.1", "prettier": "^2.8.8", "supertest": "^6.3.3", "ts-jest": "^29.1.0", "ts-node": "^10.9.1", "typescript": "^5.0.4" } -} \ No newline at end of file +} From 5cf554494ad58e7e15db1d7d9df45df4700c8232 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 24 Nov 2023 23:02:11 +0330 Subject: [PATCH 02/17] [FEAUTRE]: use mongo-lib databaseManager --- src/database/connection.ts | 46 ------------------- src/events/channel/channelCreate.ts | 2 +- src/events/channel/channelDelete.ts | 2 +- src/events/channel/channelUpdate.ts | 2 +- src/events/client/ready.ts | 2 +- src/events/member/guildMemberAdd.ts | 2 +- src/events/member/guildMemberRemove.ts | 2 +- src/events/member/guildMemberUpdate.ts | 3 +- src/events/role/roleCreate.ts | 2 +- src/events/role/roleDelete.ts | 2 +- src/events/role/roleUpdate.ts | 2 +- src/events/user/userUpdate.ts | 2 +- src/functions/cronJon.ts | 2 +- src/index.ts | 3 +- ...isgeneratedbyweebhook-to-rawinfo-schema.ts | 2 +- src/migrations/utils/template.ts | 2 +- 16 files changed, 15 insertions(+), 63 deletions(-) delete mode 100644 src/database/connection.ts diff --git a/src/database/connection.ts b/src/database/connection.ts deleted file mode 100644 index a112bf63..00000000 --- a/src/database/connection.ts +++ /dev/null @@ -1,46 +0,0 @@ -import mongoose, { Connection } from 'mongoose'; -import { - heatMapSchema, - rawInfoSchema, - MemberActivitySchema, - guildMemberSchema, - channelSchema, - roleSchema, - type IHeatMap, - type IRawInfo, - type IMemberActivity, - type IGuildMember, - type IChannel, - type IRole, -} from '@togethercrew.dev/db'; -import { type Snowflake } from 'discord.js'; - -export default class DatabaseManager { - private static instance: DatabaseManager; - private modelCache: Record = {}; - public static getInstance(): DatabaseManager { - if (typeof DatabaseManager.instance === 'undefined') { - DatabaseManager.instance = new DatabaseManager(); - } - return DatabaseManager.instance; - } - - public getTenantDb(tenantId: Snowflake): Connection { - const dbName = tenantId; - const db = mongoose.connection.useDb(dbName, { useCache: true }); - this.setupModels(db); - return db; - } - - private setupModels(db: Connection): void { - if (!this.modelCache[db.name]) { - db.model('HeatMap', heatMapSchema); - db.model('RawInfo', rawInfoSchema); - db.model('MemberActivity', MemberActivitySchema); - db.model('GuildMember', guildMemberSchema); - db.model('Channel', channelSchema); - db.model('Role', roleSchema); - this.modelCache[db.name] = true; - } - } -} diff --git a/src/events/channel/channelCreate.ts b/src/events/channel/channelCreate.ts index e86dcf2d..8282b097 100644 --- a/src/events/channel/channelCreate.ts +++ b/src/events/channel/channelCreate.ts @@ -1,6 +1,6 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; import { channelService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ChannelCreate' }); diff --git a/src/events/channel/channelDelete.ts b/src/events/channel/channelDelete.ts index ee0f99c9..5e98f55a 100644 --- a/src/events/channel/channelDelete.ts +++ b/src/events/channel/channelDelete.ts @@ -1,6 +1,6 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; import { channelService, guildService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ChannelDelete' }); diff --git a/src/events/channel/channelUpdate.ts b/src/events/channel/channelUpdate.ts index 43a94d36..1848d501 100644 --- a/src/events/channel/channelUpdate.ts +++ b/src/events/channel/channelUpdate.ts @@ -1,6 +1,6 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; import { channelService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ChannelUpdate' }); diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index b7cf0b6a..438e5a1b 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -3,7 +3,7 @@ import { guildService } from '../../database/services'; import fetchMembers from '../../functions/fetchMembers'; import fetchChannels from '../../functions/fetchChannels'; import fetchRoles from '../../functions/fetchRoles'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ClientReady' }); diff --git a/src/events/member/guildMemberAdd.ts b/src/events/member/guildMemberAdd.ts index 4004c55f..1afc1d3f 100644 --- a/src/events/member/guildMemberAdd.ts +++ b/src/events/member/guildMemberAdd.ts @@ -1,6 +1,6 @@ import { Events, GuildMember } from 'discord.js'; import { guildMemberService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildMemberAdd' }); diff --git a/src/events/member/guildMemberRemove.ts b/src/events/member/guildMemberRemove.ts index a84f5cd1..157e66e6 100644 --- a/src/events/member/guildMemberRemove.ts +++ b/src/events/member/guildMemberRemove.ts @@ -1,6 +1,6 @@ import { Events, GuildMember } from 'discord.js'; import { guildMemberService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildMemberRemove' }); diff --git a/src/events/member/guildMemberUpdate.ts b/src/events/member/guildMemberUpdate.ts index e90f7213..d79260db 100644 --- a/src/events/member/guildMemberUpdate.ts +++ b/src/events/member/guildMemberUpdate.ts @@ -1,7 +1,6 @@ import { Events, GuildMember } from 'discord.js'; import { guildMemberService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; - +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildMemberUpdate' }); diff --git a/src/events/role/roleCreate.ts b/src/events/role/roleCreate.ts index 5c2ffc94..32677c2b 100644 --- a/src/events/role/roleCreate.ts +++ b/src/events/role/roleCreate.ts @@ -1,6 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildRoleCreate' }); diff --git a/src/events/role/roleDelete.ts b/src/events/role/roleDelete.ts index 386b3986..8b5daa72 100644 --- a/src/events/role/roleDelete.ts +++ b/src/events/role/roleDelete.ts @@ -1,6 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; diff --git a/src/events/role/roleUpdate.ts b/src/events/role/roleUpdate.ts index 40012a8e..8b015e8f 100644 --- a/src/events/role/roleUpdate.ts +++ b/src/events/role/roleUpdate.ts @@ -1,6 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildRoleUpdate' }); diff --git a/src/events/user/userUpdate.ts b/src/events/user/userUpdate.ts index b59fa7f0..6f4fa11f 100644 --- a/src/events/user/userUpdate.ts +++ b/src/events/user/userUpdate.ts @@ -1,6 +1,6 @@ import { Events, User } from 'discord.js'; import { guildMemberService, guildService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'UserUpdate' }); diff --git a/src/functions/cronJon.ts b/src/functions/cronJon.ts index 3e21bfea..9842c1f5 100644 --- a/src/functions/cronJon.ts +++ b/src/functions/cronJon.ts @@ -3,7 +3,7 @@ import { guildService } from '../database/services'; import { ChoreographyDict, MBConnection, Status } from '@togethercrew.dev/tc-messagebroker'; import guildExtraction from './guildExtraction'; import parentLogger from '../config/logger'; -import DatabaseManager from '../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; const logger = parentLogger.child({ event: 'CronJob' }); diff --git a/src/index.ts b/src/index.ts index a152c7b8..bb9ed65f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import { Queue, Worker, Job } from 'bullmq'; import RabbitMQ, { Event, MBConnection, Queue as RabbitMQQueue } from '@togethercrew.dev/tc-messagebroker'; // import './rabbitmqEvents' // we need this import statement here to initialize RabbitMQ events import { connectDB } from './database'; -import { databaseService } from '@togethercrew.dev/db'; +import { DatabaseManager } from '@togethercrew.dev/db'; import guildExtraction from './functions/guildExtraction'; import sendDirectMessage from './functions/sendDirectMessage'; import { createPrivateThreadAndSendMessage } from './functions/thread'; @@ -15,7 +15,6 @@ import fetchMembers from './functions/fetchMembers'; import fetchChannels from './functions/fetchChannels'; import fetchRoles from './functions/fetchRoles'; import parentLogger from './config/logger'; -import DatabaseManager from './database/connection'; const logger = parentLogger.child({ module: 'App' }); diff --git a/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts b/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts index 54176114..a6601624 100644 --- a/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts +++ b/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts @@ -4,7 +4,7 @@ import { guildService } from '../../database/services'; import { connectDB } from '../../database'; import config from '../../config'; import webhookLogic from '../utils/webhookLogic'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; const { Guilds, diff --git a/src/migrations/utils/template.ts b/src/migrations/utils/template.ts index 4b0954ee..352e3fa8 100644 --- a/src/migrations/utils/template.ts +++ b/src/migrations/utils/template.ts @@ -1,6 +1,6 @@ import { connectDB } from '../../database'; import 'dotenv/config'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; export const up = async () => { await connectDB(); From f568ac2f87e006aac71c09306e73d70c44889131 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 24 Nov 2023 23:07:49 +0330 Subject: [PATCH 03/17] [FEAUTRE]: add platform service and delete guild service --- src/database/services/guild.service.ts | 76 ----------------------- src/database/services/index.ts | 4 +- src/database/services/platform.service.ts | 76 +++++++++++++++++++++++ 3 files changed, 78 insertions(+), 78 deletions(-) delete mode 100644 src/database/services/guild.service.ts create mode 100644 src/database/services/platform.service.ts diff --git a/src/database/services/guild.service.ts b/src/database/services/guild.service.ts deleted file mode 100644 index 212628a8..00000000 --- a/src/database/services/guild.service.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Guild, IGuild, IGuildUpdateBody } from '@togethercrew.dev/db'; -import { Snowflake, Client } from 'discord.js'; -import parentLogger from '../../config/logger'; - -const logger = parentLogger.child({ module: 'GuildService' }); - -/** - * get guild by query - * @param {Object} filter - * @returns {Promise} - */ -async function getGuild(filter: object): Promise { - return Guild.findOne(filter); -} - -/** - * Retrieve and return multiple guild entries that match the provided filter. - * @param {object} filter - Filter criteria to match the desired guild entries. - * @returns {Promise} - A promise that resolves to an array of matching guild entries. - */ -async function getGuilds(filter: object): Promise { - return await Guild.find(filter); -} - -/** - * Update the guild entry that matches the provided filter with the provided data. - * @param {object} filter - Filter criteria to match the desired guild entry for update. - * @param {IGuildUpdateBody} updateBody - Updated information for the guild entry. - * @returns {Promise} - A promise that resolves to the updated guild entry, or null if not found. - */ -async function updateGuild(filter: object, updateBody: IGuildUpdateBody): Promise { - try { - const guild = await Guild.findOne(filter); - if (!guild) { - return null; - } - Object.assign(guild, updateBody); - return await guild.save(); - } catch (error) { - logger.error({ database: 'RnDAO', filter, updateBody, error }, 'Failed to update guild'); - return null; - } -} - -/** - * Update multiple guild entries that match the provided filter with the provided data. - * @param {object} filter - Filter criteria to match the desired guild entries for update. - * @param {IGuildUpdateBody} updateBody - Updated information for the guild entry. - * @returns {Promise} - A promise that resolves to the number of guild entries updated. - */ -async function updateManyGuilds(filter: object, updateBody: IGuildUpdateBody): Promise { - try { - const updateResult = await Guild.updateMany(filter, updateBody); - const modifiedCount = updateResult.modifiedCount; - return modifiedCount; - } catch (error) { - logger.error({ database: 'RnDAO', filter, updateBody, error }, 'Failed to update guilds'); - return 0; - } -} - -async function checkBotAccessToGuild(client: Client, guildId: Snowflake) { - if (!client.guilds.cache.has(guildId)) { - await updateGuild({ guildId }, { isDisconnected: false }); - return false; - } - return true; -} - -export default { - getGuild, - getGuilds, - updateGuild, - updateManyGuilds, - checkBotAccessToGuild, -}; diff --git a/src/database/services/index.ts b/src/database/services/index.ts index 5d7a9d19..f1cad469 100644 --- a/src/database/services/index.ts +++ b/src/database/services/index.ts @@ -1,6 +1,6 @@ import guildMemberService from './guildMember.service'; import rawInfoService from './rawInfo.service'; -import guildService from './guild.service'; +import platformService from './platform.service'; import roleService from './role.service'; import channelService from './channel.service'; -export { guildMemberService, guildService, rawInfoService, roleService, channelService }; +export { guildMemberService, platformService, rawInfoService, roleService, channelService }; diff --git a/src/database/services/platform.service.ts b/src/database/services/platform.service.ts new file mode 100644 index 00000000..f9f51150 --- /dev/null +++ b/src/database/services/platform.service.ts @@ -0,0 +1,76 @@ +import { Platform, IPlatform, IPlatformUpdateBody } from '@togethercrew.dev/db'; +import { Snowflake, Client } from 'discord.js'; +import parentLogger from '../../config/logger'; + +const logger = parentLogger.child({ module: 'PlatformService' }); + +/** + * get platform by query + * @param {Object} filter + * @returns {Promise} + */ +async function getPlatform(filter: object): Promise { + return Platform.findOne(filter); +} + +/** + * Retrieve and return multiple platform entries that match the provided filter. + * @param {object} filter - Filter criteria to match the desired platform entries. + * @returns {Promise} - A promise that resolves to an array of matching platform entries. + */ +async function getPlatforms(filter: object): Promise { + return await Platform.find(filter); +} + +/** + * Update the platform entry that matches the provided filter with the provided data. + * @param {object} filter - Filter criteria to match the desired platform entry for update. + * @param {IPlatformUpdateBody} updateBody - Updated information for the platform entry. + * @returns {Promise} - A promise that resolves to the updated platform entry, or null if not found. + */ +async function updatePlatform(filter: object, updateBody: IPlatformUpdateBody): Promise { + try { + const platofrm = await Platform.findOne(filter); + if (!platofrm) { + return null; + } + Object.assign(platofrm, updateBody); + return await platofrm.save(); + } catch (error) { + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platofrm'); + return null; + } +} + +/** + * Update multiple platform entries that match the provided filter with the provided data. + * @param {object} filter - Filter criteria to match the desired platform entries for update. + * @param {IPlatformUpdateBody} updateBody - Updated information for the platform entry. + * @returns {Promise} - A promise that resolves to the number of platform entries updated. + */ +async function updateManyPlatforms(filter: object, updateBody: IPlatformUpdateBody): Promise { + try { + const updateResult = await Platform.updateMany(filter, updateBody); + const modifiedCount = updateResult.modifiedCount; + return modifiedCount; + } catch (error) { + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platofrms'); + return 0; + } +} + +async function checkBotAccessToGuild(client: Client, guildId: Snowflake) { + if (!client.guilds.cache.has(guildId)) { + await updatePlatform({ 'metadata.id': guildId }, { disconnectedAt: new Date() }); + return false; + } + return true; +} + +export default { + getPlatform, + getPlatforms, + updatePlatform, + updateManyPlatforms, + checkBotAccessToGuild, +}; From 48eac0005cb63c7abacbcd4ef7f9b943b126eded Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 24 Nov 2023 23:18:03 +0330 Subject: [PATCH 04/17] [FEATURE]: replace the platform with guild in events --- src/database/services/platform.service.ts | 20 ++++++++++++++------ src/events/channel/channelDelete.ts | 12 +++++++----- src/events/client/ready.ts | 23 +++++++++++++---------- src/events/role/roleDelete.ts | 1 - src/events/user/userUpdate.ts | 11 +++++++---- 5 files changed, 41 insertions(+), 26 deletions(-) diff --git a/src/database/services/platform.service.ts b/src/database/services/platform.service.ts index f9f51150..f9d4bf2a 100644 --- a/src/database/services/platform.service.ts +++ b/src/database/services/platform.service.ts @@ -30,14 +30,22 @@ async function getPlatforms(filter: object): Promise { */ async function updatePlatform(filter: object, updateBody: IPlatformUpdateBody): Promise { try { - const platofrm = await Platform.findOne(filter); - if (!platofrm) { + const platform = await Platform.findOne(filter); + if (!platform) { return null; } - Object.assign(platofrm, updateBody); - return await platofrm.save(); + + if (updateBody.metadata) { + updateBody.metadata = { + ...platform.metadata, + ...updateBody.metadata + }; + } + + Object.assign(platform, updateBody); + return await platform.save(); } catch (error) { - logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platofrm'); + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platform'); return null; } } @@ -54,7 +62,7 @@ async function updateManyPlatforms(filter: object, updateBody: IPlatformUpdateBo const modifiedCount = updateResult.modifiedCount; return modifiedCount; } catch (error) { - logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platofrms'); + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platforms'); return 0; } } diff --git a/src/events/channel/channelDelete.ts b/src/events/channel/channelDelete.ts index 5e98f55a..5db0749a 100644 --- a/src/events/channel/channelDelete.ts +++ b/src/events/channel/channelDelete.ts @@ -1,8 +1,9 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; -import { channelService, guildService } from '../../database/services'; +import { channelService, platformService } from '../../database/services'; import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; +console.log('FLAG') const logger = parentLogger.child({ event: 'ChannelDelete' }); export default { @@ -16,11 +17,12 @@ export default { try { const channelDoc = await channelService.getChannel(connection, { channelId: channel.id }); await channelDoc?.softDelete(); - const guildDoc = await guildService.getGuild({ guildId: channel.guild.id }); - const updatedSelecetdChannels = guildDoc?.selectedChannels?.filter( - selectedChannel => selectedChannel.channelId !== channel.id + const platformDoc = await platformService.getPlatform({ 'metadata.id': channel.guild.id }); + const updatedSelecetdChannels = platformDoc?.metadata?.selectedChannels?.filter( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (selectedChannel: any) => selectedChannel.channelId !== channel.id ); - await guildService.updateGuild({ guildId: channel.guild.id }, { selectedChannels: updatedSelecetdChannels }); + await platformService.updatePlatform({ 'metadata.id': channel.guild.id }, { metadata: { selectedChannels: updatedSelecetdChannels } }); logger.info(logFields, 'event is done'); } catch (err) { diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 438e5a1b..91f6cdaf 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -1,11 +1,14 @@ import { Events, Client } from 'discord.js'; -import { guildService } from '../../database/services'; +import { platformService } from '../../database/services'; import fetchMembers from '../../functions/fetchMembers'; import fetchChannels from '../../functions/fetchChannels'; import fetchRoles from '../../functions/fetchRoles'; import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; +console.log('FLAG') + + const logger = parentLogger.child({ event: 'ClientReady' }); export default { @@ -13,17 +16,17 @@ export default { once: true, async execute(client: Client) { logger.info('event is running'); - const guilds = await guildService.getGuilds({ isDisconnected: false }); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); + const platforms = await platformService.getPlatforms({ disconnectedAt: null }); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); try { - logger.info({ guild_id: guilds[i].guildId }, 'Fetching guild members, roles,and channels'); - await fetchMembers(connection, client, guilds[i].guildId); - await fetchRoles(connection, client, guilds[i].guildId); - await fetchChannels(connection, client, guilds[i].guildId); - logger.info({ guild_id: guilds[i].guildId }, 'Fetching guild members, roles, channels is done'); + logger.info({ platform_id: platforms[i].metadata?.id }, 'Fetching guild members, roles,and channels'); + await fetchMembers(connection, client, platforms[i].metadata?.id); + await fetchRoles(connection, client, platforms[i].metadata?.id); + await fetchChannels(connection, client, platforms[i].metadata?.id); + logger.info({ platform_id: platforms[i].metadata?.id }, 'Fetching guild members, roles, channels is done'); } catch (err) { - logger.error({ guild_id: guilds[i].guildId, err }, 'Fetching guild members, roles,and channels failed'); + logger.error({ platform_id: platforms[i].metadata?.id, err }, 'Fetching guild members, roles,and channels failed'); logger.info('event is done'); } } diff --git a/src/events/role/roleDelete.ts b/src/events/role/roleDelete.ts index 8b5daa72..bfc200d8 100644 --- a/src/events/role/roleDelete.ts +++ b/src/events/role/roleDelete.ts @@ -1,7 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; import { DatabaseManager } from '@togethercrew.dev/db'; - import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildRoleDelete' }); diff --git a/src/events/user/userUpdate.ts b/src/events/user/userUpdate.ts index 6f4fa11f..626a1b67 100644 --- a/src/events/user/userUpdate.ts +++ b/src/events/user/userUpdate.ts @@ -1,8 +1,11 @@ import { Events, User } from 'discord.js'; -import { guildMemberService, guildService } from '../../database/services'; +import { guildMemberService, platformService } from '../../database/services'; import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; +console.log('FLAG') + + const logger = parentLogger.child({ event: 'UserUpdate' }); export default { name: Events.UserUpdate, @@ -11,9 +14,9 @@ export default { const logFields = { user_id: newUser.id }; logger.info(logFields, 'event is running'); try { - const guilds = await guildService.getGuilds({}); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); + const platforms = await platformService.getPlatforms({ disconnectedAt: null }); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); await guildMemberService.updateGuildMember( connection, { discordId: newUser.id }, From 28818713f332e3b2d0aabc2650730a010e446fae Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 24 Nov 2023 23:50:04 +0330 Subject: [PATCH 05/17] [FEATURE]: update platform service --- src/database/services/platform.service.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/database/services/platform.service.ts b/src/database/services/platform.service.ts index f9d4bf2a..665e0c8b 100644 --- a/src/database/services/platform.service.ts +++ b/src/database/services/platform.service.ts @@ -1,3 +1,4 @@ +import { HydratedDocument } from 'mongoose'; import { Platform, IPlatform, IPlatformUpdateBody } from '@togethercrew.dev/db'; import { Snowflake, Client } from 'discord.js'; import parentLogger from '../../config/logger'; @@ -9,7 +10,7 @@ const logger = parentLogger.child({ module: 'PlatformService' }); * @param {Object} filter * @returns {Promise} */ -async function getPlatform(filter: object): Promise { +async function getPlatform(filter: object): Promise | null> { return Platform.findOne(filter); } @@ -18,7 +19,7 @@ async function getPlatform(filter: object): Promise { * @param {object} filter - Filter criteria to match the desired platform entries. * @returns {Promise} - A promise that resolves to an array of matching platform entries. */ -async function getPlatforms(filter: object): Promise { +async function getPlatforms(filter: object): Promise[]> { return await Platform.find(filter); } @@ -28,7 +29,7 @@ async function getPlatforms(filter: object): Promise { * @param {IPlatformUpdateBody} updateBody - Updated information for the platform entry. * @returns {Promise} - A promise that resolves to the updated platform entry, or null if not found. */ -async function updatePlatform(filter: object, updateBody: IPlatformUpdateBody): Promise { +async function updatePlatform(filter: object, updateBody: IPlatformUpdateBody): Promise | null> { try { const platform = await Platform.findOne(filter); if (!platform) { From a8826401cb9ce444b1d596a9c12bcaa5a502be03 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Mon, 27 Nov 2023 16:45:17 +0330 Subject: [PATCH 06/17] [FEATURE]: update functions to CC --- src/events/client/ready.ts | 2 +- src/functions/cronJon.ts | 28 ++++++++++++++------------ src/functions/fetchChannels.ts | 18 +++++++++-------- src/functions/fetchMembers.ts | 21 +++++++++++--------- src/functions/guildExtraction.ts | 34 +++++++++++++++++--------------- 5 files changed, 56 insertions(+), 47 deletions(-) diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 91f6cdaf..5fdf7fc1 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -20,7 +20,7 @@ export default { for (let i = 0; i < platforms.length; i++) { const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); try { - logger.info({ platform_id: platforms[i].metadata?.id }, 'Fetching guild members, roles,and channels'); + logger.info({ platform_id: platforms[i].id }, 'Fetching guild members, roles,and channels'); await fetchMembers(connection, client, platforms[i].metadata?.id); await fetchRoles(connection, client, platforms[i].metadata?.id); await fetchChannels(connection, client, platforms[i].metadata?.id); diff --git a/src/functions/cronJon.ts b/src/functions/cronJon.ts index 9842c1f5..43872d15 100644 --- a/src/functions/cronJon.ts +++ b/src/functions/cronJon.ts @@ -1,22 +1,24 @@ -import { Client, Snowflake } from 'discord.js'; -import { guildService } from '../database/services'; +import { Client } from 'discord.js'; +import { Types } from 'mongoose'; +import { platformService } from '../database/services'; import { ChoreographyDict, MBConnection, Status } from '@togethercrew.dev/tc-messagebroker'; import guildExtraction from './guildExtraction'; import parentLogger from '../config/logger'; import { DatabaseManager } from '@togethercrew.dev/db'; +console.log('FLAG') const logger = parentLogger.child({ event: 'CronJob' }); -async function createAndStartCronJobSaga(guildId: Snowflake) { +async function createAndStartCronJobSaga(platformId: Types.ObjectId) { try { const saga = await MBConnection.models.Saga.create({ status: Status.NOT_STARTED, - data: { guildId }, + data: { platformId }, choreography: ChoreographyDict.DISCORD_SCHEDULED_JOB, }); await saga.start(); } catch (err) { - logger.error({ guild_Id: guildId, err }, 'Faield to create saga'); + logger.error({ platform_Id: platformId, err }, 'Failed to create saga'); } } @@ -26,16 +28,16 @@ async function createAndStartCronJobSaga(guildId: Snowflake) { */ export default async function cronJob(client: Client) { logger.info('event is running'); - const guilds = await guildService.getGuilds({ isDisconnected: false }); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); + const platforms = await platformService.getPlatforms({ disconnectedAt: null }); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); try { - logger.info({ guild_id: guilds[i].guildId }, 'is running cronJob for guild'); - await guildExtraction(connection, client, guilds[i].guildId); - await createAndStartCronJobSaga(guilds[i].guildId); - logger.info({ guild_id: guilds[i].guildId }, 'cronJob is done for guild'); + logger.info({ platform_Id: platforms[i].metadata?.id }, 'is running cronJob for platform'); + await guildExtraction(connection, client, platforms[i]); + await createAndStartCronJobSaga(platforms[i].metadata?.id); + logger.info({ platform_Id: platforms[i].metadata?.id }, 'cronJob is done for platform'); } catch (err) { - logger.error({ guild_id: guilds[i].guildId, err }, 'CronJob faield for guild'); + logger.error({ platform_Id: platforms[i].metadata?.id, err }, 'CronJob Failed for platform'); } } diff --git a/src/functions/fetchChannels.ts b/src/functions/fetchChannels.ts index 4db591af..2098a672 100644 --- a/src/functions/fetchChannels.ts +++ b/src/functions/fetchChannels.ts @@ -1,8 +1,10 @@ -import { Client, Snowflake, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; -import { Connection } from 'mongoose'; +import { Client, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db'; import { IChannel } from '@togethercrew.dev/db'; -import { channelService, guildService } from '../database/services'; +import { channelService, platformService } from '../database/services'; import parentLogger from '../config/logger'; +console.log('FLAG') const logger = parentLogger.child({ module: 'FetchChannels' }); @@ -28,13 +30,13 @@ function pushChannelsToArray( * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract text and voice channels from. */ -export default async function fetchGuildChannels(connection: Connection, client: Client, guildId: Snowflake) { +export default async function fetchGuildChannels(connection: Connection, client: Client, platform: HydratedDocument) { try { - if (!client.guilds.cache.has(guildId)) { - await guildService.updateGuild({ guildId }, { isDisconnected: false }); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); + const guild = await client.guilds.fetch(platform.metadata?.id); const channelsToStore: IChannel[] = []; const textAndVoiceChannels = [...guild.channels.cache.values()].filter( channel => channel.type === 0 || channel.type === 2 || channel.type === 4 @@ -42,6 +44,6 @@ export default async function fetchGuildChannels(connection: Connection, client: pushChannelsToArray(channelsToStore, textAndVoiceChannels); await channelService.createChannels(connection, channelsToStore); // assuming a 'channelService' } catch (error) { - logger.error({ guildId, error }, 'Failed to fetch channels'); + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch channels'); } } diff --git a/src/functions/fetchMembers.ts b/src/functions/fetchMembers.ts index 424d9ab2..dc01d50d 100644 --- a/src/functions/fetchMembers.ts +++ b/src/functions/fetchMembers.ts @@ -1,8 +1,11 @@ -import { GuildMember, Client, Snowflake } from 'discord.js'; -import { Connection } from 'mongoose'; -import { IGuildMember } from '@togethercrew.dev/db'; -import { guildMemberService, guildService } from '../database/services'; +import { GuildMember, Client } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db'; +import { IGuildMember, } from '@togethercrew.dev/db'; +import { guildMemberService, platformService } from '../database/services'; + import parentLogger from '../config/logger'; +console.log('FLAG') const logger = parentLogger.child({ module: 'FetchMembers' }); @@ -26,18 +29,18 @@ function pushMembersToArray(arr: IGuildMember[], guildMembersArray: GuildMember[ * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract information from. */ -export default async function fetchGuildMembers(connection: Connection, client: Client, guildId: Snowflake) { +export default async function fetchGuildMembers(connection: Connection, client: Client, platform: HydratedDocument) { try { - if (!client.guilds.cache.has(guildId)) { - await guildService.updateGuild({ guildId }, { isDisconnected: false }); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); + const guild = await client.guilds.fetch(platform.metadata?.id); const membersToStore: IGuildMember[] = []; const fetchMembers = await guild.members.fetch(); pushMembersToArray(membersToStore, [...fetchMembers.values()]); await guildMemberService.createGuildMembers(connection, membersToStore); } catch (error) { - logger.error({ guildId, error }, 'Failed to fetch guild members'); + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch guild members'); } } diff --git a/src/functions/guildExtraction.ts b/src/functions/guildExtraction.ts index 79eb31ff..f24b5c55 100644 --- a/src/functions/guildExtraction.ts +++ b/src/functions/guildExtraction.ts @@ -1,9 +1,12 @@ -import { Client, Snowflake } from 'discord.js'; -import { guildService } from '../database/services'; +import { Client } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db'; +import { platformService } from '../database/services'; import handleFetchChannelMessages from './fetchMessages'; -import { Connection } from 'mongoose'; import parentLogger from '../config/logger'; +console.log('FLAG - isInProgress Update?? || selectedChannels array of object to string') + const logger = parentLogger.child({ module: 'GuildExtraction' }); /** * Extracts information from a given guild. @@ -11,28 +14,27 @@ const logger = parentLogger.child({ module: 'GuildExtraction' }); * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract information from. */ -export default async function guildExtraction(connection: Connection, client: Client, guildId: Snowflake) { - logger.info({ guild_id: guildId }, 'Guild extraction for guild is running'); +export default async function guildExtraction(connection: Connection, client: Client, platform: HydratedDocument) { + logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is running'); try { - const hasBotAccessToGuild = await guildService.checkBotAccessToGuild(client, guildId); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); - const guildDoc = await guildService.getGuild({ guildId }); - if (guildDoc && guildDoc.selectedChannels && guildDoc.period) { - await guildService.updateGuild({ guildId }, { isInProgress: true }); - const selectedChannelsIds = guildDoc.selectedChannels.map(selectedChannel => selectedChannel.channelId); - for (const channelId of selectedChannelsIds) { - const channel = await guild.channels.fetch(channelId); + const guild = await client.guilds.fetch(platform.metadata?.id); + if (platform.metadata?.selectedChannels && platform.metadata?.period) { + await platformService.updatePlatform({ _id: platform.id }, { metadata: { isInProgress: true } }); + + for (let i = 0; i < platform.metadata?.selectedChannels.length; i++) { + const channel = await guild.channels.fetch(platform.metadata?.selectedChannels[i]); if (channel) { if (channel.type !== 0) continue; - await handleFetchChannelMessages(connection, channel, guildDoc?.period); + await handleFetchChannelMessages(connection, channel, platform.metadata?.period); } } } } catch (err) { - logger.error({ guild_id: guildId, err }, 'Guild extraction CronJob failed for guild'); + logger.error({ guild_id: platform.metadata?.id, err }, 'Guild extraction CronJob failed for guild'); } - logger.info({ guild_id: guildId }, 'Guild extraction for guild is done'); + logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is done'); } From 7f08c3980ef68f1d1d4a1372ddfdbde1c1477be7 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Mon, 27 Nov 2023 16:45:44 +0330 Subject: [PATCH 07/17] [FEATURE]: update functions to CC --- src/events/client/ready.ts | 6 +++--- src/functions/fetchChannels.ts | 3 +-- src/functions/fetchRoles.ts | 22 ++++++++++++---------- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 5fdf7fc1..c953ba14 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -21,9 +21,9 @@ export default { const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); try { logger.info({ platform_id: platforms[i].id }, 'Fetching guild members, roles,and channels'); - await fetchMembers(connection, client, platforms[i].metadata?.id); - await fetchRoles(connection, client, platforms[i].metadata?.id); - await fetchChannels(connection, client, platforms[i].metadata?.id); + await fetchMembers(connection, client, platforms[i]); + await fetchRoles(connection, client, platforms[i]); + await fetchChannels(connection, client, platforms[i]); logger.info({ platform_id: platforms[i].metadata?.id }, 'Fetching guild members, roles, channels is done'); } catch (err) { logger.error({ platform_id: platforms[i].metadata?.id, err }, 'Fetching guild members, roles,and channels failed'); diff --git a/src/functions/fetchChannels.ts b/src/functions/fetchChannels.ts index 2098a672..55600adc 100644 --- a/src/functions/fetchChannels.ts +++ b/src/functions/fetchChannels.ts @@ -1,7 +1,6 @@ import { Client, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; import { Connection, HydratedDocument } from 'mongoose'; -import { IPlatform } from '@togethercrew.dev/db'; -import { IChannel } from '@togethercrew.dev/db'; +import { IPlatform, IChannel } from '@togethercrew.dev/db'; import { channelService, platformService } from '../database/services'; import parentLogger from '../config/logger'; console.log('FLAG') diff --git a/src/functions/fetchRoles.ts b/src/functions/fetchRoles.ts index 113050fc..38dcedc1 100644 --- a/src/functions/fetchRoles.ts +++ b/src/functions/fetchRoles.ts @@ -1,9 +1,11 @@ -import { Client, Snowflake, Role } from 'discord.js'; -import { Connection } from 'mongoose'; -import { IRole } from '@togethercrew.dev/db'; -import { roleService, guildService } from '../database/services'; +import { Client, Role } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform, IRole } from '@togethercrew.dev/db'; +import { roleService, platformService } from '../database/services'; import parentLogger from '../config/logger'; +console.log('FLAG') + const logger = parentLogger.child({ module: 'FetchRoles' }); /** @@ -25,17 +27,17 @@ function pushRolesToArray(arr: IRole[], roleArray: Role[]): IRole[] { * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract roles from. */ -export default async function fetchGuildRoles(connection: Connection, client: Client, guildId: Snowflake) { +export default async function fetchGuildRoles(connection: Connection, client: Client, platform: HydratedDocument) { try { - if (!client.guilds.cache.has(guildId)) { - await guildService.updateGuild({ guildId }, { isDisconnected: false }); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); + const guild = await client.guilds.fetch(platform.metadata?.id); const rolesToStore: IRole[] = []; pushRolesToArray(rolesToStore, [...guild.roles.cache.values()]); - await roleService.createRoles(connection, rolesToStore); // assuming a 'roleService' + await roleService.createRoles(connection, rolesToStore); } catch (error) { - logger.error({ guildId, error }, 'Failed to fetch roles'); + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch roles'); } } From 2ecf2b0d6feac65cbf0e5eee6f7c210ea5b3e7ec Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Mon, 27 Nov 2023 16:46:52 +0330 Subject: [PATCH 08/17] [FEATURE]: update migration to CC --- ...7863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts b/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts index a6601624..9c4f7fb2 100644 --- a/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts +++ b/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts @@ -1,6 +1,6 @@ import 'dotenv/config'; import { Client, GatewayIntentBits, } from 'discord.js'; -import { guildService } from '../../database/services'; +import { platformService } from '../../database/services'; import { connectDB } from '../../database'; import config from '../../config'; import webhookLogic from '../utils/webhookLogic'; @@ -22,10 +22,10 @@ export const up = async () => { await client.login(config.discord.botToken); await connectDB(); - const guilds = await guildService.getGuilds({}); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); - await webhookLogic(connection, client, guilds[i].guildId); + const platforms = await platformService.getPlatforms({}); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); + await webhookLogic(connection, client, platforms[i].metadata?.id); } }; From cf1694862532caf91915e8240b47409bceb6cd75 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Tue, 28 Nov 2023 13:26:27 +0330 Subject: [PATCH 09/17] [FEATURE]: allow platform icon to be empty --- src/events/client/ready.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index b7cf0b6a..f45ead75 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -29,4 +29,4 @@ export default { } logger.info('event is done'); }, -}; +}; \ No newline at end of file From 7d85ef2011f667049a2025e22275417d5e9ebbb9 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:00:50 +0330 Subject: [PATCH 10/17] [FEATURE]: update others to CC --- src/database/services/platform.service.ts | 2 +- src/functions/cronJon.ts | 2 +- src/index.ts | 58 +++++++++++++++-------- 3 files changed, 39 insertions(+), 23 deletions(-) diff --git a/src/database/services/platform.service.ts b/src/database/services/platform.service.ts index 665e0c8b..2af4dbaa 100644 --- a/src/database/services/platform.service.ts +++ b/src/database/services/platform.service.ts @@ -1,4 +1,4 @@ -import { HydratedDocument } from 'mongoose'; +import { HydratedDocument, ObjectId } from 'mongoose'; import { Platform, IPlatform, IPlatformUpdateBody } from '@togethercrew.dev/db'; import { Snowflake, Client } from 'discord.js'; import parentLogger from '../../config/logger'; diff --git a/src/functions/cronJon.ts b/src/functions/cronJon.ts index 43872d15..bc8438dc 100644 --- a/src/functions/cronJon.ts +++ b/src/functions/cronJon.ts @@ -34,7 +34,7 @@ export default async function cronJob(client: Client) { try { logger.info({ platform_Id: platforms[i].metadata?.id }, 'is running cronJob for platform'); await guildExtraction(connection, client, platforms[i]); - await createAndStartCronJobSaga(platforms[i].metadata?.id); + await createAndStartCronJobSaga(platforms[i].id); logger.info({ platform_Id: platforms[i].metadata?.id }, 'cronJob is done for platform'); } catch (err) { logger.error({ platform_Id: platforms[i].metadata?.id, err }, 'CronJob Failed for platform'); diff --git a/src/index.ts b/src/index.ts index bb9ed65f..9de709e9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,6 @@ import { Channel, ChannelType, Client, GatewayIntentBits, Snowflake, TextChannel } from 'discord.js'; +import { HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db' import config from './config'; import * as Sentry from '@sentry/node'; import loadEvents from './functions/loadEvents'; @@ -15,6 +17,7 @@ import fetchMembers from './functions/fetchMembers'; import fetchChannels from './functions/fetchChannels'; import fetchRoles from './functions/fetchRoles'; import parentLogger from './config/logger'; +import { platformService } from './database/services'; const logger = parentLogger.child({ module: 'App' }); @@ -46,16 +49,22 @@ const fetchMethod = async (msg: any) => { const { content } = msg; const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); logger.info({ saga: saga.data }, 'the saga info'); - const guildId = saga.data['guildId']; - const isGuildCreated = saga.data['created']; - const connection = DatabaseManager.getInstance().getTenantDb(guildId); - if (isGuildCreated) { - await fetchMembers(connection, client, guildId); - await fetchRoles(connection, client, guildId); - await fetchChannels(connection, client, guildId); - } else { - await guildExtraction(connection, client, guildId); + const platformId = saga.data['platformId']; + const platform = await platformService.getPlatform({ _id: platformId }); + console.log(platform) + + if (platform) { + const isPlatformCreated = saga.data['created']; + const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); + if (isPlatformCreated) { + await fetchMembers(connection, client, platform); + await fetchRoles(connection, client, platform); + await fetchChannels(connection, client, platform); + } else { + await guildExtraction(connection, client, platform); + } } + logger.info({ msg }, 'fetchMethod is done'); }; @@ -89,11 +98,11 @@ const notifyUserAboutAnalysisFinish = async ( } }; -const fetchInitialData = async (guildId: Snowflake) => { - const connection = DatabaseManager.getInstance().getTenantDb(guildId); - await fetchRoles(connection, client, guildId); - await fetchChannels(connection, client, guildId); - await fetchMembers(connection, client, guildId); +const fetchInitialData = async (platform: HydratedDocument) => { + const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); + await fetchRoles(connection, client, platform); + await fetchChannels(connection, client, platform); + await fetchMembers(connection, client, platform); }; // APP @@ -137,13 +146,16 @@ async function app() { const { content } = msg; const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const guildId = saga.data['guildId']; - const discordId = saga.data['discordId']; + const platformId = saga.data['platformId']; + const platform = await platformService.getPlatform({ _id: platformId }); const discordId = saga.data['discordId']; const message = saga.data['message']; const useFallback = saga.data['useFallback']; - const fn = notifyUserAboutAnalysisFinish.bind({}, discordId, { guildId, message, useFallback }); - await saga.next(fn); + if (platform) { + const fn = notifyUserAboutAnalysisFinish.bind({}, discordId, { guildId: platform.metadata?.id, message, useFallback }); + await saga.next(fn); + } + logger.info({ msg, event: Event.DISCORD_BOT.SEND_MESSAGE }, 'is done'); }); @@ -154,10 +166,14 @@ async function app() { const { content } = msg; const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const guildId = saga.data['guildId']; + const platformId = saga.data['platformId']; - const fn = fetchInitialData.bind({}, guildId); - await saga.next(fn); + const platform = await platformService.getPlatform({ _id: platformId }); + + if (platform) { + const fn = fetchInitialData.bind({}, platform.metadata?.id); + await saga.next(fn); + } logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is done'); }); From 63dd25bbf4d68b6d86b8f187509b92ebbcd79242 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:01:49 +0330 Subject: [PATCH 11/17] [TEST]: remove guild tests --- __tests__/fixtures/guid.fixture.ts | 62 ---------- .../unit/database/services/guild.test.ts | 110 ------------------ 2 files changed, 172 deletions(-) delete mode 100644 __tests__/fixtures/guid.fixture.ts delete mode 100644 __tests__/unit/database/services/guild.test.ts diff --git a/__tests__/fixtures/guid.fixture.ts b/__tests__/fixtures/guid.fixture.ts deleted file mode 100644 index dede6ee0..00000000 --- a/__tests__/fixtures/guid.fixture.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Types } from 'mongoose'; -import { Guild } from '@togethercrew.dev/db'; - -export const guild1 = { - guildId: '123456789', - user: '987654321', - name: 'Guild 1', - _id: new Types.ObjectId(), - selectedChannels: [ - { - channelId: '111111111', - channelName: 'Channel 1', - }, - ], - period: new Date(), - connectedAt: new Date(), - isDisconnected: false, - isInProgress: true, - icon: 'guild1.png', - window: [1, 2], // Update to have 2 numbers - action: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 1], // Update to have 13 numbers -}; - -export const guild2 = { - guildId: '987654321', - user: '987654321', - name: 'Guild 2', - _id: new Types.ObjectId(), - selectedChannels: [ - { - channelId: '333333333', - channelName: 'Channel 3', - }, - ], - connectedAt: new Date(), - isDisconnected: true, - isInProgress: false, - icon: null, - window: [7, 8], // Update to have 2 numbers - action: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 1], // Update to have 13 numbers -}; - -export const guild3 = { - guildId: '567890123', - user: '098765432', - name: 'Guild 3', - _id: new Types.ObjectId(), - selectedChannels: [ - { - channelId: '555555555', - channelName: 'Channel 5', - }, - ], - connectedAt: new Date(), - isDisconnected: false, - isInProgress: true, - icon: 'guild3.png', -}; - -export const insertManyGuilds = async function (guilds: Array) { - await Guild.insertMany(guilds.map((guild) => guild)); -}; diff --git a/__tests__/unit/database/services/guild.test.ts b/__tests__/unit/database/services/guild.test.ts deleted file mode 100644 index 44e32d9b..00000000 --- a/__tests__/unit/database/services/guild.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { Guild, IGuildUpdateBody } from '@togethercrew.dev/db'; -import { guildService } from '../../../../src/database/services'; -import { - insertManyGuilds, - guild1, - guild2, -} from '../../../fixtures/guid.fixture'; -import setupTestDB from '../../../utils/setupTestDB'; - -setupTestDB(); - -describe('guildService', () => { - describe('getGuild', () => { - test('should retrieve an existing guild that matches the filter criteria', async () => { - await insertManyGuilds([guild1]); - const result = await guildService.getGuild({ guildId: guild1.guildId }); - - expect(result).toMatchObject(guild1); - }); - - test('should return null when no guild matches the filter criteria', async () => { - const result = await guildService.getGuild({}); - expect(result).toBeNull(); - }); - }); - - describe('getGuilds', () => { - test('should retrieve an existing guilds that matches the filter criteria', async () => { - await insertManyGuilds([guild1, guild2]); - const result = await guildService.getGuilds({ user: guild1.user }); - - expect(result).toMatchObject([guild1, guild2]); - }); - - test('should return null when no guilds matches the filter criteria', async () => { - const result = await guildService.getGuild({}); - expect(result).toBeNull(); - }); - }); - - describe('updateGuild', () => { - const updateBody: IGuildUpdateBody = { - selectedChannels: [ - { - channelId: '1233123213', - channelName: 'test1', - }, - ], - isDisconnected: false, - }; - test('should update an existing guild that matches the filter criteria', async () => { - await insertManyGuilds([guild1]); - const result = await guildService.updateGuild( - { guildId: guild1.guildId }, - updateBody - ); - - expect(result).toMatchObject({ - id: guild1?._id.toHexString(), - guildId: guild1.guildId, - isDisconnected: updateBody.isDisconnected, - name: guild1.name, - selectedChannels: updateBody.selectedChannels, - }); - - const dbGuild = await Guild.findById(guild1?._id); - expect(dbGuild).toBeDefined(); - expect(dbGuild).toMatchObject({ - isDisconnected: updateBody.isDisconnected, - selectedChannels: updateBody.selectedChannels, - }); - }); - test('should return null when no guild matches the filter criteria', async () => { - const result = await guildService.updateGuild( - { guildId: 'notExistId' }, - updateBody - ); - expect(result).toBeNull(); - }); - }); - - describe('updateGuilds', () => { - const updateBody: IGuildUpdateBody = { - selectedChannels: [ - { - channelId: '14151322', - channelName: 'test2', - }, - ], - isDisconnected: false, - }; - test('should update an existing guilds that matches the filter criteria', async () => { - await insertManyGuilds([guild1, guild2]); - const result = await guildService.updateManyGuilds( - { user: guild1.user }, - updateBody - ); - - expect(result).toBe(2); - }); - test('should return null when no guild matches the filter criteria', async () => { - const result = await guildService.updateManyGuilds( - { guildId: 'notExistId' }, - updateBody - ); - - expect(result).toBe(0); - }); - }); -}); From e6e60e12781313b44dfd03fe3e65e9f6aaf0e641 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Tue, 5 Dec 2023 11:29:17 +0330 Subject: [PATCH 12/17] 1 --- src/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 9de709e9..cc078bf0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -51,7 +51,6 @@ const fetchMethod = async (msg: any) => { logger.info({ saga: saga.data }, 'the saga info'); const platformId = saga.data['platformId']; const platform = await platformService.getPlatform({ _id: platformId }); - console.log(platform) if (platform) { const isPlatformCreated = saga.data['created']; From 5d7e2025eebc4463b275f785a16d6066e6989570 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Tue, 5 Dec 2023 17:42:26 +0330 Subject: [PATCH 13/17] [FIXBUG]: fix bug related to fetch members --- src/events/channel/channelDelete.ts | 1 - src/events/client/ready.ts | 3 --- src/events/user/userUpdate.ts | 3 --- src/functions/cronJon.ts | 1 - src/functions/fetchChannels.ts | 1 - src/functions/fetchMembers.ts | 1 - src/functions/fetchRoles.ts | 1 - src/index.ts | 25 +++++++++++++++---------- 8 files changed, 15 insertions(+), 21 deletions(-) diff --git a/src/events/channel/channelDelete.ts b/src/events/channel/channelDelete.ts index 5db0749a..31b5eb55 100644 --- a/src/events/channel/channelDelete.ts +++ b/src/events/channel/channelDelete.ts @@ -3,7 +3,6 @@ import { channelService, platformService } from '../../database/services'; import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; -console.log('FLAG') const logger = parentLogger.child({ event: 'ChannelDelete' }); export default { diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index c953ba14..1bdd38b5 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -6,9 +6,6 @@ import fetchRoles from '../../functions/fetchRoles'; import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; -console.log('FLAG') - - const logger = parentLogger.child({ event: 'ClientReady' }); export default { diff --git a/src/events/user/userUpdate.ts b/src/events/user/userUpdate.ts index 626a1b67..b92b003c 100644 --- a/src/events/user/userUpdate.ts +++ b/src/events/user/userUpdate.ts @@ -3,9 +3,6 @@ import { guildMemberService, platformService } from '../../database/services'; import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; -console.log('FLAG') - - const logger = parentLogger.child({ event: 'UserUpdate' }); export default { name: Events.UserUpdate, diff --git a/src/functions/cronJon.ts b/src/functions/cronJon.ts index bc8438dc..e9cda21f 100644 --- a/src/functions/cronJon.ts +++ b/src/functions/cronJon.ts @@ -5,7 +5,6 @@ import { ChoreographyDict, MBConnection, Status } from '@togethercrew.dev/tc-mes import guildExtraction from './guildExtraction'; import parentLogger from '../config/logger'; import { DatabaseManager } from '@togethercrew.dev/db'; -console.log('FLAG') const logger = parentLogger.child({ event: 'CronJob' }); diff --git a/src/functions/fetchChannels.ts b/src/functions/fetchChannels.ts index 55600adc..dc08145c 100644 --- a/src/functions/fetchChannels.ts +++ b/src/functions/fetchChannels.ts @@ -3,7 +3,6 @@ import { Connection, HydratedDocument } from 'mongoose'; import { IPlatform, IChannel } from '@togethercrew.dev/db'; import { channelService, platformService } from '../database/services'; import parentLogger from '../config/logger'; -console.log('FLAG') const logger = parentLogger.child({ module: 'FetchChannels' }); diff --git a/src/functions/fetchMembers.ts b/src/functions/fetchMembers.ts index dc01d50d..8ef2d943 100644 --- a/src/functions/fetchMembers.ts +++ b/src/functions/fetchMembers.ts @@ -5,7 +5,6 @@ import { IGuildMember, } from '@togethercrew.dev/db'; import { guildMemberService, platformService } from '../database/services'; import parentLogger from '../config/logger'; -console.log('FLAG') const logger = parentLogger.child({ module: 'FetchMembers' }); diff --git a/src/functions/fetchRoles.ts b/src/functions/fetchRoles.ts index 38dcedc1..137259b7 100644 --- a/src/functions/fetchRoles.ts +++ b/src/functions/fetchRoles.ts @@ -4,7 +4,6 @@ import { IPlatform, IRole } from '@togethercrew.dev/db'; import { roleService, platformService } from '../database/services'; import parentLogger from '../config/logger'; -console.log('FLAG') const logger = parentLogger.child({ module: 'FetchRoles' }); diff --git a/src/index.ts b/src/index.ts index cc078bf0..8e358ecc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -159,21 +159,26 @@ async function app() { }); RabbitMQ.onEvent(Event.DISCORD_BOT.FETCH_MEMBERS, async msg => { - logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is running'); - if (!msg) return; + try { + logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is running'); + if (!msg) return; - const { content } = msg; - const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); + const { content } = msg; + const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const platformId = saga.data['platformId']; + const platformId = saga.data['platformId']; - const platform = await platformService.getPlatform({ _id: platformId }); + const platform = await platformService.getPlatform({ _id: platformId }); - if (platform) { - const fn = fetchInitialData.bind({}, platform.metadata?.id); - await saga.next(fn); + if (platform) { + const fn = fetchInitialData.bind({}, platform); + await saga.next(fn); + } + logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is done'); + } catch (error) { + logger.error({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS, error }, 'is failed'); } - logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is done'); + }); // *****************************BULLMQ From 73e9664abe134f54b2fb02fb1b5055b7d326b5b1 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Tue, 5 Dec 2023 18:45:50 +0330 Subject: [PATCH 14/17] [DEBUG] --- src/functions/fetchChannels.ts | 5 +++++ src/functions/fetchMembers.ts | 4 ++++ src/functions/fetchRoles.ts | 4 ++++ src/index.ts | 38 ++++++++++++++++++++++++---------- 4 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/functions/fetchChannels.ts b/src/functions/fetchChannels.ts index dc08145c..cb701c96 100644 --- a/src/functions/fetchChannels.ts +++ b/src/functions/fetchChannels.ts @@ -30,7 +30,10 @@ function pushChannelsToArray( */ export default async function fetchGuildChannels(connection: Connection, client: Client, platform: HydratedDocument) { try { + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + logger.info({ hasBotAccessToGuild, guildId: platform.metadata?.id, type: 'channel' }) + if (!hasBotAccessToGuild) { return; } @@ -40,6 +43,8 @@ export default async function fetchGuildChannels(connection: Connection, client: channel => channel.type === 0 || channel.type === 2 || channel.type === 4 ) as Array; pushChannelsToArray(channelsToStore, textAndVoiceChannels); + logger.info({ channels: channelsToStore }) + await channelService.createChannels(connection, channelsToStore); // assuming a 'channelService' } catch (error) { logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch channels'); diff --git a/src/functions/fetchMembers.ts b/src/functions/fetchMembers.ts index 8ef2d943..c5416a76 100644 --- a/src/functions/fetchMembers.ts +++ b/src/functions/fetchMembers.ts @@ -31,6 +31,8 @@ function pushMembersToArray(arr: IGuildMember[], guildMembersArray: GuildMember[ export default async function fetchGuildMembers(connection: Connection, client: Client, platform: HydratedDocument) { try { const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + logger.info({ hasBotAccessToGuild, guildId: platform.metadata?.id, type: 'guild member' }) + if (!hasBotAccessToGuild) { return; } @@ -38,6 +40,8 @@ export default async function fetchGuildMembers(connection: Connection, client: const membersToStore: IGuildMember[] = []; const fetchMembers = await guild.members.fetch(); pushMembersToArray(membersToStore, [...fetchMembers.values()]); + logger.info({ members: membersToStore }) + await guildMemberService.createGuildMembers(connection, membersToStore); } catch (error) { logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch guild members'); diff --git a/src/functions/fetchRoles.ts b/src/functions/fetchRoles.ts index 137259b7..e15a64c3 100644 --- a/src/functions/fetchRoles.ts +++ b/src/functions/fetchRoles.ts @@ -29,12 +29,16 @@ function pushRolesToArray(arr: IRole[], roleArray: Role[]): IRole[] { export default async function fetchGuildRoles(connection: Connection, client: Client, platform: HydratedDocument) { try { const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + logger.info({ hasBotAccessToGuild, guildId: platform.metadata?.id, type: 'role' }) + if (!hasBotAccessToGuild) { return; } const guild = await client.guilds.fetch(platform.metadata?.id); const rolesToStore: IRole[] = []; pushRolesToArray(rolesToStore, [...guild.roles.cache.values()]); + logger.info({ roles: rolesToStore }) + await roleService.createRoles(connection, rolesToStore); } catch (error) { logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch roles'); diff --git a/src/index.ts b/src/index.ts index 2ac0fb8d..55da3b48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,6 +44,8 @@ const partial = func(...args, ...rest); const fetchMethod = async (msg: any) => { + + console.log(11) logger.info({ msg }, 'fetchMethod is running'); if (!msg) return; const { content } = msg; @@ -51,6 +53,8 @@ const fetchMethod = async (msg: any) => { logger.info({ saga: saga.data }, 'the saga info'); const platformId = saga.data['platformId']; const platform = await platformService.getPlatform({ _id: platformId }); + console.log(saga) + console.log(platform) if (platform) { const isPlatformCreated = saga.data['created']; @@ -98,10 +102,15 @@ const notifyUserAboutAnalysisFinish = async ( }; const fetchInitialData = async (platform: HydratedDocument) => { - const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); - await fetchRoles(connection, client, platform); - await fetchChannels(connection, client, platform); - await fetchMembers(connection, client, platform); + try { + const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); + await fetchRoles(connection, client, platform); + await fetchChannels(connection, client, platform); + await fetchMembers(connection, client, platform); + } catch (error) { + logger.error({ error }, 'fetchInitialData is failed'); + } + }; // APP @@ -127,15 +136,20 @@ async function app() { ); RabbitMQ.onEvent(Event.DISCORD_BOT.FETCH, async msg => { - logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is running'); - if (!msg) return; + try { + logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is running'); + if (!msg) return; - const { content } = msg; - const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); + const { content } = msg; + const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const fn = partial(fetchMethod, msg); - await saga.next(fn); - logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is done'); + const fn = partial(fetchMethod, msg); + await saga.next(fn); + logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is done'); + } catch (error) { + logger.error({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS, error }, 'is failed'); + + } }); RabbitMQ.onEvent(Event.DISCORD_BOT.SEND_MESSAGE, async msg => { @@ -170,7 +184,9 @@ async function app() { const platform = await platformService.getPlatform({ _id: platformId }); + logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS, platform, platformId }) if (platform) { + logger.info({ event: "FETCHING Initial DATA" }) const fn = fetchInitialData.bind({}, platform); await saga.next(fn); } From db29ed0a96cb78d352b31e18e52dddd3c5fef354 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Wed, 6 Dec 2023 16:59:01 +0330 Subject: [PATCH 15/17] [DEBUG] --- src/functions/fetchChannels.ts | 1 - src/functions/fetchMembers.ts | 2 -- src/functions/fetchRoles.ts | 2 -- src/index.ts | 7 ++----- 4 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/functions/fetchChannels.ts b/src/functions/fetchChannels.ts index cb701c96..33b27e4b 100644 --- a/src/functions/fetchChannels.ts +++ b/src/functions/fetchChannels.ts @@ -44,7 +44,6 @@ export default async function fetchGuildChannels(connection: Connection, client: ) as Array; pushChannelsToArray(channelsToStore, textAndVoiceChannels); logger.info({ channels: channelsToStore }) - await channelService.createChannels(connection, channelsToStore); // assuming a 'channelService' } catch (error) { logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch channels'); diff --git a/src/functions/fetchMembers.ts b/src/functions/fetchMembers.ts index c5416a76..0bd981e0 100644 --- a/src/functions/fetchMembers.ts +++ b/src/functions/fetchMembers.ts @@ -40,8 +40,6 @@ export default async function fetchGuildMembers(connection: Connection, client: const membersToStore: IGuildMember[] = []; const fetchMembers = await guild.members.fetch(); pushMembersToArray(membersToStore, [...fetchMembers.values()]); - logger.info({ members: membersToStore }) - await guildMemberService.createGuildMembers(connection, membersToStore); } catch (error) { logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch guild members'); diff --git a/src/functions/fetchRoles.ts b/src/functions/fetchRoles.ts index e15a64c3..6c1b46ba 100644 --- a/src/functions/fetchRoles.ts +++ b/src/functions/fetchRoles.ts @@ -37,8 +37,6 @@ export default async function fetchGuildRoles(connection: Connection, client: Cl const guild = await client.guilds.fetch(platform.metadata?.id); const rolesToStore: IRole[] = []; pushRolesToArray(rolesToStore, [...guild.roles.cache.values()]); - logger.info({ roles: rolesToStore }) - await roleService.createRoles(connection, rolesToStore); } catch (error) { logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch roles'); diff --git a/src/index.ts b/src/index.ts index 55da3b48..464f5b1d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,9 +60,9 @@ const fetchMethod = async (msg: any) => { const isPlatformCreated = saga.data['created']; const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); if (isPlatformCreated) { + await fetchChannels(connection, client, platform); await fetchMembers(connection, client, platform); await fetchRoles(connection, client, platform); - await fetchChannels(connection, client, platform); } else { await guildExtraction(connection, client, platform); } @@ -104,13 +104,12 @@ const notifyUserAboutAnalysisFinish = async ( const fetchInitialData = async (platform: HydratedDocument) => { try { const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); - await fetchRoles(connection, client, platform); await fetchChannels(connection, client, platform); + await fetchRoles(connection, client, platform); await fetchMembers(connection, client, platform); } catch (error) { logger.error({ error }, 'fetchInitialData is failed'); } - }; // APP @@ -184,9 +183,7 @@ async function app() { const platform = await platformService.getPlatform({ _id: platformId }); - logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS, platform, platformId }) if (platform) { - logger.info({ event: "FETCHING Initial DATA" }) const fn = fetchInitialData.bind({}, platform); await saga.next(fn); } From dc994aeb7d81c263dcc033d889da099d8a40e5ff Mon Sep 17 00:00:00 2001 From: Behzad Rabiei Date: Fri, 8 Dec 2023 09:40:29 +0400 Subject: [PATCH 16/17] [FIXBUG]: fix channel permissions checker --- package-lock.json | 8 ++++---- package.json | 2 +- src/index.ts | 4 ---- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index 45df096c..b3cbcb27 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "ISC", "dependencies": { "@sentry/node": "^7.51.2", - "@togethercrew.dev/db": "^3.0.16", + "@togethercrew.dev/db": "^3.0.18", "@togethercrew.dev/tc-messagebroker": "^0.0.40", "babel-jest": "^29.5.0", "bullmq": "^3.14.0", @@ -3038,9 +3038,9 @@ } }, "node_modules/@togethercrew.dev/db": { - "version": "3.0.16", - "resolved": "https://registry.npmjs.org/@togethercrew.dev/db/-/db-3.0.16.tgz", - "integrity": "sha512-HzvK7ckkdNzpRhlj/94D1GLPUZqZGyozcZfkz2vN25mByMDe+NPE/IC2LK8RlcdZHLRjlUiyvfsbv+7+h9iqcA==", + "version": "3.0.18", + "resolved": "https://registry.npmjs.org/@togethercrew.dev/db/-/db-3.0.18.tgz", + "integrity": "sha512-LIGkRnChhja1hnHnVk9qfaZXfCoruUsYVtMvt2v4IOzFLvUt6DeVqvrvSheK5yf63ikkwdiQMLyx62WNLbtUmw==", "dependencies": { "discord.js": "^14.7.1", "joi": "^17.7.0", diff --git a/package.json b/package.json index ee20b1d3..c58495ab 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "homepage": "https://github.com/Behzad-rabiei/tc-discordBot#readme", "dependencies": { "@sentry/node": "^7.51.2", - "@togethercrew.dev/db": "^3.0.16", + "@togethercrew.dev/db": "^3.0.18", "@togethercrew.dev/tc-messagebroker": "^0.0.40", "babel-jest": "^29.5.0", "bullmq": "^3.14.0", diff --git a/src/index.ts b/src/index.ts index 464f5b1d..cfe29625 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,7 +45,6 @@ const partial = const fetchMethod = async (msg: any) => { - console.log(11) logger.info({ msg }, 'fetchMethod is running'); if (!msg) return; const { content } = msg; @@ -53,8 +52,6 @@ const fetchMethod = async (msg: any) => { logger.info({ saga: saga.data }, 'the saga info'); const platformId = saga.data['platformId']; const platform = await platformService.getPlatform({ _id: platformId }); - console.log(saga) - console.log(platform) if (platform) { const isPlatformCreated = saga.data['created']; @@ -67,7 +64,6 @@ const fetchMethod = async (msg: any) => { await guildExtraction(connection, client, platform); } } - logger.info({ msg }, 'fetchMethod is done'); }; From ea68aec566c974ad8e5616bf4711380133f01327 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Fri, 22 Dec 2023 13:09:49 +0330 Subject: [PATCH 17/17] [REFACTOR]: fix naming --- src/config/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/config/index.ts b/src/config/index.ts index 0168e183..ace3287e 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -12,7 +12,7 @@ const envVarsSchema = Joi.object() RABBIT_PORT: Joi.string().required().description('RabbitMQ port'), RABBIT_USER: Joi.string().required().description('RabbitMQ username'), RABBIT_PASSWORD: Joi.string().required().description('RabbitMQ password'), - DISCROD_CLIENT_ID: Joi.string().required().description('Discord clinet id'), + DISCORD_CLIENT_ID: Joi.string().required().description('Discord clinet id'), DISCORD_CLIENT_SECRET: Joi.string().required().description('Discord clinet secret'), DISCORD_BOT_TOKEN: Joi.string().required().description('Discord bot token'), SENTRY_DSN: Joi.string().required().description('Sentry DSN'), @@ -44,7 +44,7 @@ export default { url: `amqp://${envVars.RABBIT_USER}:${envVars.RABBIT_PASSWORD}@${envVars.RABBIT_HOST}:${envVars.RABBIT_PORT}`, }, discord: { - clientId: envVars.DISCROD_CLIENT_ID, + clientId: envVars.DISCORD_CLIENT_ID, clientSecret: envVars.DISCORD_CLIENT_SECRET, botToken: envVars.DISCORD_BOT_TOKEN, },